llama-sampling.cpp 86 KB

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