llama-sampling.cpp 80 KB

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