cui-llama.rn 1.2.6 → 1.3.0

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