llama-sampling.cpp 77 KB

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