llama-sampling.cpp 86 KB

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