llama-sampling.cpp 78 KB

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