llama-sampling.cpp 86 KB

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