sampling.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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, adaptive_target = %.3f, adaptive_decay = %.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, adaptive_target, adaptive_decay);
  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. bool use_adaptive_p = false; // see below
  217. for (const auto & cnstr : params.samplers) {
  218. switch (cnstr) {
  219. case COMMON_SAMPLER_TYPE_DRY:
  220. {
  221. std::vector<const char *> c_breakers;
  222. c_breakers.reserve(params.dry_sequence_breakers.size());
  223. for (const auto & str : params.dry_sequence_breakers) {
  224. c_breakers.push_back(str.c_str());
  225. }
  226. 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()));
  227. }
  228. break;
  229. case COMMON_SAMPLER_TYPE_TOP_K:
  230. samplers.push_back(llama_sampler_init_top_k(params.top_k));
  231. break;
  232. case COMMON_SAMPLER_TYPE_TOP_P:
  233. samplers.push_back(llama_sampler_init_top_p(params.top_p, params.min_keep));
  234. break;
  235. case COMMON_SAMPLER_TYPE_TOP_N_SIGMA:
  236. samplers.push_back(llama_sampler_init_top_n_sigma(params.top_n_sigma));
  237. break;
  238. case COMMON_SAMPLER_TYPE_MIN_P:
  239. samplers.push_back(llama_sampler_init_min_p(params.min_p, params.min_keep));
  240. break;
  241. case COMMON_SAMPLER_TYPE_XTC:
  242. samplers.push_back(llama_sampler_init_xtc(params.xtc_probability, params.xtc_threshold, params.min_keep, params.seed));
  243. break;
  244. case COMMON_SAMPLER_TYPE_TYPICAL_P:
  245. samplers.push_back(llama_sampler_init_typical(params.typ_p, params.min_keep));
  246. break;
  247. case COMMON_SAMPLER_TYPE_TEMPERATURE:
  248. samplers.push_back(llama_sampler_init_temp_ext(params.temp, params.dynatemp_range, params.dynatemp_exponent));
  249. break;
  250. case COMMON_SAMPLER_TYPE_INFILL:
  251. samplers.push_back(llama_sampler_init_infill(vocab));
  252. break;
  253. case COMMON_SAMPLER_TYPE_PENALTIES:
  254. samplers.push_back(llama_sampler_init_penalties(params.penalty_last_n, params.penalty_repeat, params.penalty_freq, params.penalty_present));
  255. break;
  256. case COMMON_SAMPLER_TYPE_ADAPTIVE_P:
  257. // the `adaptive-p` sampler is like `dist` and `mirostat` in that it selects
  258. // a single token, so we will add `dist` at the end of the chain by default,
  259. // unless the user specifically included `adaptive-p`. we set this flag here
  260. // so we know to add the sampler at the very end.
  261. use_adaptive_p = true;
  262. break;
  263. default:
  264. GGML_ASSERT(false && "unknown sampler type");
  265. }
  266. }
  267. if (use_adaptive_p) {
  268. // only if user explicitly included adaptive-p sampler
  269. samplers.push_back(llama_sampler_init_adaptive_p(params.adaptive_target, params.adaptive_decay, params.seed));
  270. } else {
  271. // default: sample from distribution
  272. samplers.push_back(llama_sampler_init_dist(params.seed));
  273. }
  274. } else if (params.mirostat == 1) {
  275. samplers.push_back(llama_sampler_init_temp(params.temp));
  276. samplers.push_back(llama_sampler_init_mirostat(llama_vocab_n_tokens(vocab), params.seed, params.mirostat_tau, params.mirostat_eta, 100));
  277. } else if (params.mirostat == 2) {
  278. samplers.push_back(llama_sampler_init_temp(params.temp));
  279. samplers.push_back(llama_sampler_init_mirostat_v2(params.seed, params.mirostat_tau, params.mirostat_eta));
  280. } else {
  281. GGML_ASSERT(false && "unknown mirostat version");
  282. }
  283. for (auto * smpl : samplers) {
  284. llama_sampler_chain_add(chain, smpl);
  285. }
  286. if (grmr && params.backend_sampling) {
  287. LOG_WRN("%s: backend sampling is not compatible with grammar, disabling\n", __func__);
  288. params.backend_sampling = false;
  289. }
  290. auto * result = new common_sampler {
  291. /* .params = */ params,
  292. /* .grmr = */ grmr,
  293. /* .chain = */ chain,
  294. /* .prev = */ ring_buffer<llama_token>(std::max(32, params.n_prev)),
  295. /* .cur = */ {},
  296. /* .cur_p = */ {},
  297. };
  298. return result;
  299. }
  300. void common_sampler_free(struct common_sampler * gsmpl) {
  301. if (!gsmpl) {
  302. return;
  303. }
  304. llama_sampler_free(gsmpl->grmr);
  305. llama_sampler_free(gsmpl->chain);
  306. delete gsmpl;
  307. }
  308. void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, bool accept_grammar) {
  309. if (!gsmpl) {
  310. return;
  311. }
  312. const auto tm = gsmpl->tm();
  313. if (gsmpl->grmr && accept_grammar) {
  314. llama_sampler_accept(gsmpl->grmr, token);
  315. }
  316. llama_sampler_accept(gsmpl->chain, token);
  317. gsmpl->prev.push_back(token);
  318. }
  319. void common_sampler_reset(struct common_sampler * gsmpl) {
  320. if (!gsmpl) {
  321. return;
  322. }
  323. gsmpl->reset();
  324. }
  325. struct common_sampler * common_sampler_clone(common_sampler * gsmpl) {
  326. return new common_sampler {
  327. /* .params = */ gsmpl->params,
  328. /* .grmr = */ llama_sampler_clone(gsmpl->grmr),
  329. /* .chain = */ llama_sampler_clone(gsmpl->chain),
  330. /* .prev = */ gsmpl->prev,
  331. /* .cur = */ gsmpl->cur,
  332. /* .cur_p = */ gsmpl->cur_p,
  333. };
  334. }
  335. void common_perf_print(const struct llama_context * ctx, const struct common_sampler * gsmpl) {
  336. // TODO: measure grammar performance
  337. const double t_sampling_ms = gsmpl ? 1e-3*gsmpl->t_total_us : 0;
  338. llama_perf_sampler_data data_smpl;
  339. llama_perf_context_data data_ctx;
  340. memset(&data_smpl, 0, sizeof(data_smpl));
  341. memset(&data_ctx, 0, sizeof(data_ctx));
  342. if (gsmpl) {
  343. auto & data = data_smpl;
  344. data = llama_perf_sampler(gsmpl->chain);
  345. // note: the sampling time includes the samplers time + extra time spent in common/sampling
  346. LOG_INF("%s: sampling time = %10.2f ms\n", __func__, t_sampling_ms);
  347. LOG_INF("%s: samplers time = %10.2f ms / %5d tokens\n", __func__, data.t_sample_ms, data.n_sample);
  348. }
  349. if (ctx) {
  350. auto & data = data_ctx;
  351. data = llama_perf_context(ctx);
  352. const double t_end_ms = 1e-3 * ggml_time_us();
  353. const double t_total_ms = t_end_ms - data.t_start_ms;
  354. const double t_unacc_ms = t_total_ms - (t_sampling_ms + data.t_p_eval_ms + data.t_eval_ms);
  355. const double t_unacc_pc = 100.0 * t_unacc_ms / t_total_ms;
  356. LOG_INF("%s: load time = %10.2f ms\n", __func__, data.t_load_ms);
  357. LOG_INF("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  358. __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);
  359. LOG_INF("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  360. __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
  361. 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));
  362. LOG_INF("%s: unaccounted time = %10.2f ms / %5.1f %% (total - sampling - prompt eval - eval) / (total)\n", __func__, t_unacc_ms, t_unacc_pc);
  363. LOG_INF("%s: graphs reused = %10d\n", __func__, data.n_reused);
  364. llama_memory_breakdown_print(ctx);
  365. }
  366. }
  367. struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl) {
  368. if (!gsmpl) {
  369. return nullptr;
  370. }
  371. return gsmpl->chain;
  372. }
  373. llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) {
  374. llama_synchronize(ctx);
  375. // start measuring sampling time after the llama_context synchronization in order to not measure any ongoing async operations
  376. const auto tm = gsmpl->tm();
  377. llama_token id = LLAMA_TOKEN_NULL;
  378. auto & grmr = gsmpl->grmr;
  379. auto & chain = gsmpl->chain;
  380. auto & cur_p = gsmpl->cur_p; // initialized by set_logits
  381. // Check if a backend sampler has already sampled a token in which case we
  382. // return that token id directly.
  383. {
  384. id = llama_get_sampled_token_ith(ctx, idx);
  385. if (id != LLAMA_TOKEN_NULL) {
  386. LOG_DBG("%s: Backend sampler selected token: '%d'. Will not run any CPU samplers\n", __func__, id);
  387. GGML_ASSERT(!gsmpl->grmr && "using grammar in combination with backend sampling is not supported");
  388. // TODO: simplify
  389. gsmpl->cur.resize(1);
  390. gsmpl->cur[0] = { id, 0.0f, 1.0f };
  391. cur_p = { gsmpl->cur.data(), gsmpl->cur.size(), 0, true };
  392. return id;
  393. }
  394. }
  395. gsmpl->set_logits(ctx, idx);
  396. if (grammar_first) {
  397. llama_sampler_apply(grmr, &cur_p);
  398. }
  399. llama_sampler_apply(chain, &cur_p);
  400. id = cur_p.data[cur_p.selected].id;
  401. if (grammar_first) {
  402. return id;
  403. }
  404. // check if it the sampled token fits the grammar (grammar-based rejection sampling)
  405. {
  406. llama_token_data single_token_data = { id, 1.0f, 0.0f };
  407. llama_token_data_array single_token_data_array = { &single_token_data, 1, -1, false };
  408. llama_sampler_apply(grmr, &single_token_data_array);
  409. const bool is_valid = single_token_data_array.data[0].logit != -INFINITY;
  410. if (is_valid) {
  411. return id;
  412. }
  413. }
  414. // resampling:
  415. // if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain
  416. gsmpl->set_logits(ctx, idx);
  417. llama_sampler_apply(grmr, &cur_p);
  418. llama_sampler_apply(chain, &cur_p);
  419. GGML_ASSERT(cur_p.selected != -1 && "no selected token during sampling - check your sampling configuration");
  420. id = cur_p.data[cur_p.selected].id;
  421. return id;
  422. }
  423. 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) {
  424. GGML_ASSERT(idxs.size() == draft.size() + 1 && "idxs.size() must be draft.size() + 1");
  425. std::vector<llama_token> result;
  426. result.reserve(idxs.size());
  427. size_t i = 0;
  428. for (; i < draft.size(); i++) {
  429. const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
  430. common_sampler_accept(gsmpl, id, true);
  431. result.push_back(id);
  432. if (draft[i] != id) {
  433. break;
  434. }
  435. }
  436. if (i == draft.size()) {
  437. const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
  438. common_sampler_accept(gsmpl, id, true);
  439. result.push_back(id);
  440. }
  441. return result;
  442. }
  443. 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) {
  444. std::vector<int> idxs(draft.size() + 1);
  445. for (size_t i = 0; i < idxs.size(); ++i) {
  446. idxs[i] = i;
  447. }
  448. return common_sampler_sample_and_accept_n(gsmpl, ctx, idxs, draft, grammar_first);
  449. }
  450. uint32_t common_sampler_get_seed(const struct common_sampler * gsmpl) {
  451. return llama_sampler_get_seed(gsmpl->chain);
  452. }
  453. // helpers
  454. llama_token_data_array * common_sampler_get_candidates(struct common_sampler * gsmpl, bool do_sort) {
  455. const auto tm = gsmpl->tm();
  456. auto * res = &gsmpl->cur_p;
  457. if (do_sort && !res->sorted) {
  458. // remember the selected token before sorting
  459. const llama_token id = res->data[res->selected].id;
  460. std::sort(res->data, res->data + res->size, [](const llama_token_data & a, const llama_token_data & b) {
  461. return a.p > b.p;
  462. });
  463. // restore the selected token after sorting
  464. for (size_t i = 0; i < res->size; ++i) {
  465. if (res->data[i].id == id) {
  466. res->selected = i;
  467. break;
  468. }
  469. }
  470. res->sorted = true;
  471. }
  472. return res;
  473. }
  474. llama_token common_sampler_last(const struct common_sampler * gsmpl) {
  475. return gsmpl->prev.rat(0);
  476. }
  477. std::string common_sampler_print(const struct common_sampler * gsmpl) {
  478. std::string result = "logits ";
  479. for (int i = 0; i < llama_sampler_chain_n(gsmpl->chain); i++) {
  480. const auto * smpl = llama_sampler_chain_get(gsmpl->chain, i);
  481. result += std::string("-> ");
  482. result += std::string(llama_sampler_name(smpl)) + " ";
  483. }
  484. return result;
  485. }
  486. std::string common_sampler_prev_str(common_sampler * gsmpl, llama_context * ctx_main, int n) {
  487. n = std::min(n, (int) gsmpl->prev.size());
  488. if (n <= 0) {
  489. return "";
  490. }
  491. std::string result;
  492. result.reserve(8*n); // 8 is the average length of a token [citation needed], TODO: compute this from the vocab
  493. for (int i = n - 1; i >= 0; i--) {
  494. const llama_token id = gsmpl->prev.rat(i);
  495. GGML_ASSERT(id != LLAMA_TOKEN_NULL && "null token in the sampling history - should not happen");
  496. result += common_token_to_piece(ctx_main, id);
  497. }
  498. return result;
  499. }
  500. char common_sampler_type_to_chr(enum common_sampler_type cnstr) {
  501. switch (cnstr) {
  502. case COMMON_SAMPLER_TYPE_DRY: return 'd';
  503. case COMMON_SAMPLER_TYPE_TOP_K: return 'k';
  504. case COMMON_SAMPLER_TYPE_TYPICAL_P: return 'y';
  505. case COMMON_SAMPLER_TYPE_TOP_P: return 'p';
  506. case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: return 's';
  507. case COMMON_SAMPLER_TYPE_MIN_P: return 'm';
  508. case COMMON_SAMPLER_TYPE_TEMPERATURE: return 't';
  509. case COMMON_SAMPLER_TYPE_XTC: return 'x';
  510. case COMMON_SAMPLER_TYPE_INFILL: return 'i';
  511. case COMMON_SAMPLER_TYPE_PENALTIES: return 'e';
  512. case COMMON_SAMPLER_TYPE_ADAPTIVE_P: return 'a';
  513. default : return '?';
  514. }
  515. }
  516. std::string common_sampler_type_to_str(enum common_sampler_type cnstr) {
  517. switch (cnstr) {
  518. case COMMON_SAMPLER_TYPE_DRY: return "dry";
  519. case COMMON_SAMPLER_TYPE_TOP_K: return "top_k";
  520. case COMMON_SAMPLER_TYPE_TYPICAL_P: return "typ_p";
  521. case COMMON_SAMPLER_TYPE_TOP_P: return "top_p";
  522. case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: return "top_n_sigma";
  523. case COMMON_SAMPLER_TYPE_MIN_P: return "min_p";
  524. case COMMON_SAMPLER_TYPE_TEMPERATURE: return "temperature";
  525. case COMMON_SAMPLER_TYPE_XTC: return "xtc";
  526. case COMMON_SAMPLER_TYPE_INFILL: return "infill";
  527. case COMMON_SAMPLER_TYPE_PENALTIES: return "penalties";
  528. case COMMON_SAMPLER_TYPE_ADAPTIVE_P: return "adaptive_p";
  529. default : return "";
  530. }
  531. }
  532. std::vector<common_sampler_type> common_sampler_types_from_names(const std::vector<std::string> & names, bool allow_alt_names) {
  533. std::unordered_map<std::string, common_sampler_type> sampler_canonical_name_map {
  534. { "dry", COMMON_SAMPLER_TYPE_DRY },
  535. { "top_k", COMMON_SAMPLER_TYPE_TOP_K },
  536. { "top_p", COMMON_SAMPLER_TYPE_TOP_P },
  537. { "top_n_sigma", COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
  538. { "typ_p", COMMON_SAMPLER_TYPE_TYPICAL_P },
  539. { "min_p", COMMON_SAMPLER_TYPE_MIN_P },
  540. { "temperature", COMMON_SAMPLER_TYPE_TEMPERATURE },
  541. { "xtc", COMMON_SAMPLER_TYPE_XTC },
  542. { "infill", COMMON_SAMPLER_TYPE_INFILL },
  543. { "penalties", COMMON_SAMPLER_TYPE_PENALTIES },
  544. { "adaptive_p", COMMON_SAMPLER_TYPE_ADAPTIVE_P },
  545. };
  546. // since samplers names are written multiple ways
  547. // make it ready for both system names and input names
  548. std::unordered_map<std::string, common_sampler_type> sampler_alt_name_map {
  549. { "top-k", COMMON_SAMPLER_TYPE_TOP_K },
  550. { "top-p", COMMON_SAMPLER_TYPE_TOP_P },
  551. { "top-n-sigma", COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
  552. { "nucleus", COMMON_SAMPLER_TYPE_TOP_P },
  553. { "typical-p", COMMON_SAMPLER_TYPE_TYPICAL_P },
  554. { "typical", COMMON_SAMPLER_TYPE_TYPICAL_P },
  555. { "typ-p", COMMON_SAMPLER_TYPE_TYPICAL_P },
  556. { "typ", COMMON_SAMPLER_TYPE_TYPICAL_P },
  557. { "min-p", COMMON_SAMPLER_TYPE_MIN_P },
  558. { "temp", COMMON_SAMPLER_TYPE_TEMPERATURE },
  559. { "adaptive-p", COMMON_SAMPLER_TYPE_ADAPTIVE_P },
  560. };
  561. std::vector<common_sampler_type> samplers;
  562. samplers.reserve(names.size());
  563. for (const auto & name : names) {
  564. auto sampler = sampler_canonical_name_map.find(name);
  565. if (sampler != sampler_canonical_name_map.end()) {
  566. samplers.push_back(sampler->second);
  567. continue;
  568. }
  569. if (allow_alt_names) {
  570. sampler = sampler_alt_name_map.find(name);
  571. if (sampler != sampler_alt_name_map.end()) {
  572. samplers.push_back(sampler->second);
  573. continue;
  574. }
  575. }
  576. LOG_WRN("%s: unable to match sampler by name '%s'\n", __func__, name.c_str());
  577. }
  578. return samplers;
  579. }
  580. std::vector<common_sampler_type> common_sampler_types_from_chars(const std::string & chars) {
  581. std::unordered_map<char, common_sampler_type> sampler_name_map = {
  582. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_DRY), COMMON_SAMPLER_TYPE_DRY },
  583. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_K), COMMON_SAMPLER_TYPE_TOP_K },
  584. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TYPICAL_P), COMMON_SAMPLER_TYPE_TYPICAL_P },
  585. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_P), COMMON_SAMPLER_TYPE_TOP_P },
  586. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_N_SIGMA), COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
  587. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_MIN_P), COMMON_SAMPLER_TYPE_MIN_P },
  588. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TEMPERATURE), COMMON_SAMPLER_TYPE_TEMPERATURE },
  589. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_XTC), COMMON_SAMPLER_TYPE_XTC },
  590. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_INFILL), COMMON_SAMPLER_TYPE_INFILL },
  591. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_PENALTIES), COMMON_SAMPLER_TYPE_PENALTIES },
  592. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_ADAPTIVE_P), COMMON_SAMPLER_TYPE_ADAPTIVE_P },
  593. };
  594. std::vector<common_sampler_type> samplers;
  595. samplers.reserve(chars.size());
  596. for (const auto & c : chars) {
  597. const auto sampler = sampler_name_map.find(c);
  598. if (sampler != sampler_name_map.end()) {
  599. samplers.push_back(sampler->second);
  600. } else {
  601. LOG_WRN("%s: unable to match sampler by char '%c'\n", __func__, c);
  602. }
  603. }
  604. return samplers;
  605. }