llama-sampling.cpp 77 KB

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