llama-sampling.cpp 82 KB

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