llama-sampling.cpp 62 KB

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