llama-sampling.cpp 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373
  1. /**
  2. * llama.cpp - commit 40c6d79fb52f995f47507fedfeaae2ac05d9b35c - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #include "llama-sampling.h"
  27. #include "llama-vocab.h"
  28. #include "llama-grammar.h"
  29. #include <algorithm>
  30. #include <cassert>
  31. #include <cfloat>
  32. #include <chrono>
  33. #include <cmath>
  34. #include <cstdlib>
  35. #include <cstring>
  36. #include <ctime>
  37. #include <numeric>
  38. #include <random>
  39. #include <unordered_map>
  40. static int llama_sample_dist(llama_token_data_array * cur_p, std::mt19937 & rng) {
  41. // iterator for the probabilities
  42. #ifdef __GNUC__
  43. #pragma GCC diagnostic push
  44. #pragma GCC diagnostic ignored "-Wunused-local-typedefs"
  45. #endif
  46. struct probs_iterator {
  47. typedef std::input_iterator_tag iterator_category;
  48. typedef float value_type;
  49. typedef float * pointer;
  50. typedef float & reference;
  51. typedef ptrdiff_t difference_type;
  52. const llama_token_data * data;
  53. bool operator==(const probs_iterator & other) const { return data == other.data; }
  54. bool operator!=(const probs_iterator & other) const { return data != other.data; }
  55. const float & operator*() const { return data->p; }
  56. probs_iterator & operator++() { ++data; return *this; }
  57. probs_iterator operator++(int) { probs_iterator tmp = *this; ++data; return tmp; }
  58. };
  59. #ifdef __GNUC__
  60. #pragma GCC diagnostic pop
  61. #endif
  62. std::discrete_distribution<int> dist(probs_iterator{cur_p->data}, probs_iterator{cur_p->data + cur_p->size});
  63. return dist(rng);
  64. }
  65. /*
  66. static void llama_log_softmax(float * array, size_t size) {
  67. float max_l = *std::max_element(array, array + size);
  68. float sum = 0.f;
  69. for (size_t i = 0; i < size; ++i) {
  70. float p = expf(array[i] - max_l);
  71. sum += p;
  72. array[i] = p;
  73. }
  74. for (size_t i = 0; i < size; ++i) {
  75. array[i] = logf(array[i] / sum);
  76. }
  77. }
  78. */
  79. static void llama_sampler_temp_impl(llama_token_data_array * cur_p, float temp) {
  80. if (temp <= 0.0f) {
  81. // find the token with the highest logit and set the rest to -inf
  82. size_t max_i = 0;
  83. float max_l = cur_p->data[0].logit;
  84. for (size_t i = 1; i < cur_p->size; ++i) {
  85. if (cur_p->data[i ].logit > max_l) {
  86. cur_p->data[max_i].logit = -INFINITY;
  87. max_i = i;
  88. max_l = cur_p->data[i].logit;
  89. } else {
  90. cur_p->data[i].logit = -INFINITY;
  91. }
  92. }
  93. return;
  94. }
  95. for (size_t i = 0; i < cur_p->size; ++i) {
  96. cur_p->data[i].logit /= temp;
  97. }
  98. }
  99. static void llama_sampler_softmax_impl(llama_token_data_array * cur_p) {
  100. GGML_ASSERT(cur_p->size > 0);
  101. // Sort the logits in descending order
  102. if (!cur_p->sorted) {
  103. std::sort(cur_p->data, cur_p->data + cur_p->size, [](const llama_token_data & a, const llama_token_data & b) {
  104. return a.logit > b.logit;
  105. });
  106. cur_p->sorted = true;
  107. }
  108. float max_l = cur_p->data[0].logit;
  109. float cum_sum = 0.0f;
  110. for (size_t i = 0; i < cur_p->size; ++i) {
  111. float p = expf(cur_p->data[i].logit - max_l);
  112. cur_p->data[i].p = p;
  113. cum_sum += p;
  114. }
  115. for (size_t i = 0; i < cur_p->size; ++i) {
  116. cur_p->data[i].p /= cum_sum;
  117. }
  118. }
  119. static void llama_sampler_top_k_impl(llama_token_data_array * cur_p, int32_t k) {
  120. // TODO: move bucket sort to separate function so that top_p/typical/softmax first is equally fast
  121. // if (k >= (int32_t)cur_p->size) {
  122. // return;
  123. // }
  124. if (k <= 0) {
  125. k = cur_p->size;
  126. }
  127. k = std::min(k, (int) cur_p->size);
  128. // Sort scores in descending order
  129. if (!cur_p->sorted) {
  130. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  131. return a.logit > b.logit;
  132. };
  133. if (k <= 128) {
  134. std::partial_sort(cur_p->data, cur_p->data + k, cur_p->data + cur_p->size, comp);
  135. } else {
  136. constexpr int nbuckets = 128;
  137. constexpr float bucket_low = -10.0f;
  138. constexpr float bucket_high = 10.0f;
  139. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  140. constexpr float bucket_inter = -bucket_low * bucket_scale;
  141. std::vector<int> bucket_idx(cur_p->size);
  142. std::vector<int> histo(nbuckets, 0);
  143. for (int i = 0; i < (int)cur_p->size; ++i) {
  144. const float val = cur_p->data[i].logit;
  145. int ib = int(bucket_scale * val + bucket_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  146. ib = std::max(0, std::min(nbuckets-1, ib));
  147. bucket_idx[i] = ib;
  148. ++histo[ib];
  149. }
  150. int nhave = 0;
  151. int ib = nbuckets - 1;
  152. for ( ; ib >= 0; --ib) {
  153. nhave += histo[ib];
  154. if (nhave >= k) {
  155. break;
  156. }
  157. }
  158. std::vector<llama_token_data> tmp_tokens(nhave);
  159. auto * ptr = tmp_tokens.data();
  160. std::vector<llama_token_data*> bucket_ptrs;
  161. bucket_ptrs.reserve(nbuckets - ib);
  162. for (int j = nbuckets - 1; j >= ib; --j) {
  163. bucket_ptrs.push_back(ptr);
  164. ptr += histo[j];
  165. }
  166. for (int i = 0; i < (int)cur_p->size; ++i) {
  167. int j = bucket_idx[i];
  168. if (j >= ib) {
  169. *bucket_ptrs[nbuckets-1-j]++ = cur_p->data[i];
  170. }
  171. }
  172. ptr = tmp_tokens.data();
  173. int ndone = 0;
  174. for (int j = nbuckets-1; j > ib; --j) {
  175. std::sort(ptr, ptr + histo[j], comp);
  176. ptr += histo[j];
  177. ndone += histo[j];
  178. }
  179. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  180. std::memcpy(cur_p->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  181. }
  182. cur_p->sorted = true;
  183. }
  184. cur_p->size = k;
  185. }
  186. static uint32_t get_rng_seed(uint32_t seed) {
  187. if (seed == LLAMA_DEFAULT_SEED) {
  188. // use system clock if std::random_device is not a true RNG
  189. static bool is_rd_prng = std::random_device().entropy() == 0;
  190. if (is_rd_prng) {
  191. return (uint32_t) std::chrono::system_clock::now().time_since_epoch().count();
  192. }
  193. std::random_device rd;
  194. return rd();
  195. }
  196. return seed;
  197. }
  198. // llama_sampler API
  199. const char * llama_sampler_name(const struct llama_sampler * smpl) {
  200. if (!smpl->iface) {
  201. return "(null)";
  202. }
  203. return smpl->iface->name(smpl);
  204. }
  205. void llama_sampler_accept(struct llama_sampler * smpl, llama_token token) {
  206. if (smpl->iface->accept) {
  207. smpl->iface->accept(smpl, token);
  208. }
  209. }
  210. void llama_sampler_apply(struct llama_sampler * smpl, struct llama_token_data_array * cur_p) {
  211. GGML_ASSERT(smpl->iface->apply);
  212. smpl->iface->apply(smpl, cur_p);
  213. }
  214. void llama_sampler_reset(struct llama_sampler * smpl) {
  215. if (smpl->iface->reset) {
  216. smpl->iface->reset(smpl);
  217. }
  218. }
  219. struct llama_sampler * llama_sampler_clone(const struct llama_sampler * smpl) {
  220. if (smpl->iface->clone) {
  221. return smpl->iface->clone(smpl);
  222. }
  223. if (smpl->ctx == nullptr) {
  224. return new llama_sampler {
  225. /* .iface = */ smpl->iface,
  226. /* .ctx = */ nullptr,
  227. };
  228. }
  229. GGML_ABORT("the sampler does not support cloning");
  230. }
  231. void llama_sampler_free(struct llama_sampler * smpl) {
  232. if (smpl == nullptr) {
  233. return;
  234. }
  235. if (smpl->iface->free) {
  236. smpl->iface->free(smpl);
  237. }
  238. delete smpl;
  239. }
  240. llama_token llama_sampler_sample(struct llama_sampler * smpl, struct llama_context * ctx, int32_t idx) {
  241. const auto * logits = llama_get_logits_ith(ctx, idx);
  242. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  243. // TODO: do not allocate each time
  244. std::vector<llama_token_data> cur;
  245. cur.reserve(n_vocab);
  246. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  247. cur.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  248. }
  249. llama_token_data_array cur_p = {
  250. /* .data = */ cur.data(),
  251. /* .size = */ cur.size(),
  252. /* .selected = */ -1,
  253. /* .sorted = */ false,
  254. };
  255. llama_sampler_apply(smpl, &cur_p);
  256. GGML_ASSERT(cur_p.selected >= 0 && cur_p.selected < (int32_t) cur_p.size);
  257. auto token = cur_p.data[cur_p.selected].id;
  258. llama_sampler_accept(smpl, token);
  259. return token;
  260. }
  261. // sampler chain
  262. static const char * llama_sampler_chain_name(const struct llama_sampler * /*smpl*/) {
  263. return "chain";
  264. }
  265. static void llama_sampler_chain_accept(struct llama_sampler * smpl, llama_token token) {
  266. auto * chain = (llama_sampler_chain *) smpl->ctx;
  267. time_meas tm(chain->t_sample_us, chain->params.no_perf);
  268. for (auto * smpl : chain->samplers) {
  269. llama_sampler_accept(smpl, token);
  270. }
  271. chain->n_sample++;
  272. }
  273. static void llama_sampler_chain_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  274. auto * chain = (llama_sampler_chain *) smpl->ctx;
  275. time_meas tm(chain->t_sample_us, chain->params.no_perf);
  276. for (auto * smpl : chain->samplers) {
  277. llama_sampler_apply(smpl, cur_p);
  278. }
  279. }
  280. static void llama_sampler_chain_reset(struct llama_sampler * smpl) {
  281. auto * chain = (llama_sampler_chain *) smpl->ctx;
  282. for (auto * smpl : chain->samplers) {
  283. llama_sampler_reset(smpl);
  284. }
  285. chain->t_sample_us = 0;
  286. chain->n_sample = 0;
  287. }
  288. static struct llama_sampler * llama_sampler_chain_clone(const struct llama_sampler * smpl) {
  289. const auto * chain_src = (const llama_sampler_chain *) smpl->ctx;
  290. auto * result = llama_sampler_chain_init(chain_src->params);
  291. for (auto * smpl : chain_src->samplers) {
  292. llama_sampler_chain_add(result, llama_sampler_clone(smpl));
  293. }
  294. return result;
  295. }
  296. static void llama_sampler_chain_free(struct llama_sampler * smpl) {
  297. auto * chain = (llama_sampler_chain *) smpl->ctx;
  298. for (auto * smpl : chain->samplers) {
  299. llama_sampler_free(smpl);
  300. }
  301. delete chain;
  302. }
  303. static struct llama_sampler_i llama_sampler_chain_i = {
  304. /* .name = */ llama_sampler_chain_name,
  305. /* .accept = */ llama_sampler_chain_accept,
  306. /* .apply = */ llama_sampler_chain_apply,
  307. /* .reset = */ llama_sampler_chain_reset,
  308. /* .clone = */ llama_sampler_chain_clone,
  309. /* .free = */ llama_sampler_chain_free,
  310. };
  311. struct llama_sampler * llama_sampler_chain_init(struct llama_sampler_chain_params params) {
  312. return new llama_sampler {
  313. /* .iface = */ &llama_sampler_chain_i,
  314. /* .ctx = */ new llama_sampler_chain {
  315. /* .params = */ params,
  316. /* .samplers = */ {},
  317. /* .t_sample_us = */ 0,
  318. /* .n_sample = */ 0,
  319. },
  320. };
  321. }
  322. void llama_sampler_chain_add(struct llama_sampler * chain, struct llama_sampler * smpl) {
  323. auto * p = (llama_sampler_chain *) chain->ctx;
  324. p->samplers.push_back(smpl);
  325. }
  326. struct llama_sampler * llama_sampler_chain_get(const struct llama_sampler * chain, int32_t i) {
  327. const auto * p = (const llama_sampler_chain *) chain->ctx;
  328. if (i < 0 || (size_t) i >= p->samplers.size()) {
  329. return nullptr;
  330. }
  331. return p->samplers[i];
  332. }
  333. struct llama_sampler * llama_sampler_chain_remove(struct llama_sampler * chain, int32_t i) {
  334. auto * p = (llama_sampler_chain *) chain->ctx;
  335. if (i < 0 || (size_t) i >= p->samplers.size()) {
  336. return nullptr;
  337. }
  338. auto * result = p->samplers[i];
  339. p->samplers.erase(p->samplers.begin() + i);
  340. return result;
  341. }
  342. int llama_sampler_chain_n(const struct llama_sampler * chain) {
  343. const auto * p = (const llama_sampler_chain *) chain->ctx;
  344. return p->samplers.size();
  345. }
  346. //
  347. // samplers
  348. //
  349. // greedy
  350. static const char * llama_sampler_greedy_name(const struct llama_sampler * /*smpl*/) {
  351. return "greedy";
  352. }
  353. static void llama_sampler_greedy_apply(struct llama_sampler * /*smpl*/, llama_token_data_array * cur_p) {
  354. cur_p->selected = 0;
  355. for (size_t i = 1; i < cur_p->size; ++i) {
  356. if (cur_p->data[i].logit > cur_p->data[cur_p->selected].logit) {
  357. cur_p->selected = i;
  358. }
  359. }
  360. }
  361. static struct llama_sampler_i llama_sampler_greedy_i = {
  362. /* .name = */ llama_sampler_greedy_name,
  363. /* .accept = */ nullptr,
  364. /* .apply = */ llama_sampler_greedy_apply,
  365. /* .reset = */ nullptr,
  366. /* .clone = */ nullptr,
  367. /* .free = */ nullptr,
  368. };
  369. struct llama_sampler * llama_sampler_init_greedy() {
  370. return new llama_sampler {
  371. /* .iface = */ &llama_sampler_greedy_i,
  372. /* .ctx = */ nullptr,
  373. };
  374. }
  375. // dist
  376. struct llama_sampler_dist {
  377. const uint32_t seed;
  378. uint32_t seed_cur;
  379. std::mt19937 rng;
  380. };
  381. static const char * llama_sampler_dist_name(const struct llama_sampler * /*smpl*/) {
  382. return "dist";
  383. }
  384. static void llama_sampler_dist_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  385. auto * ctx = (llama_sampler_dist *) smpl->ctx;
  386. llama_sampler_softmax_impl(cur_p);
  387. cur_p->selected = llama_sample_dist(cur_p, ctx->rng);
  388. }
  389. static struct llama_sampler * llama_sampler_dist_clone(const struct llama_sampler * smpl) {
  390. const auto * ctx = (const llama_sampler_dist *) smpl->ctx;
  391. auto * result = llama_sampler_init_dist(ctx->seed);
  392. // copy the state
  393. {
  394. auto * result_ctx = (llama_sampler_dist *) result->ctx;
  395. result_ctx->rng = ctx->rng;
  396. }
  397. return result;
  398. }
  399. static void llama_sampler_dist_reset(struct llama_sampler * smpl) {
  400. auto * ctx = (llama_sampler_dist *) smpl->ctx;
  401. ctx->seed_cur = get_rng_seed(ctx->seed);
  402. ctx->rng.seed(ctx->seed_cur);
  403. }
  404. static void llama_sampler_dist_free(struct llama_sampler * smpl) {
  405. delete (llama_sampler_dist *) smpl->ctx;
  406. }
  407. static struct llama_sampler_i llama_sampler_dist_i = {
  408. /* .name = */ llama_sampler_dist_name,
  409. /* .accept = */ nullptr,
  410. /* .apply = */ llama_sampler_dist_apply,
  411. /* .reset = */ llama_sampler_dist_reset,
  412. /* .clone = */ llama_sampler_dist_clone,
  413. /* .free = */ llama_sampler_dist_free,
  414. };
  415. struct llama_sampler * llama_sampler_init_dist(uint32_t seed) {
  416. auto seed_cur = get_rng_seed(seed);
  417. return new llama_sampler {
  418. /* .iface = */ &llama_sampler_dist_i,
  419. /* .ctx = */ new llama_sampler_dist {
  420. /* .seed = */ seed,
  421. /* .seed_cur = */ seed_cur,
  422. /* .rng = */ std::mt19937(seed_cur),
  423. },
  424. };
  425. }
  426. // softmax
  427. static const char * llama_sampler_softmax_name(const struct llama_sampler * /*smpl*/) {
  428. return "softmax";
  429. }
  430. static void llama_sampler_softmax_apply(struct llama_sampler * /*smpl*/, llama_token_data_array * cur_p) {
  431. llama_sampler_softmax_impl(cur_p);
  432. }
  433. static struct llama_sampler_i llama_sampler_softmax_i = {
  434. /* .name = */ llama_sampler_softmax_name,
  435. /* .accept = */ nullptr,
  436. /* .apply = */ llama_sampler_softmax_apply,
  437. /* .reset = */ nullptr,
  438. /* .clone = */ nullptr,
  439. /* .free = */ nullptr,
  440. };
  441. struct llama_sampler * llama_sampler_init_softmax() {
  442. return new llama_sampler {
  443. /* .iface = */ &llama_sampler_softmax_i,
  444. /* .ctx = */ nullptr,
  445. };
  446. }
  447. // top-k
  448. struct llama_sampler_top_k {
  449. const int32_t k;
  450. };
  451. static const char * llama_sampler_top_k_name(const struct llama_sampler * /*smpl*/) {
  452. return "top-k";
  453. }
  454. static void llama_sampler_top_k_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  455. const auto * ctx = (llama_sampler_top_k *) smpl->ctx;
  456. llama_sampler_top_k_impl(cur_p, ctx->k);
  457. }
  458. static struct llama_sampler * llama_sampler_top_k_clone(const struct llama_sampler * smpl) {
  459. const auto * ctx = (const llama_sampler_top_k *) smpl->ctx;
  460. return llama_sampler_init_top_k(ctx->k);
  461. }
  462. static void llama_sampler_top_k_free(struct llama_sampler * smpl) {
  463. delete (llama_sampler_top_k *) smpl->ctx;
  464. }
  465. static struct llama_sampler_i llama_sampler_top_k_i = {
  466. /* .name = */ llama_sampler_top_k_name,
  467. /* .accept = */ nullptr,
  468. /* .apply = */ llama_sampler_top_k_apply,
  469. /* .reset = */ nullptr,
  470. /* .clone = */ llama_sampler_top_k_clone,
  471. /* .free = */ llama_sampler_top_k_free,
  472. };
  473. struct llama_sampler * llama_sampler_init_top_k(int32_t k) {
  474. return new llama_sampler {
  475. /* .iface = */ &llama_sampler_top_k_i,
  476. /* .ctx = */ new llama_sampler_top_k {
  477. /* .k = */ k,
  478. },
  479. };
  480. }
  481. // top-p
  482. struct llama_sampler_top_p {
  483. const float p;
  484. const size_t min_keep;
  485. };
  486. static const char * llama_sampler_top_p_name(const struct llama_sampler * /*smpl*/) {
  487. return "top-p";
  488. }
  489. static void llama_sampler_top_p_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  490. const auto * ctx = (llama_sampler_top_p *) smpl->ctx;
  491. if (ctx->p >= 1.0f) {
  492. return;
  493. }
  494. llama_sampler_softmax_impl(cur_p);
  495. // Compute the cumulative probabilities
  496. float cum_sum = 0.0f;
  497. size_t last_idx = cur_p->size;
  498. for (size_t i = 0; i < cur_p->size; ++i) {
  499. cum_sum += cur_p->data[i].p;
  500. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  501. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  502. if (cum_sum >= ctx->p && i + 1 >= ctx->min_keep) {
  503. last_idx = i + 1;
  504. break;
  505. }
  506. }
  507. // Resize the output vector to keep only the top-p tokens
  508. cur_p->size = last_idx;
  509. }
  510. static struct llama_sampler * llama_sampler_top_p_clone(const struct llama_sampler * smpl) {
  511. const auto * ctx = (const llama_sampler_top_p *) smpl->ctx;
  512. return llama_sampler_init_top_p(ctx->p, ctx->min_keep);
  513. }
  514. static void llama_sampler_top_p_free(struct llama_sampler * smpl) {
  515. delete (llama_sampler_top_p *) smpl->ctx;
  516. }
  517. static struct llama_sampler_i llama_sampler_top_p_i = {
  518. /* .name = */ llama_sampler_top_p_name,
  519. /* .accept = */ nullptr,
  520. /* .apply = */ llama_sampler_top_p_apply,
  521. /* .reset = */ nullptr,
  522. /* .clone = */ llama_sampler_top_p_clone,
  523. /* .free = */ llama_sampler_top_p_free,
  524. };
  525. struct llama_sampler * llama_sampler_init_top_p(float p, size_t min_keep) {
  526. return new llama_sampler {
  527. /* .iface = */ &llama_sampler_top_p_i,
  528. /* .ctx = */ new llama_sampler_top_p {
  529. /* .p = */ p,
  530. /* .min_keep = */ min_keep,
  531. },
  532. };
  533. }
  534. // min-p
  535. struct llama_sampler_min_p {
  536. const float p;
  537. const size_t min_keep;
  538. };
  539. static const char * llama_sampler_min_p_name(const struct llama_sampler * /*smpl*/) {
  540. return "min-p";
  541. }
  542. static void llama_sampler_min_p_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  543. const auto * ctx = (llama_sampler_min_p *) smpl->ctx;
  544. if (ctx->p <= 0.0f || !cur_p->size) {
  545. return;
  546. }
  547. bool min_p_applied = false;
  548. // if the cur_p aren't sorted, try the unsorted implementation first
  549. if (!cur_p->sorted) {
  550. std::vector<llama_token_data> filtered_tokens;
  551. float max_logit = -FLT_MAX;
  552. for (size_t i = 0; i < cur_p->size; ++i) {
  553. max_logit = std::max(max_logit, cur_p->data[i].logit);
  554. }
  555. const float min_logit = max_logit + logf(ctx->p); // min logit for p_i >= p * p_max
  556. for (size_t i = 0; i < cur_p->size; ++i) {
  557. if (cur_p->data[i].logit >= min_logit) {
  558. filtered_tokens.push_back(cur_p->data[i]);
  559. }
  560. }
  561. // if we have enough values the operation was a success
  562. if (filtered_tokens.size() >= ctx->min_keep) {
  563. memcpy(cur_p->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  564. cur_p->size = filtered_tokens.size();
  565. min_p_applied = true;
  566. }
  567. }
  568. // if the cur_p are sorted or the unsorted implementation failed, use this implementation
  569. if (!min_p_applied) {
  570. // Sort the logits in descending order
  571. if (!cur_p->sorted) {
  572. std::sort(cur_p->data, cur_p->data + cur_p->size, [](const llama_token_data & a, const llama_token_data & b) {
  573. return a.logit > b.logit;
  574. });
  575. cur_p->sorted = true;
  576. }
  577. const float min_logit = cur_p->data[0].logit + logf(ctx->p); // min logit for p_i >= p * p_max
  578. size_t i = 1; // first token always matches
  579. for (; i < cur_p->size; ++i) {
  580. if (cur_p->data[i].logit < min_logit && i >= ctx->min_keep) {
  581. break; // prob too small
  582. }
  583. }
  584. // Resize the output vector to keep only the matching tokens
  585. cur_p->size = i;
  586. }
  587. }
  588. static struct llama_sampler * llama_sampler_min_p_clone(const struct llama_sampler * smpl) {
  589. const auto * ctx = (const llama_sampler_min_p *) smpl->ctx;
  590. return llama_sampler_init_min_p(ctx->p, ctx->min_keep);
  591. }
  592. static void llama_sampler_min_p_free(struct llama_sampler * smpl) {
  593. delete (llama_sampler_min_p *) smpl->ctx;
  594. }
  595. static struct llama_sampler_i llama_sampler_min_p_i = {
  596. /* .name = */ llama_sampler_min_p_name,
  597. /* .accept = */ nullptr,
  598. /* .apply = */ llama_sampler_min_p_apply,
  599. /* .reset = */ nullptr,
  600. /* .clone = */ llama_sampler_min_p_clone,
  601. /* .free = */ llama_sampler_min_p_free,
  602. };
  603. struct llama_sampler * llama_sampler_init_min_p(float p, size_t min_keep) {
  604. return new llama_sampler {
  605. /* .iface = */ &llama_sampler_min_p_i,
  606. /* .ctx = */ new llama_sampler_min_p {
  607. /* .p = */ p,
  608. /* .min_keep = */ min_keep,
  609. },
  610. };
  611. }
  612. // typical
  613. struct llama_sampler_typical {
  614. const float p;
  615. const size_t min_keep;
  616. };
  617. static const char * llama_sampler_typical_name(const struct llama_sampler * /*smpl*/) {
  618. return "typical";
  619. }
  620. static void llama_sampler_typical_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  621. const auto * ctx = (llama_sampler_typical *) smpl->ctx;
  622. // Reference implementation:
  623. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  624. if (ctx->p >= 1.0f) {
  625. return;
  626. }
  627. // Compute the softmax of logits and calculate entropy
  628. llama_sampler_softmax_impl(cur_p);
  629. float entropy = 0.0f;
  630. for (size_t i = 0; i < cur_p->size; ++i) {
  631. entropy += -cur_p->data[i].p * logf(cur_p->data[i].p);
  632. }
  633. // Compute the absolute difference between negative log probability and entropy for each candidate
  634. std::vector<float> shifted_scores;
  635. for (size_t i = 0; i < cur_p->size; ++i) {
  636. float shifted_score = fabsf(-logf(cur_p->data[i].p) - entropy);
  637. shifted_scores.push_back(shifted_score);
  638. }
  639. // Sort tokens based on the shifted_scores and their corresponding indices
  640. std::vector<size_t> indices(cur_p->size);
  641. std::iota(indices.begin(), indices.end(), 0);
  642. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  643. return shifted_scores[a] < shifted_scores[b];
  644. });
  645. // Compute the cumulative probabilities
  646. float cum_sum = 0.0f;
  647. size_t last_idx = indices.size();
  648. for (size_t i = 0; i < indices.size(); ++i) {
  649. size_t idx = indices[i];
  650. cum_sum += cur_p->data[idx].p;
  651. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  652. if (cum_sum > ctx->p && i >= ctx->min_keep - 1) {
  653. last_idx = i + 1;
  654. break;
  655. }
  656. }
  657. // Resize the output vector to keep only the locally typical tokens
  658. std::vector<llama_token_data> cur_p_new;
  659. for (size_t i = 0; i < last_idx; ++i) {
  660. size_t idx = indices[i];
  661. cur_p_new.push_back(cur_p->data[idx]);
  662. }
  663. // Replace the data in cur_p with the cur_p_new data
  664. std::copy(cur_p_new.begin(), cur_p_new.end(), cur_p->data);
  665. cur_p->size = cur_p_new.size();
  666. cur_p->sorted = false;
  667. }
  668. static struct llama_sampler * llama_sampler_typical_clone(const struct llama_sampler * smpl) {
  669. const auto * ctx = (const llama_sampler_typical *) smpl->ctx;
  670. return llama_sampler_init_typical(ctx->p, ctx->min_keep);
  671. }
  672. static void llama_sampler_typical_free(struct llama_sampler * smpl) {
  673. delete (llama_sampler_typical *) smpl->ctx;
  674. }
  675. static struct llama_sampler_i llama_sampler_typical_i = {
  676. /* .name = */ llama_sampler_typical_name,
  677. /* .accept = */ nullptr,
  678. /* .apply = */ llama_sampler_typical_apply,
  679. /* .reset = */ nullptr,
  680. /* .clone = */ llama_sampler_typical_clone,
  681. /* .free = */ llama_sampler_typical_free,
  682. };
  683. struct llama_sampler * llama_sampler_init_typical(float p, size_t min_keep) {
  684. return new llama_sampler {
  685. /* .iface = */ &llama_sampler_typical_i,
  686. /* .ctx = */ new llama_sampler_typical {
  687. /* .p = */ p,
  688. /* .min_keep = */ min_keep,
  689. },
  690. };
  691. }
  692. // temp
  693. struct llama_sampler_temp {
  694. const float temp;
  695. };
  696. static const char * llama_sampler_temp_name(const struct llama_sampler * /*smpl*/) {
  697. return "temp";
  698. }
  699. static void llama_sampler_temp_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  700. const auto * ctx = (llama_sampler_temp *) smpl->ctx;
  701. llama_sampler_temp_impl(cur_p, ctx->temp);
  702. }
  703. static struct llama_sampler * llama_sampler_temp_clone(const struct llama_sampler * smpl) {
  704. const auto * ctx = (const llama_sampler_temp *) smpl->ctx;
  705. return llama_sampler_init_temp(ctx->temp);
  706. }
  707. static void llama_sampler_temp_free(struct llama_sampler * smpl) {
  708. delete (llama_sampler_temp *) smpl->ctx;
  709. }
  710. static struct llama_sampler_i llama_sampler_temp_i = {
  711. /* .name = */ llama_sampler_temp_name,
  712. /* .accept = */ nullptr,
  713. /* .apply = */ llama_sampler_temp_apply,
  714. /* .reset = */ nullptr,
  715. /* .clone = */ llama_sampler_temp_clone,
  716. /* .free = */ llama_sampler_temp_free,
  717. };
  718. struct llama_sampler * llama_sampler_init_temp(float temp) {
  719. return new llama_sampler {
  720. /* .iface = */ &llama_sampler_temp_i,
  721. /* .ctx = */ new llama_sampler_temp {
  722. /*.temp = */ temp,
  723. },
  724. };
  725. }
  726. // temp-ext
  727. struct llama_sampler_temp_ext {
  728. const float temp;
  729. const float delta;
  730. const float exponent;
  731. };
  732. static const char * llama_sampler_temp_ext_name(const struct llama_sampler * /*smpl*/) {
  733. return "temp-ext";
  734. }
  735. static void llama_sampler_temp_ext_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  736. const auto * ctx = (llama_sampler_temp_ext *) smpl->ctx;
  737. if (ctx->delta > 0) {
  738. const float min_temp = std::max(0.0f, ctx->temp - ctx->delta);
  739. const float max_temp = ctx->temp + ctx->delta;
  740. float exponent_val = ctx->exponent;
  741. // no need to do anything if there is only one (or zero) candidates
  742. if (cur_p->size <= 1) {
  743. return;
  744. }
  745. // Calculate maximum possible entropy
  746. float max_entropy = -logf(1.0f / cur_p->size);
  747. llama_sampler_softmax_impl(cur_p);
  748. // Calculate entropy of the softmax probabilities
  749. float entropy = 0.0f;
  750. for (size_t i = 0; i < cur_p->size; ++i) {
  751. float prob = cur_p->data[i].p;
  752. if (prob > 0.0f) { // Ensure no log(0)
  753. entropy -= prob * logf(prob);
  754. }
  755. }
  756. // Normalize the entropy (max_entropy cannot be 0 here because we checked cur_p->size != 1 above)
  757. float normalized_entropy = entropy / max_entropy;
  758. // Map the normalized entropy to the desired temperature range using the power function
  759. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  760. #ifdef DEBUG
  761. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  762. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  763. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  764. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  765. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  766. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  767. #endif
  768. // Apply the dynamically calculated temperature scaling
  769. llama_sampler_temp_impl(cur_p, dyn_temp);
  770. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  771. const double max_l_double = cur_p->data[0].logit;
  772. double cum_sum_double = 0.0;
  773. for (size_t i = 0; i < cur_p->size; ++i) {
  774. double p = exp(cur_p->data[i].logit - max_l_double);
  775. cur_p->data[i].p = p; // Store the scaled probability
  776. cum_sum_double += p;
  777. }
  778. for (size_t i = 0; i < cur_p->size; ++i) {
  779. cur_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  780. }
  781. #ifdef DEBUG
  782. // Print the updated top 25 probabilities after temperature scaling
  783. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  784. for (size_t i = 0; i < 25 && i < cur_p->size; ++i) {
  785. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, cur_p->data[i].p * 100.0f);
  786. }
  787. #endif
  788. } else {
  789. llama_sampler_temp_impl(cur_p, ctx->temp);
  790. }
  791. }
  792. static struct llama_sampler * llama_sampler_temp_ext_clone(const struct llama_sampler * smpl) {
  793. const auto * ctx = (const llama_sampler_temp_ext *) smpl->ctx;
  794. return llama_sampler_init_temp_ext(ctx->temp, ctx->delta, ctx->exponent);
  795. }
  796. static void llama_sampler_temp_ext_free(struct llama_sampler * smpl) {
  797. delete (llama_sampler_temp_ext *) smpl->ctx;
  798. }
  799. static struct llama_sampler_i llama_sampler_temp_ext_i = {
  800. /* .name = */ llama_sampler_temp_ext_name,
  801. /* .accept = */ nullptr,
  802. /* .apply = */ llama_sampler_temp_ext_apply,
  803. /* .reset = */ nullptr,
  804. /* .clone = */ llama_sampler_temp_ext_clone,
  805. /* .free = */ llama_sampler_temp_ext_free,
  806. };
  807. struct llama_sampler * llama_sampler_init_temp_ext(float temp, float delta, float exponent) {
  808. return new llama_sampler {
  809. /* .iface = */ &llama_sampler_temp_ext_i,
  810. /* .ctx = */ new llama_sampler_temp_ext {
  811. /* .temp = */ temp,
  812. /* .delta = */ delta,
  813. /* .exponent = */ exponent,
  814. },
  815. };
  816. }
  817. // xtc
  818. struct llama_sampler_xtc {
  819. const float probability;
  820. const float threshold;
  821. const size_t min_keep;
  822. const uint32_t seed;
  823. uint32_t seed_cur;
  824. std::mt19937 rng;
  825. };
  826. static const char * llama_sampler_xtc_name(const struct llama_sampler * /*smpl*/) {
  827. return "xtc";
  828. }
  829. static void llama_sample_xtc_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  830. auto * ctx = (llama_sampler_xtc *) smpl->ctx;
  831. if (ctx->probability <= 0.0f
  832. || ctx->threshold > 0.5f
  833. || cur_p->size < 2) {
  834. return;
  835. }
  836. std::uniform_real_distribution<float> distribution(0.0f, 1.0f);
  837. float chance = distribution(ctx->rng);
  838. if (chance > ctx->probability) return;
  839. // in case it's not sorted/recalculated yet
  840. llama_sampler_softmax_impl(cur_p);
  841. int pos_last = 0;
  842. for (size_t i = 0; i < cur_p->size; ++i) {
  843. if (cur_p->data[i].p >= ctx->threshold) {
  844. pos_last = i;
  845. } else break;
  846. }
  847. if (cur_p->size - pos_last >= ctx->min_keep && pos_last > 0) {
  848. cur_p->data += pos_last;
  849. cur_p->size -= pos_last;
  850. }
  851. }
  852. static struct llama_sampler * llama_sampler_xtc_clone(const struct llama_sampler * smpl) {
  853. const auto * ctx = (const llama_sampler_xtc *) smpl->ctx;
  854. auto * result = llama_sampler_init_xtc(ctx->probability, ctx->threshold, ctx->min_keep, ctx->seed);
  855. // copy the state
  856. {
  857. auto * result_ctx = (llama_sampler_xtc *) result->ctx;
  858. result_ctx->rng = ctx->rng;
  859. }
  860. return result;
  861. }
  862. static void llama_sampler_xtc_free(struct llama_sampler * smpl) {
  863. delete (llama_sampler_xtc *) smpl->ctx;
  864. }
  865. static void llama_sampler_xtc_reset(struct llama_sampler * smpl) {
  866. auto * ctx = (llama_sampler_xtc *) smpl->ctx;
  867. ctx->seed_cur = get_rng_seed(ctx->seed);
  868. ctx->rng.seed(ctx->seed_cur);
  869. }
  870. static struct llama_sampler_i llama_sampler_xtc_i = {
  871. /* .name = */ llama_sampler_xtc_name,
  872. /* .accept = */ nullptr,
  873. /* .apply = */ llama_sample_xtc_apply,
  874. /* .reset = */ llama_sampler_xtc_reset,
  875. /* .clone = */ llama_sampler_xtc_clone,
  876. /* .free = */ llama_sampler_xtc_free,
  877. };
  878. struct llama_sampler * llama_sampler_init_xtc(float p, float t, size_t min_keep, uint32_t seed) {
  879. auto seed_cur = get_rng_seed(seed);
  880. return new llama_sampler {
  881. /* .iface = */ &llama_sampler_xtc_i,
  882. /* .ctx = */ new llama_sampler_xtc {
  883. /* .probability = */ p,
  884. /* .threshold = */ t,
  885. /* .min_keep = */ min_keep,
  886. /* .seed = */ seed,
  887. /* .seed_cur = */ seed_cur,
  888. /* .rng = */ std::mt19937(seed_cur),
  889. },
  890. };
  891. }
  892. // mirostat
  893. struct llama_sampler_mirostat {
  894. const int32_t n_vocab;
  895. const uint32_t seed;
  896. uint32_t seed_cur;
  897. const float tau;
  898. const float eta;
  899. const int32_t m;
  900. float mu;
  901. std::mt19937 rng;
  902. };
  903. static const char * llama_sampler_mirostat_name(const struct llama_sampler * /*smpl*/) {
  904. return "mirostat";
  905. }
  906. static void llama_sampler_mirostat_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  907. auto * ctx = (llama_sampler_mirostat *) smpl->ctx;
  908. llama_sampler_softmax_impl(cur_p);
  909. // Estimate s_hat using the most probable m tokens
  910. float s_hat = 0.0;
  911. float sum_ti_bi = 0.0;
  912. float sum_ti_sq = 0.0;
  913. for (size_t i = 0; i < size_t(ctx->m - 1) && i < cur_p->size - 1; ++i) {
  914. float t_i = logf(float(i + 2) / float(i + 1));
  915. float b_i = logf(cur_p->data[i].p / cur_p->data[i + 1].p);
  916. sum_ti_bi += t_i * b_i;
  917. sum_ti_sq += t_i * t_i;
  918. }
  919. s_hat = sum_ti_bi / sum_ti_sq;
  920. // Compute k from the estimated s_hat and target surprise value
  921. float epsilon_hat = s_hat - 1;
  922. float k = powf((epsilon_hat * powf(2, ctx->mu)) / (1 - powf(ctx->n_vocab, -epsilon_hat)), 1 / s_hat);
  923. llama_sampler_top_k_impl(cur_p, std::max(int(k), 1));
  924. llama_sampler_softmax_impl(cur_p);
  925. const int idx = llama_sample_dist(cur_p, ctx->rng);
  926. cur_p->selected = idx;
  927. float observed_surprise = -log2f(cur_p->data[idx].p);
  928. float e = observed_surprise - ctx->tau;
  929. // Update mu using the learning rate and error
  930. ctx->mu = ctx->mu - ctx->eta * e;
  931. }
  932. static struct llama_sampler * llama_sampler_mirostat_clone(const struct llama_sampler * smpl) {
  933. const auto * ctx = (const llama_sampler_mirostat *) smpl->ctx;
  934. auto * result = llama_sampler_init_mirostat(ctx->n_vocab, ctx->seed, ctx->tau, ctx->eta, ctx->m);
  935. // copy the state
  936. {
  937. auto * result_ctx = (llama_sampler_mirostat *) smpl->ctx;
  938. result_ctx->mu = ctx->mu;
  939. result_ctx->rng = ctx->rng;
  940. }
  941. return result;
  942. }
  943. static void llama_sampler_mirostat_reset(struct llama_sampler * smpl) {
  944. auto * ctx = (llama_sampler_mirostat *) smpl->ctx;
  945. ctx->mu = 2.0f*ctx->tau;
  946. ctx->seed_cur = get_rng_seed(ctx->seed);
  947. ctx->rng.seed(ctx->seed_cur);
  948. }
  949. static void llama_sampler_mirostat_free(struct llama_sampler * smpl) {
  950. delete (llama_sampler_mirostat *) smpl->ctx;
  951. }
  952. static struct llama_sampler_i llama_sampler_mirostat_i = {
  953. /* .name = */ llama_sampler_mirostat_name,
  954. /* .accept = */ nullptr,
  955. /* .apply = */ llama_sampler_mirostat_apply,
  956. /* .reset = */ llama_sampler_mirostat_reset,
  957. /* .clone = */ llama_sampler_mirostat_clone,
  958. /* .free = */ llama_sampler_mirostat_free,
  959. };
  960. struct llama_sampler * llama_sampler_init_mirostat(int32_t n_vocab, uint32_t seed, float tau, float eta, int32_t m) {
  961. auto seed_cur = get_rng_seed(seed);
  962. return new llama_sampler {
  963. /* .iface = */ &llama_sampler_mirostat_i,
  964. /* .ctx = */ new llama_sampler_mirostat {
  965. /* .n_vocab = */ n_vocab,
  966. /* .seed = */ seed,
  967. /* .seed_cur = */ seed_cur,
  968. /* .tau = */ tau,
  969. /* .eta = */ eta,
  970. /* .m = */ m,
  971. /* .mu = */ 2.0f*tau,
  972. /* .rng = */ std::mt19937(seed_cur),
  973. },
  974. };
  975. }
  976. // mirostat v2
  977. struct llama_sampler_mirostat_v2 {
  978. const uint32_t seed;
  979. uint32_t seed_cur;
  980. const float tau;
  981. const float eta;
  982. float mu;
  983. std::mt19937 rng;
  984. };
  985. static const char * llama_sampler_mirostat_v2_name(const struct llama_sampler * /*smpl*/) {
  986. return "mirostat-v2";
  987. }
  988. static void llama_sampler_mirostat_v2_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  989. auto * ctx = (llama_sampler_mirostat_v2 *) smpl->ctx;
  990. llama_sampler_softmax_impl(cur_p);
  991. // Truncate the words with surprise values greater than mu
  992. cur_p->size = std::distance(cur_p->data, std::find_if(cur_p->data, cur_p->data + cur_p->size, [&](const llama_token_data & candidate) {
  993. return -log2f(candidate.p) > ctx->mu;
  994. }));
  995. if (cur_p->size == 0) {
  996. cur_p->size = 1;
  997. }
  998. // Normalize the probabilities of the remaining words
  999. llama_sampler_softmax_impl(cur_p);
  1000. const int idx = llama_sample_dist(cur_p, ctx->rng);
  1001. cur_p->selected = idx;
  1002. float observed_surprise = -log2f(cur_p->data[idx].p);
  1003. float e = observed_surprise - ctx->tau;
  1004. // Update mu using the learning rate and error
  1005. ctx->mu = ctx->mu - ctx->eta * e;
  1006. }
  1007. static void llama_sampler_mirostat_v2_reset(struct llama_sampler * smpl) {
  1008. auto * ctx = (llama_sampler_mirostat_v2 *) smpl->ctx;
  1009. ctx->mu = 2.0f*ctx->tau;
  1010. ctx->seed_cur = get_rng_seed(ctx->seed);
  1011. ctx->rng.seed(ctx->seed_cur);
  1012. }
  1013. static struct llama_sampler * llama_sampler_mirostat_v2_clone(const struct llama_sampler * smpl) {
  1014. const auto * ctx = (const llama_sampler_mirostat_v2 *) smpl->ctx;
  1015. auto * result = llama_sampler_init_mirostat_v2(ctx->seed, ctx->tau, ctx->eta);
  1016. // copy the state
  1017. {
  1018. auto * result_ctx = (llama_sampler_mirostat_v2 *) result->ctx;
  1019. result_ctx->mu = ctx->mu;
  1020. result_ctx->rng = ctx->rng;
  1021. }
  1022. return result;
  1023. }
  1024. static void llama_sampler_mirostat_v2_free(struct llama_sampler * smpl) {
  1025. delete (llama_sampler_mirostat_v2 *) smpl->ctx;
  1026. }
  1027. static struct llama_sampler_i llama_sampler_mirostat_v2_i = {
  1028. /* .name = */ llama_sampler_mirostat_v2_name,
  1029. /* .accept = */ nullptr,
  1030. /* .apply = */ llama_sampler_mirostat_v2_apply,
  1031. /* .reset = */ llama_sampler_mirostat_v2_reset,
  1032. /* .clone = */ llama_sampler_mirostat_v2_clone,
  1033. /* .free = */ llama_sampler_mirostat_v2_free,
  1034. };
  1035. struct llama_sampler * llama_sampler_init_mirostat_v2(uint32_t seed, float tau, float eta) {
  1036. auto seed_cur = get_rng_seed(seed);
  1037. return new llama_sampler {
  1038. /* .iface = */ &llama_sampler_mirostat_v2_i,
  1039. /* .ctx = */ new llama_sampler_mirostat_v2 {
  1040. /* .seed = */ seed,
  1041. /* .seed_cur = */ seed_cur,
  1042. /* .tau = */ tau,
  1043. /* .eta = */ eta,
  1044. /* .mu = */ 2.0f*tau,
  1045. /* .rng = */ std::mt19937(seed_cur),
  1046. },
  1047. };
  1048. }
  1049. // grammar
  1050. struct llama_sampler_grammar {
  1051. const struct llama_vocab * vocab;
  1052. std::string grammar_str;
  1053. std::string grammar_root;
  1054. struct llama_grammar * grammar;
  1055. };
  1056. static const char * llama_sampler_grammar_name(const struct llama_sampler * /*smpl*/) {
  1057. return "grammar";
  1058. }
  1059. static void llama_sampler_grammar_accept_impl(struct llama_sampler * smpl, llama_token token) {
  1060. auto * ctx = (llama_sampler_grammar *) smpl->ctx;
  1061. if (ctx->grammar) {
  1062. llama_grammar_accept_impl(*ctx->grammar, token);
  1063. }
  1064. }
  1065. static void llama_sampler_grammar_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  1066. auto * ctx = (llama_sampler_grammar *) smpl->ctx;
  1067. if (ctx->grammar) {
  1068. llama_grammar_apply_impl(*ctx->grammar, cur_p);
  1069. }
  1070. }
  1071. static void llama_sampler_grammar_reset(struct llama_sampler * smpl) {
  1072. auto * ctx = (llama_sampler_grammar *) smpl->ctx;
  1073. if (!ctx->grammar) {
  1074. return;
  1075. }
  1076. auto * grammar_new = llama_grammar_init_impl(ctx->grammar->vocab, ctx->grammar_str.c_str(), ctx->grammar_root.c_str());
  1077. llama_grammar_free_impl(ctx->grammar);
  1078. ctx->grammar = grammar_new;
  1079. }
  1080. static struct llama_sampler * llama_sampler_grammar_clone(const struct llama_sampler * smpl) {
  1081. const auto * ctx = (const llama_sampler_grammar *) smpl->ctx;
  1082. auto * result = llama_sampler_init_grammar_impl(*ctx->vocab, nullptr, nullptr);
  1083. // copy the state
  1084. {
  1085. auto * result_ctx = (llama_sampler_grammar *) result->ctx;
  1086. if (ctx->grammar) {
  1087. result_ctx->grammar_str = ctx->grammar_str;
  1088. result_ctx->grammar_root = ctx->grammar_root;
  1089. result_ctx->grammar = llama_grammar_clone_impl(*ctx->grammar);
  1090. }
  1091. }
  1092. return result;
  1093. }
  1094. static void llama_sampler_grammar_free(struct llama_sampler * smpl) {
  1095. const auto * ctx = (llama_sampler_grammar *) smpl->ctx;
  1096. if (ctx->grammar) {
  1097. llama_grammar_free_impl(ctx->grammar);
  1098. }
  1099. delete ctx;
  1100. }
  1101. static struct llama_sampler_i llama_sampler_grammar_i = {
  1102. /* .name = */ llama_sampler_grammar_name,
  1103. /* .accept = */ llama_sampler_grammar_accept_impl,
  1104. /* .apply = */ llama_sampler_grammar_apply,
  1105. /* .reset = */ llama_sampler_grammar_reset,
  1106. /* .clone = */ llama_sampler_grammar_clone,
  1107. /* .free = */ llama_sampler_grammar_free,
  1108. };
  1109. struct llama_sampler * llama_sampler_init_grammar_impl(const struct llama_vocab & vocab, const char * grammar_str, const char * grammar_root) {
  1110. auto * ctx = new llama_sampler_grammar;
  1111. if (grammar_str != nullptr && grammar_str[0] != '\0') {
  1112. *ctx = {
  1113. /* .vocab = */ &vocab,
  1114. /* .grammar_str = */ grammar_str,
  1115. /* .grammar_root = */ grammar_root,
  1116. /* .grammar = */ llama_grammar_init_impl(&vocab, grammar_str, grammar_root),
  1117. };
  1118. } else {
  1119. *ctx = {
  1120. /* .vocab = */ &vocab,
  1121. /* .grammar_str = */ {},
  1122. /* .grammar_root = */ {},
  1123. /* .grammar = */ nullptr,
  1124. };
  1125. }
  1126. return new llama_sampler {
  1127. /* .iface = */ &llama_sampler_grammar_i,
  1128. /* .ctx = */ ctx,
  1129. };
  1130. }
  1131. // penalties
  1132. struct llama_sampler_penalties {
  1133. const int32_t n_vocab;
  1134. const llama_token special_eos_id;
  1135. const llama_token linefeed_id;
  1136. const int32_t penalty_last_n;
  1137. const float penalty_repeat;
  1138. const float penalty_freq;
  1139. const float penalty_present;
  1140. const bool penalize_nl;
  1141. const bool ignore_eos;
  1142. ring_buffer<llama_token> prev;
  1143. };
  1144. static const char * llama_sampler_penalties_name(const struct llama_sampler * /*smpl*/) {
  1145. return "penalties";
  1146. }
  1147. static void llama_sampler_penalties_accept(struct llama_sampler * smpl, llama_token token) {
  1148. auto * ctx = (llama_sampler_penalties *) smpl->ctx;
  1149. if (ctx->penalty_last_n == 0) {
  1150. return;
  1151. }
  1152. ctx->prev.push_back(token);
  1153. }
  1154. static void llama_sampler_penalties_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  1155. auto * ctx = (llama_sampler_penalties *) smpl->ctx;
  1156. if (ctx->ignore_eos) {
  1157. assert(ctx->special_eos_id >= 0);
  1158. // optimistically check if the candidates are not yet sorted/shuffled/truncated
  1159. if (cur_p->size > (size_t) ctx->special_eos_id && cur_p->data[ctx->special_eos_id].id == ctx->special_eos_id) {
  1160. cur_p->data[ctx->special_eos_id].logit = -INFINITY;
  1161. } else {
  1162. // else, search for the special EOS token
  1163. for (size_t i = 0; i < cur_p->size; ++i) {
  1164. if (cur_p->data[i].id == ctx->special_eos_id) {
  1165. cur_p->data[i].logit = -INFINITY;
  1166. break;
  1167. }
  1168. }
  1169. }
  1170. }
  1171. if ((ctx->penalty_last_n == 0) ||
  1172. (ctx->penalty_repeat == 1.0f && ctx->penalty_freq == 0.0f && ctx->penalty_present == 0.0f)) {
  1173. return;
  1174. }
  1175. bool nl_found = false;
  1176. size_t nl_idx = 0;
  1177. float nl_logit = -INFINITY;
  1178. if (!ctx->penalize_nl) {
  1179. assert(ctx->linefeed_id >= 0);
  1180. // optimistically check if the candidates are not yet sorted/shuffled/truncated
  1181. if (cur_p->size > (size_t) ctx->linefeed_id && cur_p->data[ctx->linefeed_id].id == ctx->linefeed_id) {
  1182. nl_found = true;
  1183. nl_idx = ctx->linefeed_id;
  1184. nl_logit = cur_p->data[ctx->linefeed_id].logit;
  1185. } else {
  1186. // else, search for the linefeed token
  1187. for (size_t i = 0; i < cur_p->size; ++i) {
  1188. if (cur_p->data[i].id == ctx->linefeed_id) {
  1189. nl_found = true;
  1190. nl_idx = i;
  1191. nl_logit = cur_p->data[i].logit;
  1192. break;
  1193. }
  1194. }
  1195. }
  1196. }
  1197. // Create a frequency map to count occurrences of each token in last_tokens
  1198. // TODO: optimize this by maintaining the token count in the sampler context
  1199. using llama_token_cnt = std::unordered_map<llama_token, int>;
  1200. llama_token_cnt token_count;
  1201. for (int i = 0; i < std::min<int>(ctx->penalty_last_n, ctx->prev.size()); ++i) {
  1202. token_count[ctx->prev.rat(i)]++;
  1203. }
  1204. // Apply frequency and presence penalties to the cur_p
  1205. for (size_t i = 0; i < cur_p->size; ++i) {
  1206. const auto token_iter = token_count.find(cur_p->data[i].id);
  1207. if (token_iter == token_count.end()) {
  1208. continue;
  1209. }
  1210. const int count = token_iter->second;
  1211. // The academic publication that described this technique actually just only divided, but that would cause tokens with negative logits to become more likely, which is obviously wrong.
  1212. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  1213. if (cur_p->data[i].logit <= 0) {
  1214. cur_p->data[i].logit *= ctx->penalty_repeat;
  1215. } else {
  1216. cur_p->data[i].logit /= ctx->penalty_repeat;
  1217. }
  1218. cur_p->data[i].logit -= float(count) * ctx->penalty_freq + float(count > 0) * ctx->penalty_present;
  1219. }
  1220. cur_p->sorted = false;
  1221. if (!ctx->penalize_nl && nl_found) {
  1222. // restore the logit of the newline token if it was penalized
  1223. cur_p->data[nl_idx].logit = nl_logit;
  1224. }
  1225. }
  1226. static void llama_sampler_penalties_reset(struct llama_sampler * smpl) {
  1227. auto * ctx = (llama_sampler_penalties *) smpl->ctx;
  1228. ctx->prev.clear();
  1229. }
  1230. static struct llama_sampler * llama_sampler_penalties_clone(const struct llama_sampler * smpl) {
  1231. const auto * ctx = (const llama_sampler_penalties *) smpl->ctx;
  1232. auto * result = llama_sampler_init_penalties(
  1233. ctx->n_vocab,
  1234. ctx->special_eos_id,
  1235. ctx->linefeed_id,
  1236. ctx->penalty_last_n,
  1237. ctx->penalty_repeat,
  1238. ctx->penalty_freq,
  1239. ctx->penalty_present,
  1240. ctx->penalize_nl,
  1241. ctx->ignore_eos);
  1242. // copy the state
  1243. {
  1244. auto * result_ctx = (llama_sampler_penalties *) result->ctx;
  1245. result_ctx->prev = ctx->prev;
  1246. }
  1247. return result;
  1248. }
  1249. static void llama_sampler_penalties_free(struct llama_sampler * smpl) {
  1250. delete (llama_sampler_penalties *) smpl->ctx;
  1251. }
  1252. static struct llama_sampler_i llama_sampler_penalties_i = {
  1253. /* .name = */ llama_sampler_penalties_name,
  1254. /* .accept = */ llama_sampler_penalties_accept,
  1255. /* .apply = */ llama_sampler_penalties_apply,
  1256. /* .reset = */ llama_sampler_penalties_reset,
  1257. /* .clone = */ llama_sampler_penalties_clone,
  1258. /* .free = */ llama_sampler_penalties_free,
  1259. };
  1260. struct llama_sampler * llama_sampler_init_penalties(
  1261. int32_t n_vocab,
  1262. llama_token special_eos_id,
  1263. llama_token linefeed_id,
  1264. int32_t penalty_last_n,
  1265. float penalty_repeat,
  1266. float penalty_freq,
  1267. float penalty_present,
  1268. bool penalize_nl,
  1269. bool ignore_eos) {
  1270. if (linefeed_id == LLAMA_TOKEN_NULL) {
  1271. penalize_nl = true;
  1272. }
  1273. if (special_eos_id == LLAMA_TOKEN_NULL) {
  1274. ignore_eos = false;
  1275. }
  1276. penalty_last_n = std::max(penalty_last_n, 0);
  1277. return new llama_sampler {
  1278. /* .iface = */ &llama_sampler_penalties_i,
  1279. /* .ctx = */ new llama_sampler_penalties {
  1280. /* .n_vocab = */ n_vocab,
  1281. /* .special_eos_id = */ special_eos_id,
  1282. /* .linefeed_id = */ linefeed_id,
  1283. /* .penalty_last_n = */ penalty_last_n,
  1284. /* .penalty_repeat = */ penalty_repeat,
  1285. /* .penalty_freq = */ penalty_freq,
  1286. /* .penalty_present = */ penalty_present,
  1287. /* .penalize_nl = */ penalize_nl,
  1288. /* .ignore_eos = */ ignore_eos,
  1289. /* .prev = */ ring_buffer<llama_token>(penalty_last_n),
  1290. },
  1291. };
  1292. }
  1293. // DRY
  1294. struct llama_sampler_dry {
  1295. int32_t total_context_size;
  1296. const float dry_multiplier;
  1297. const float dry_base;
  1298. const int32_t dry_allowed_length;
  1299. const int32_t dry_penalty_last_n;
  1300. std::unordered_multimap<llama_token, std::vector<llama_token>> dry_processed_breakers;
  1301. std::vector<int> dry_repeat_count;
  1302. std::unordered_map<llama_token, int> dry_max_token_repeat;
  1303. ring_buffer<llama_token> last_tokens;
  1304. };
  1305. // Ported from Koboldcpp, original PR: https://github.com/LostRuins/koboldcpp/pull/982 (Original author: pi6am)
  1306. static void get_overlapping_token_sequences(const llama_vocab & vocab, const std::string& str, std::unordered_multimap<llama_token, std::vector<llama_token>>& token_sequences, int max_tail_len = -1) {
  1307. for (llama_token token_id = 0; token_id < (llama_token)vocab.n_vocab; token_id++) {
  1308. std::string word = llama_detokenize(vocab, {token_id}, true);
  1309. if (word.find(str) != std::string::npos) {
  1310. token_sequences.emplace(token_id, std::vector<llama_token>());
  1311. } else {
  1312. size_t word_len = word.size(), str_len = str.size();
  1313. size_t pos = -1;
  1314. while ((pos = word.find(str[0], pos + 1)) != std::string::npos) {
  1315. bool match = true;
  1316. size_t i;
  1317. for (i = 1; i < str_len && i + pos < word_len; ++i) {
  1318. if (word[pos + i] != str[i]) {
  1319. match = false;
  1320. break;
  1321. }
  1322. }
  1323. if (match) {
  1324. std::vector<llama_token> tokenization = llama_tokenize_internal(vocab, str.substr(i), false, false);
  1325. if (max_tail_len >= 0 && tokenization.size() > (size_t)max_tail_len) {
  1326. tokenization.resize(max_tail_len);
  1327. }
  1328. // Ensure we don't already have a duplicate matching tokenization
  1329. auto its = token_sequences.equal_range(token_id);
  1330. bool found = false;
  1331. for (auto it = its.first; it != its.second; ++it) {
  1332. if (tokenization == it->second) {
  1333. found = true;
  1334. break;
  1335. }
  1336. }
  1337. if (!found) {
  1338. token_sequences.emplace(token_id, tokenization);
  1339. }
  1340. }
  1341. }
  1342. }
  1343. }
  1344. }
  1345. static const char * llama_sampler_dry_name(const struct llama_sampler * /*smpl*/) {
  1346. return "dry";
  1347. }
  1348. static void llama_sampler_dry_accept(struct llama_sampler * smpl, llama_token token) {
  1349. auto * ctx = (llama_sampler_dry *) smpl->ctx;
  1350. if (ctx->dry_multiplier == 0.0f || ctx->dry_base < 1.0f || ctx->dry_penalty_last_n == 0) {
  1351. return;
  1352. }
  1353. ctx->last_tokens.push_back(token);
  1354. }
  1355. // Ported from Koboldcpp, original PR: https://github.com/LostRuins/koboldcpp/pull/982 (Original author: pi6am)
  1356. static void llama_sampler_dry_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  1357. auto * ctx = (llama_sampler_dry *) smpl->ctx;
  1358. if (ctx->dry_multiplier == 0.0f || ctx->dry_base < 1.0f || ctx->dry_penalty_last_n == 0) {
  1359. return;
  1360. }
  1361. int32_t effective_dry_penalty_last_n = (ctx->dry_penalty_last_n == -1) ? ctx->total_context_size : std::max(ctx->dry_penalty_last_n, 0);
  1362. int last_n_repeat = std::min(std::min((int)ctx->last_tokens.size(), effective_dry_penalty_last_n), ctx->total_context_size);
  1363. if (last_n_repeat <= ctx->dry_allowed_length) {
  1364. return;
  1365. }
  1366. ctx->dry_repeat_count.assign(last_n_repeat, 0);
  1367. ctx->dry_max_token_repeat.clear();
  1368. // Step 1: Look for restart sequences to limit the maximum repetition length.
  1369. // Work backwards through the context looking for any token that begins a restart sequence.
  1370. //
  1371. // The collection `restart_sequences` is a mapping from a "head" token to all "tail"
  1372. // sequences that together comprise a restart sequence. This allows us to quickly check
  1373. // whether each token is the head of a complete sequence. Most restart sequences are actually
  1374. // a single token, and for these the "tail" is an empty vector.
  1375. //
  1376. // If the token is a "head", test all restart sequences that begin with this token
  1377. // (there will often only be one sequence for each token, but if sequences like 'aaaq1' and
  1378. // 'aaa1' are used as restart strings, both could start with 'aaa' when tokenized). The
  1379. // longest matching sequence (if any) is used to limit the maximum repetition length.
  1380. //
  1381. // Note that in the case case of a short sequence contained in a longer one, this might fail to
  1382. // find the smallest value for `rep_limit`. For example, if 'amniotic' and 'ni' are both used as
  1383. // restart sequences, 'ni' will be found first, and since it's shorter it will fail to suppress
  1384. // 'otic'. This is a minor issue since fully contained restart sequences are likely to be rare.
  1385. //
  1386. // This is theoretically worst-case O(N^2) for arbitrary restart sequences, which is why we
  1387. // have already clamped the maximum tail sequence length when generating `restart_sequences`.
  1388. // With clamping, this scan is O(N) in the context length.
  1389. int rep_limit = last_n_repeat;
  1390. for (int i = 0; i < last_n_repeat; ++i) {
  1391. llama_token token = ctx->last_tokens.rat(i);
  1392. auto its = ctx->dry_processed_breakers.equal_range(token);
  1393. if (its.first == ctx->dry_processed_breakers.end()) {
  1394. continue;
  1395. }
  1396. int longest_match = -1;
  1397. for (auto it = its.first; it != its.second; ++it) {
  1398. // Note that (*it) does not contain the head character, so seq_len will be
  1399. // the restart sequence length minus 1.
  1400. // In the common case of a single-token restart sequence, (*it) will be empty
  1401. // and we will trivially match.
  1402. int seq_len = (int)it->second.size();
  1403. if (seq_len > longest_match && seq_len <= (int)i) {
  1404. bool match = true;
  1405. for (int offset = 0; offset < seq_len; ++offset) {
  1406. // The -1 when indexing `last_tokens` is because we already matched the head.
  1407. if (it->second[offset] != ctx->last_tokens.rat(i - offset - 1)) {
  1408. match = false;
  1409. break;
  1410. }
  1411. }
  1412. if (match) {
  1413. longest_match = seq_len;
  1414. }
  1415. }
  1416. }
  1417. if (longest_match >= 0) {
  1418. // We found a restart sequence starting `i` tokens from the end and continuing for
  1419. // `longest_match` tokens.
  1420. rep_limit = i - longest_match;
  1421. break;
  1422. }
  1423. }
  1424. if (rep_limit < ctx->dry_allowed_length) {
  1425. return;
  1426. }
  1427. // Step 2: Iterate in reverse over the last N tokens of the context, using the "Z-algorithm" (in
  1428. // the reverse direction) to efficiently compute the positions and lengths of suffixes appearing
  1429. // elsewhere in the context. We limit the suffix length to `rep_limit` to respect restart sequences.
  1430. //
  1431. // This algorithm is not currently documented on Wikipedia, but there is a clear description here:
  1432. // https://ivanyu.me/blog/2014/10/15/z-algorithm/
  1433. //
  1434. // The code below is adapted from the public domain implementation by the same author here:
  1435. // https://github.com/ivanyu/string-algorithms/blob/master/z_algorithm.py
  1436. //
  1437. // Example:
  1438. // Last N tokens: a b c c b c y a b c
  1439. // Repeat counts: 0 0 3 1 0 2 0 0 0 0
  1440. // ^
  1441. // This `3` means that the last three tokens of the context (a b c) also appear here.
  1442. //
  1443. // This step is worst case O(N) since the Z-algorithm is linear, despite the appearance of nested
  1444. // for/while loops. This can be seen by observing that the `lt` and `rt` bounds are set after each
  1445. // repeated suffix is detected (i.e. after each while loop when n > 0). These bound variables
  1446. // ensure that the inner while loops only examine each token in the context once as the outer
  1447. // for loop iterates over the context.
  1448. {
  1449. const int last = last_n_repeat - 1;
  1450. int rt = 0, lt = 0;
  1451. for (int k = 1; k < last_n_repeat; ++k) {
  1452. if (k > rt) {
  1453. // If k is outside the current Z-box, do naive computation.
  1454. int n = 0;
  1455. while (n + k < last_n_repeat && ctx->last_tokens.rat(n) == ctx->last_tokens.rat(n+k)) {
  1456. ++n;
  1457. }
  1458. ctx->dry_repeat_count[last - k] = std::min(n, rep_limit);
  1459. if (n > 0) {
  1460. lt = k;
  1461. rt = k+n-1;
  1462. }
  1463. } else {
  1464. // If k is inside the current Z-box, consider two cases.
  1465. int p = k - lt; // Pair index.
  1466. int right_part_len = rt - k + 1;
  1467. if (ctx->dry_repeat_count[last - p] < right_part_len) {
  1468. int n = std::min(ctx->dry_repeat_count[last - p], rep_limit);
  1469. ctx->dry_repeat_count[last - k] = n;
  1470. } else {
  1471. int i = rt + 1;
  1472. while (i < last_n_repeat && ctx->last_tokens.rat(i) == ctx->last_tokens.rat(i - k)) {
  1473. i += 1;
  1474. }
  1475. int n = std::min(i - k, rep_limit);
  1476. ctx->dry_repeat_count[last - k] = n;
  1477. lt = k;
  1478. rt = i - 1;
  1479. }
  1480. }
  1481. }
  1482. }
  1483. // Step 3: Iterate over dry_repeat_count and last_tokens, examining the maximum repeat length
  1484. // that would be generated by emitting each new token that would extend a sequence.
  1485. //
  1486. // Following the same example as above:
  1487. // Last N tokens: a b c c b c y a b c
  1488. // Repeat counts: 0 0 3 1 0 2 0 0 0 0
  1489. //
  1490. // For each non-zero, look ahead one token. This token, if emitted, would extend the repetition.
  1491. // c: 3 -> 4 (from `a b c` to `a b c c`)
  1492. // b: 1 -> 2 (from `c` to `c b`)
  1493. // y: 2 -> 3 (from `b c` to `b c y`)
  1494. for (int i = 0; i < last_n_repeat - 1; ++i) {
  1495. int repeat_len = ctx->dry_repeat_count[i];
  1496. if (repeat_len >= ctx->dry_allowed_length) {
  1497. // This token ends a repeat, so the next token would continue one.
  1498. // By convention, the value of `repeat_len` only includes the tokens currently
  1499. // in the context, not the new token that would be added.
  1500. llama_token token = ctx->last_tokens.rat(last_n_repeat - 2 - i);
  1501. // Track the maximum sequence ending in this token.
  1502. const auto& it = ctx->dry_max_token_repeat.find(token);
  1503. if (it == ctx->dry_max_token_repeat.end() || it->second < repeat_len) {
  1504. ctx->dry_max_token_repeat[token] = repeat_len;
  1505. }
  1506. }
  1507. }
  1508. // Step 4: Apply logit penalties based on the maximum repeat length for relevant tokens.
  1509. // Prevent floating point overflow in `pow(penalty_base, exponent)` by clamping to `max_exponent`.
  1510. // Compute it from `penalty_base` and the approximate log of `std::numeric_limits<float>::max()`
  1511. const float FLOAT_MAX_LOG = 88.7228391f;
  1512. int max_exponent = 0;
  1513. if (ctx->dry_base > 1.000001f) {
  1514. max_exponent = FLOAT_MAX_LOG / std::log(ctx->dry_base);
  1515. }
  1516. for (size_t i = 0; i < cur_p->size; ++i) {
  1517. const auto& af_kvp = ctx->dry_max_token_repeat.find(cur_p->data[i].id);
  1518. if (af_kvp != ctx->dry_max_token_repeat.end()) {
  1519. // Check all sequence breakers starting with this token
  1520. auto range = ctx->dry_processed_breakers.equal_range(cur_p->data[i].id);
  1521. bool is_single_token_breaker = false;
  1522. for (auto it = range.first; it != range.second; ++it) {
  1523. if (it->second.empty()) {
  1524. is_single_token_breaker = true;
  1525. break;
  1526. }
  1527. }
  1528. // Apply penalty only if it's not a single-token sequence breaker
  1529. if (!is_single_token_breaker) {
  1530. int repeat_exp = af_kvp->second - ctx->dry_allowed_length;
  1531. if (max_exponent > 0 && repeat_exp > max_exponent) {
  1532. repeat_exp = max_exponent;
  1533. }
  1534. float penalty = ctx->dry_multiplier * std::pow(ctx->dry_base, repeat_exp);
  1535. cur_p->data[i].logit -= penalty;
  1536. }
  1537. }
  1538. }
  1539. cur_p->sorted = false;
  1540. }
  1541. static void llama_sampler_dry_reset(struct llama_sampler * smpl) {
  1542. auto * ctx = (llama_sampler_dry *) smpl->ctx;
  1543. ctx->last_tokens.clear();
  1544. ctx->dry_repeat_count.clear();
  1545. ctx->dry_max_token_repeat.clear();
  1546. }
  1547. static struct llama_sampler * llama_sampler_dry_clone(const struct llama_sampler * smpl) {
  1548. const auto * ctx = (llama_sampler_dry *) smpl->ctx;
  1549. llama_vocab dummy_vocab;
  1550. // dummy vocab is passed because it is only needed for raw sequence breaker processing, which we have already done and will simply be copying
  1551. auto * result = llama_sampler_init_dry_impl(dummy_vocab, ctx->total_context_size, ctx->dry_multiplier, ctx->dry_base, ctx->dry_allowed_length, ctx->dry_penalty_last_n, NULL, 0);
  1552. // Copy the state, including the processed breakers
  1553. {
  1554. auto * result_ctx = (llama_sampler_dry *) result->ctx;
  1555. result_ctx->dry_processed_breakers = ctx->dry_processed_breakers;
  1556. result_ctx->dry_repeat_count = ctx->dry_repeat_count;
  1557. result_ctx->dry_max_token_repeat = ctx->dry_max_token_repeat;
  1558. result_ctx->last_tokens = ctx->last_tokens;
  1559. }
  1560. return result;
  1561. }
  1562. static void llama_sampler_dry_free(struct llama_sampler * smpl) {
  1563. delete (llama_sampler_dry *) smpl->ctx;
  1564. }
  1565. static struct llama_sampler_i llama_sampler_dry_i = {
  1566. /* .name = */ llama_sampler_dry_name,
  1567. /* .accept = */ llama_sampler_dry_accept,
  1568. /* .apply = */ llama_sampler_dry_apply,
  1569. /* .reset = */ llama_sampler_dry_reset,
  1570. /* .clone = */ llama_sampler_dry_clone,
  1571. /* .free = */ llama_sampler_dry_free,
  1572. };
  1573. struct llama_sampler * llama_sampler_init_dry_impl(const struct llama_vocab & vocab, int32_t context_size, float dry_multiplier, float dry_base, int32_t dry_allowed_length, int32_t dry_penalty_last_n, const char** seq_breakers, size_t num_breakers) {
  1574. int32_t effective_dry_penalty_last_n = (dry_penalty_last_n == -1) ? context_size : std::max(dry_penalty_last_n, 0);
  1575. std::unordered_multimap<llama_token, std::vector<llama_token>> processed_breakers;
  1576. const int MAX_CHAR_LEN = 40;
  1577. const int MAX_SEQ_LEN = 20;
  1578. const bool dry_enabled = (dry_multiplier != 0.0f && dry_base >= 1.0f && dry_penalty_last_n != 0);
  1579. if (dry_enabled && seq_breakers != nullptr && num_breakers > 0) {
  1580. // Process sequence breakers
  1581. for (size_t i = 0; i < num_breakers; ++i) {
  1582. if (seq_breakers[i] == nullptr || std::strlen(seq_breakers[i]) == 0) {
  1583. LLAMA_LOG_WARN("skipping null or empty DRY sequence breaker at index %zu\n", i);
  1584. continue;
  1585. }
  1586. std::string sequence_break(seq_breakers[i]);
  1587. if (sequence_break.empty()) {
  1588. LLAMA_LOG_WARN("skipping empty DRY sequence breaker\n");
  1589. continue;
  1590. }
  1591. if (sequence_break.size() > MAX_CHAR_LEN) {
  1592. LLAMA_LOG_WARN("truncating DRY sequence breaker to %d characters\n", MAX_CHAR_LEN);
  1593. sequence_break.resize(MAX_CHAR_LEN);
  1594. }
  1595. get_overlapping_token_sequences(vocab, sequence_break, processed_breakers, MAX_SEQ_LEN);
  1596. }
  1597. }
  1598. return new llama_sampler {
  1599. /* .iface = */ &llama_sampler_dry_i,
  1600. /* .ctx = */ new llama_sampler_dry {
  1601. /* .total_context_size = */ context_size,
  1602. /* .dry_multiplier = */ dry_multiplier,
  1603. /* .dry_base = */ dry_base,
  1604. /* .dry_allowed_length = */ dry_allowed_length,
  1605. /* .dry_penalty_last_n = */ dry_penalty_last_n,
  1606. /* .dry_processed_breakers = */ std::move(processed_breakers),
  1607. /* .dry_repeat_count = */ dry_enabled ? std::vector<int>(effective_dry_penalty_last_n, 0) : std::vector<int>{},
  1608. /* .dry_max_token_repeat = */ {},
  1609. /* .last_tokens = */ dry_enabled ? ring_buffer<llama_token>(effective_dry_penalty_last_n) : ring_buffer<llama_token>(0),
  1610. },
  1611. };
  1612. }
  1613. // wrapper for test-sampling.cpp
  1614. struct llama_sampler * llama_sampler_init_dry_testing(int32_t context_size, float dry_multiplier, float dry_base, int32_t dry_allowed_length, int32_t dry_penalty_last_n, const std::vector<std::vector<llama_token>>& seq_breakers) {
  1615. llama_vocab dummy_vocab;
  1616. auto * result = llama_sampler_init_dry_impl(dummy_vocab, context_size, dry_multiplier, dry_base, dry_allowed_length, dry_penalty_last_n, NULL, 0);
  1617. auto * ctx = (llama_sampler_dry *) result->ctx;
  1618. // Process the token-based sequence breakers
  1619. ctx->dry_processed_breakers.clear();
  1620. if (seq_breakers.empty()) {
  1621. LLAMA_LOG_WARN("empty DRY sequence breakers list in llama_sampler_init_dry_testing\n");
  1622. } else {
  1623. for (const auto& breaker : seq_breakers) {
  1624. if (breaker.empty()) {
  1625. LLAMA_LOG_WARN("skipping DRY empty sequence breaker\n");
  1626. continue;
  1627. }
  1628. llama_token head_token = breaker[0];
  1629. std::vector<llama_token> tail_tokens(breaker.begin() + 1, breaker.end());
  1630. ctx->dry_processed_breakers.emplace(head_token, std::move(tail_tokens));
  1631. }
  1632. if (ctx->dry_processed_breakers.empty()) {
  1633. LLAMA_LOG_WARN("no valid DRY sequence breakers processed in llama_sampler_init_dry_testing\n");
  1634. }
  1635. }
  1636. return result;
  1637. }
  1638. // logit-bias
  1639. struct llama_sampler_logit_bias {
  1640. const int32_t n_vocab;
  1641. const std::vector<llama_logit_bias> logit_bias;
  1642. std::vector<llama_logit_bias> to_search;
  1643. };
  1644. static const char * llama_sampler_logit_bias_name(const struct llama_sampler * /*smpl*/) {
  1645. return "logit-bias";
  1646. }
  1647. static void llama_sampler_logit_bias_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  1648. auto * ctx = (llama_sampler_logit_bias *) smpl->ctx;
  1649. if (ctx->logit_bias.empty()) {
  1650. return;
  1651. }
  1652. ctx->to_search.clear();
  1653. // update the candidates that have not been shuffled in the vocabulary (i.e. idx == id)
  1654. for (const auto & lb : ctx->logit_bias) {
  1655. if (lb.token >= 0 && cur_p->size > (size_t) lb.token && cur_p->data[lb.token].id == lb.token) {
  1656. cur_p->data[lb.token].logit += lb.bias;
  1657. } else {
  1658. ctx->to_search.push_back(lb);
  1659. }
  1660. }
  1661. if (ctx->to_search.empty()) {
  1662. return;
  1663. }
  1664. // search for the remaining candidates that were not found in the previous step
  1665. for (size_t i = 0; i < cur_p->size; ++i) {
  1666. for (const auto & lb : ctx->to_search) {
  1667. if (cur_p->data[i].id == lb.token) {
  1668. cur_p->data[i].logit += lb.bias;
  1669. break;
  1670. }
  1671. }
  1672. }
  1673. }
  1674. static struct llama_sampler * llama_sampler_logit_bias_clone(const struct llama_sampler * smpl) {
  1675. const auto * ctx = (const llama_sampler_logit_bias *) smpl->ctx;
  1676. return llama_sampler_init_logit_bias(ctx->n_vocab, ctx->logit_bias.size(), ctx->logit_bias.data());
  1677. }
  1678. static void llama_sampler_logit_bias_free(struct llama_sampler * smpl) {
  1679. delete (llama_sampler_logit_bias *) smpl->ctx;
  1680. }
  1681. static struct llama_sampler_i llama_sampler_logit_bias_i = {
  1682. /* .name = */ llama_sampler_logit_bias_name,
  1683. /* .accept = */ nullptr,
  1684. /* .apply = */ llama_sampler_logit_bias_apply,
  1685. /* .reset = */ nullptr,
  1686. /* .clone = */ llama_sampler_logit_bias_clone,
  1687. /* .free = */ llama_sampler_logit_bias_free,
  1688. };
  1689. struct llama_sampler * llama_sampler_init_logit_bias(
  1690. int32_t n_vocab,
  1691. int32_t n_logit_bias,
  1692. const llama_logit_bias * logit_bias) {
  1693. return new llama_sampler {
  1694. /* .iface = */ &llama_sampler_logit_bias_i,
  1695. /* .ctx = */ new llama_sampler_logit_bias {
  1696. /* .n_vocab = */ n_vocab,
  1697. /* .logit_bias = */ std::vector<llama_logit_bias>(logit_bias, logit_bias + n_logit_bias),
  1698. /* .to_search = */ {},
  1699. },
  1700. };
  1701. }
  1702. // infill
  1703. //#define GGML_DEBUG_SAMPLER_INFILL
  1704. struct llama_sampler_infill {
  1705. const struct llama_vocab * vocab;
  1706. std::vector<char> buf0;
  1707. std::vector<char> buf1;
  1708. };
  1709. static const char * llama_sampler_infill_name(const struct llama_sampler * /*smpl*/) {
  1710. return "infill";
  1711. }
  1712. static void llama_sampler_infill_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
  1713. auto * ctx = (llama_sampler_infill *) smpl->ctx;
  1714. llama_sampler_softmax_impl(cur_p);
  1715. #if defined(GGML_DEBUG_SAMPLER_INFILL)
  1716. #define LOG_DBG_CUR LLAMA_LOG_DEBUG
  1717. #else
  1718. #define LOG_DBG_CUR(...)
  1719. #endif
  1720. for (size_t i = 0; i < cur_p->size; ++i) {
  1721. LOG_DBG_CUR("%s: cur_p[%3zu] = { id: %6d, p: %.6f, logit: %6.3f }\n", __func__, i, cur_p->data[i].id, cur_p->data[i].p, cur_p->data[i].logit);
  1722. }
  1723. float p_txt_sum = 0.0f;
  1724. float p_eog_sum = 0.0f;
  1725. for (size_t i = 0; i < cur_p->size; ++i) {
  1726. if (llama_token_is_eog_impl(*ctx->vocab, cur_p->data[i].id)) {
  1727. p_eog_sum += cur_p->data[i].p;
  1728. } else {
  1729. p_txt_sum += cur_p->data[i].p;
  1730. }
  1731. }
  1732. const float rat = p_eog_sum == 0.0 ? INFINITY : p_txt_sum / p_eog_sum; GGML_UNUSED(rat);
  1733. LOG_DBG_CUR("%s: p_txt_sum = %.2f, p_eog_sum = %.2f, rat = %.2f, n = %zu\n", __func__, p_txt_sum, p_eog_sum, rat, cur_p->size);
  1734. if (3*p_eog_sum*cur_p->size > p_txt_sum) {
  1735. LOG_DBG_CUR("%s: the ratio p_txt/p_eog = %.2f is too low -> sampling EOG\n", __func__, p_txt_sum/p_eog_sum);
  1736. // keep just the EOG tokens
  1737. const auto size_org = cur_p->size;
  1738. cur_p->size = 0;
  1739. float p_sum = 0.0f;
  1740. for (size_t i = 0; i < size_org; ++i) {
  1741. if (llama_token_is_eog_impl(*ctx->vocab, cur_p->data[i].id)) {
  1742. p_sum += cur_p->data[i].p;
  1743. cur_p->data[cur_p->size++] = cur_p->data[i];
  1744. }
  1745. }
  1746. // normalize probs
  1747. for (size_t i = 0; i < cur_p->size; ++i) {
  1748. cur_p->data[i].p /= p_sum;
  1749. }
  1750. return;
  1751. }
  1752. size_t n_combined = 0; GGML_UNUSED(n_combined);
  1753. // combine tokens with common prefix
  1754. for (size_t i0 = 0; i0 < cur_p->size; ++i0) {
  1755. for (size_t i1 = 0; i1 < cur_p->size; ++i1) {
  1756. if (cur_p->data[i0].logit == -INFINITY) {
  1757. break;
  1758. }
  1759. if (i0 == i1 || cur_p->data[i1].logit == -INFINITY) {
  1760. continue;
  1761. }
  1762. int len0 = llama_token_to_piece_impl(*ctx->vocab, cur_p->data[i0].id, ctx->buf0.data(), ctx->buf0.size(), 0, false);
  1763. if (len0 < 0) {
  1764. ctx->buf0.resize(len0);
  1765. len0 = llama_token_to_piece_impl(*ctx->vocab, cur_p->data[i0].id, ctx->buf0.data(), ctx->buf0.size(), 0, false);
  1766. assert(len0 > 0);
  1767. }
  1768. int len1 = llama_token_to_piece_impl(*ctx->vocab, cur_p->data[i1].id, ctx->buf1.data(), ctx->buf1.size(), 0, false);
  1769. if (len1 < 0) {
  1770. ctx->buf1.resize(len1);
  1771. len1 = llama_token_to_piece_impl(*ctx->vocab, cur_p->data[i1].id, ctx->buf1.data(), ctx->buf1.size(), 0, false);
  1772. assert(len1 > 0);
  1773. }
  1774. // token i0 is a prefix of token i1
  1775. if (len0 > 0 && len0 <= len1 && memcmp(ctx->buf0.data(), ctx->buf1.data(), len0) == 0) {
  1776. int dst = i0;
  1777. int src = i1;
  1778. // merge into the token with higher probability
  1779. if (cur_p->data[i1].p > cur_p->data[i0].p) {
  1780. std::swap(dst, src);
  1781. }
  1782. cur_p->data[dst].p += cur_p->data[src].p;
  1783. cur_p->data[src].logit = -INFINITY;
  1784. cur_p->data[src].p = 0.0f;
  1785. n_combined++;
  1786. }
  1787. }
  1788. }
  1789. size_t n_non_eog = 0;
  1790. size_t size_org = cur_p->size;
  1791. float p_sum = 0.0f;
  1792. float thold = 0.2f;
  1793. cur_p->size = 0;
  1794. LOG_DBG_CUR("%s: n_combined = %zu, applying thold = %.3f\n", __func__, n_combined, thold);
  1795. for (size_t i = 0; i < size_org; ++i) {
  1796. const bool is_eog = llama_token_is_eog_impl(*ctx->vocab, cur_p->data[i].id);
  1797. if (cur_p->data[i].p < thold && !is_eog) {
  1798. continue;
  1799. }
  1800. if (!is_eog) {
  1801. ++n_non_eog;
  1802. }
  1803. p_sum += cur_p->data[i].p;
  1804. // keep this token
  1805. cur_p->data[cur_p->size++] = cur_p->data[i];
  1806. }
  1807. LOG_DBG_CUR("%s: n_non_eog = %zu\n", __func__, n_non_eog);
  1808. // if no non-EOG tokens are left -> reduce cur_p to single EOT token
  1809. if (n_non_eog == 0) {
  1810. cur_p->size = 1;
  1811. cur_p->data[0].id = llama_token_eot_impl(*ctx->vocab);
  1812. cur_p->data[0].logit = 1.0f;
  1813. return;
  1814. }
  1815. // normalize probs
  1816. for (size_t i = 0; i < cur_p->size; ++i) {
  1817. cur_p->data[i].p /= p_sum;
  1818. LOG_DBG_CUR("%s: cur_p[%3zu] = { id: %6d, p: %.6f, logit: %6.3f }\n", __func__, i, cur_p->data[i].id, cur_p->data[i].p, cur_p->data[i].logit);
  1819. }
  1820. size_org = cur_p->size;
  1821. p_sum = 0.0f;
  1822. thold = 1.0/(n_non_eog + 1);
  1823. cur_p->size = 0;
  1824. LOG_DBG_CUR("%s: applying thold = %.3f\n", __func__, thold);
  1825. for (size_t i = 0; i < size_org; ++i) {
  1826. const bool is_eog = llama_token_is_eog_impl(*ctx->vocab, cur_p->data[i].id);
  1827. if (cur_p->data[i].p < thold && !is_eog) {
  1828. continue;
  1829. }
  1830. p_sum += cur_p->data[i].p;
  1831. cur_p->data[cur_p->size++] = cur_p->data[i];
  1832. }
  1833. // normalize probs
  1834. for (size_t i = 0; i < cur_p->size; ++i) {
  1835. cur_p->data[i].p /= p_sum;
  1836. LOG_DBG_CUR("%s: cur_p[%3zu] = { id: %6d, p: %.6f, logit: %6.3f }\n", __func__, i, cur_p->data[i].id, cur_p->data[i].p, cur_p->data[i].logit);
  1837. }
  1838. #undef LOG_DBG_CUR
  1839. }
  1840. static struct llama_sampler * llama_sampler_infill_clone(const struct llama_sampler * smpl) {
  1841. const auto * ctx = (const llama_sampler_infill *) smpl->ctx;
  1842. return llama_sampler_init_infill_impl(*ctx->vocab);
  1843. }
  1844. static void llama_sampler_infill_free(struct llama_sampler * smpl) {
  1845. delete (llama_sampler_infill *) smpl->ctx;
  1846. }
  1847. static struct llama_sampler_i llama_sampler_infill_i = {
  1848. /* .name = */ llama_sampler_infill_name,
  1849. /* .accept = */ nullptr,
  1850. /* .apply = */ llama_sampler_infill_apply,
  1851. /* .reset = */ nullptr,
  1852. /* .clone = */ llama_sampler_infill_clone,
  1853. /* .free = */ llama_sampler_infill_free,
  1854. };
  1855. struct llama_sampler * llama_sampler_init_infill_impl(
  1856. const struct llama_vocab & vocab) {
  1857. return new llama_sampler {
  1858. /* .iface = */ &llama_sampler_infill_i,
  1859. /* .ctx = */ new llama_sampler_infill {
  1860. /* .vocab = */ &vocab,
  1861. /* .buf0 = */ std::vector<char>(512),
  1862. /* .buf1 = */ std::vector<char>(512),
  1863. },
  1864. };
  1865. }
  1866. // utils
  1867. uint32_t llama_sampler_get_seed(const struct llama_sampler * smpl) {
  1868. if (smpl->iface == &llama_sampler_dist_i) {
  1869. return ((const llama_sampler_dist *) smpl->ctx)->seed_cur;
  1870. }
  1871. if (smpl->iface == &llama_sampler_mirostat_i) {
  1872. return ((const llama_sampler_mirostat *) smpl->ctx)->seed_cur;
  1873. }
  1874. if (smpl->iface == &llama_sampler_mirostat_v2_i) {
  1875. return ((const llama_sampler_mirostat_v2 *) smpl->ctx)->seed_cur;
  1876. }
  1877. if (smpl->iface == &llama_sampler_chain_i) {
  1878. const auto * ctx = (const llama_sampler_chain *) smpl->ctx;
  1879. for (auto it = ctx->samplers.rbegin(); it != ctx->samplers.rend(); ++it) {
  1880. const uint32_t seed = llama_sampler_get_seed(*it);
  1881. if (seed != LLAMA_DEFAULT_SEED) {
  1882. return seed;
  1883. }
  1884. }
  1885. }
  1886. return LLAMA_DEFAULT_SEED;
  1887. }
  1888. // perf
  1889. struct llama_perf_sampler_data llama_perf_sampler(const struct llama_sampler * chain) {
  1890. struct llama_perf_sampler_data data = {};
  1891. if (chain == nullptr || chain->iface != &llama_sampler_chain_i) {
  1892. GGML_ABORT("%s: invalid sampler passed - requires a sampler created with llama_sampler_chain_init()\n", __func__);
  1893. }
  1894. const auto * ctx = (const struct llama_sampler_chain *) chain->ctx;
  1895. data.t_sample_ms = 1e-3 * ctx->t_sample_us;
  1896. data.n_sample = std::max(0, ctx->n_sample);
  1897. return data;
  1898. }
  1899. void llama_perf_sampler_print(const struct llama_sampler * chain) {
  1900. const auto data = llama_perf_sampler(chain);
  1901. LLAMA_LOG_INFO("%s: sampling time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  1902. __func__, data.t_sample_ms, data.n_sample, data.t_sample_ms / data.n_sample, 1e3 / data.t_sample_ms * data.n_sample);
  1903. }
  1904. void llama_perf_sampler_reset(struct llama_sampler * chain) {
  1905. if (chain == nullptr || chain->iface != &llama_sampler_chain_i) {
  1906. GGML_ABORT("%s: invalid sampler passed - requires a sampler created with llama_sampler_chain_init()\n", __func__);
  1907. }
  1908. auto * ctx = (struct llama_sampler_chain *) chain->ctx;
  1909. ctx->t_sample_us = ctx->n_sample = 0;
  1910. }