llama-sampling.cpp 62 KB

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