llama-sampling.cpp 77 KB

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