llama-sampling.cpp 76 KB

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