llama-sampling.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  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. // utils
  1395. uint32_t llama_sampler_get_seed(const struct llama_sampler * smpl) {
  1396. if (smpl->iface == &llama_sampler_dist_i) {
  1397. return ((const llama_sampler_dist *) smpl->ctx)->seed_cur;
  1398. }
  1399. if (smpl->iface == &llama_sampler_mirostat_i) {
  1400. return ((const llama_sampler_mirostat *) smpl->ctx)->seed_cur;
  1401. }
  1402. if (smpl->iface == &llama_sampler_mirostat_v2_i) {
  1403. return ((const llama_sampler_mirostat_v2 *) smpl->ctx)->seed_cur;
  1404. }
  1405. if (smpl->iface == &llama_sampler_chain_i) {
  1406. const auto * ctx = (const llama_sampler_chain *) smpl->ctx;
  1407. for (auto it = ctx->samplers.rbegin(); it != ctx->samplers.rend(); ++it) {
  1408. const uint32_t seed = llama_sampler_get_seed(*it);
  1409. if (seed != LLAMA_DEFAULT_SEED) {
  1410. return seed;
  1411. }
  1412. }
  1413. }
  1414. return LLAMA_DEFAULT_SEED;
  1415. }
  1416. // perf
  1417. struct llama_perf_sampler_data llama_perf_sampler(const struct llama_sampler * chain) {
  1418. struct llama_perf_sampler_data data = {};
  1419. if (chain == nullptr || chain->iface != &llama_sampler_chain_i) {
  1420. GGML_ABORT("%s: invalid sampler passed - requires a sampler created with llama_sampler_chain_init()\n", __func__);
  1421. }
  1422. const auto * ctx = (const struct llama_sampler_chain *) chain->ctx;
  1423. data.t_sample_ms = 1e-3 * ctx->t_sample_us;
  1424. data.n_sample = std::max(0, ctx->n_sample);
  1425. return data;
  1426. }
  1427. void llama_perf_sampler_print(const struct llama_sampler * chain) {
  1428. const auto data = llama_perf_sampler(chain);
  1429. LLAMA_LOG_INFO("%s: sampling time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  1430. __func__, data.t_sample_ms, data.n_sample, data.t_sample_ms / data.n_sample, 1e3 / data.t_sample_ms * data.n_sample);
  1431. }
  1432. void llama_perf_sampler_reset(struct llama_sampler * chain) {
  1433. if (chain == nullptr || chain->iface != &llama_sampler_chain_i) {
  1434. GGML_ABORT("%s: invalid sampler passed - requires a sampler created with llama_sampler_chain_init()\n", __func__);
  1435. }
  1436. auto * ctx = (struct llama_sampler_chain *) chain->ctx;
  1437. ctx->t_sample_us = ctx->n_sample = 0;
  1438. }