cui-llama.rn 1.4.0 → 1.4.1

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