"tests/vscode:/vscode.git/clone" did not exist on "b1e69105d4ad4b998f167e84ef928bf60df63292"
llama-sampling.cpp 86.3 KB
Newer Older
1
2
#include "llama-sampling.h"

3
#include "llama-impl.h"
4
5
6
#include "llama-vocab.h"
#include "llama-grammar.h"

7
#include <algorithm>
8
9
10
11
12
#include <cassert>
#include <cfloat>
#include <chrono>
#include <cmath>
#include <cstdlib>
13
14
15
#include <cstring>
#include <ctime>
#include <numeric>
16
#include <random>
17
#include <unordered_map>
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdexcept>

// the ring buffer works similarly to std::deque, but with a fixed capacity
template<typename T>
struct ring_buffer {
    ring_buffer(size_t cap) : capacity(cap), data(cap) {}

    T & front() {
        if (sz == 0) {
            throw std::runtime_error("ring buffer is empty");
        }
        return data[first];
    }

    const T & front() const {
        if (sz == 0) {
            throw std::runtime_error("ring buffer is empty");
        }
        return data[first];
    }

    T & back() {
        if (sz == 0) {
            throw std::runtime_error("ring buffer is empty");
        }
        return data[pos];
    }

    const T & back() const {
        if (sz == 0) {
            throw std::runtime_error("ring buffer is empty");
        }
        return data[pos];
    }

    void push_back(const T & value) {
        if (capacity == 0) {
            throw std::runtime_error("ring buffer: capacity is zero");
        }

        if (sz == capacity) {
            // advance the start when buffer is full
            first = (first + 1) % capacity;
        } else {
            sz++;
        }
        data[pos] = value;
        pos = (pos + 1) % capacity;
    }

    T pop_front() {
        if (sz == 0) {
            throw std::runtime_error("ring buffer is empty");
        }
        T value = data[first];
        first = (first + 1) % capacity;
        sz--;
        return value;
    }

    //T & operator[](size_t i) {
    //    if (i >= sz) {
    //        throw std::runtime_error("ring buffer: index out of bounds");
    //    }
    //    return data[(first + i) % capacity];
    //}

    //const T & at(size_t i) const {
    //    if (i >= sz) {
    //        throw std::runtime_error("ring buffer: index out of bounds");
    //    }
    //    return data[(first + i) % capacity];
    //}

    const T & rat(size_t i) const {
        if (i >= sz) {
            throw std::runtime_error("ring buffer: index out of bounds");
        }
        return data[(first + sz - i - 1) % capacity];
    }

    std::vector<T> to_vector() const {
        std::vector<T> result;
        result.reserve(sz);
        for (size_t i = 0; i < sz; i++) {
            result.push_back(data[(first + i) % capacity]);
        }
        return result;
    }

    void clear() {
        // here only reset the status of the buffer
        sz = 0;
        first = 0;
        pos = 0;
    }

    bool empty() const {
        return sz == 0;
    }

    size_t size() const {
        return sz;
    }

    size_t capacity = 0;
    size_t sz = 0;
    size_t first = 0;
    size_t pos = 0;

    std::vector<T> data;
};
130

Daniel Hiltgen's avatar
Daniel Hiltgen committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// writes result in res, does not mutate cur
static void llama_token_data_array_partial_sort(const llama_token_data_array & cur, int npartial, std::vector<llama_token_data> & res) {
    static const auto comp = [](const llama_token_data & a, const llama_token_data & b) {
        return a.logit > b.logit;
    };

    constexpr int   nbuckets     = 128;
    constexpr float bucket_low   = -10.0f;
    constexpr float bucket_high  =  10.0f;
    constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
    constexpr float bucket_inter = -bucket_low * bucket_scale;

    std::vector<int> bucket_idx;
    std::vector<int> histo(nbuckets, 0);

    std::vector<llama_token_data*> bucket_ptrs;

    bucket_idx.reserve(cur.size);

    for (int i = 0; i < (int)cur.size; ++i) {
        const float val = cur.data[i].logit;
        int ib = int(bucket_scale * val + bucket_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
        ib = std::max(0, std::min(nbuckets - 1, ib));
        bucket_idx.push_back(ib);
        ++histo[ib];
    }
    int nhave = 0;
    int ib = nbuckets - 1;
    for ( ; ib >= 0; --ib) {
        nhave += histo[ib];
        if (nhave >= npartial) {
            break;
        }
    }
    res.resize(nhave);
    auto * ptr = res.data();
    bucket_ptrs.reserve(nbuckets - ib);
    for (int j = nbuckets - 1; j >= ib; --j) {
        bucket_ptrs.push_back(ptr);
        ptr += histo[j];
    }
    for (int i = 0; i < (int)cur.size; ++i) {
        int j = bucket_idx[i];
        if (j >= ib) {
            *bucket_ptrs[nbuckets - 1 - j]++ = cur.data[i];
        }
    }

    ptr = res.data();
    int ndone = 0;
    for (int j = nbuckets - 1; j > ib; --j) {
        std::sort(ptr, ptr + histo[j], comp);
        ptr += histo[j];
        ndone += histo[j];
    }
    std::partial_sort(ptr, ptr + npartial - ndone, ptr + histo[ib], comp);
}

// reduces the size of cur_p to npartial, keeping only the top npartial elements
static void llama_token_data_array_partial_sort_inplace(llama_token_data_array * cur_p, int npartial) {
    static const auto comp = [](const llama_token_data & a, const llama_token_data & b) {
        return a.logit > b.logit;
    };

    if (npartial <= 128) {
        std::partial_sort(cur_p->data, cur_p->data + npartial, cur_p->data + cur_p->size, comp);

        cur_p->size = npartial;
        cur_p->sorted = true;

        return;
    }

    std::vector<llama_token_data> tmp;

    llama_token_data_array_partial_sort(*cur_p, npartial, tmp);

    std::copy(tmp.data(), tmp.data() + npartial, cur_p->data);

    cur_p->size = npartial;
    cur_p->sorted = true;
}

214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
static int llama_sample_dist(llama_token_data_array * cur_p, std::mt19937 & rng) {
    // iterator for the probabilities
#ifdef __GNUC__
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif

    struct probs_iterator {
        typedef std::input_iterator_tag iterator_category;
        typedef float value_type;
        typedef float * pointer;
        typedef float & reference;
        typedef ptrdiff_t difference_type;

        const llama_token_data * data;

        bool operator==(const probs_iterator & other) const { return data == other.data; }
        bool operator!=(const probs_iterator & other) const { return data != other.data; }
        const float & operator*() const { return data->p; }
        probs_iterator & operator++() { ++data; return *this; }
        probs_iterator operator++(int) { probs_iterator tmp = *this; ++data; return tmp; }
    };

#ifdef __GNUC__
    #pragma GCC diagnostic pop
#endif

    std::discrete_distribution<int> dist(probs_iterator{cur_p->data}, probs_iterator{cur_p->data + cur_p->size});

    return dist(rng);
}

/*
247
248
249
250
251
252
253
254
255
256
257
258
259
static void llama_log_softmax(float * array, size_t size) {
    float max_l = *std::max_element(array, array + size);
    float sum = 0.f;
    for (size_t i = 0; i < size; ++i) {
        float p = expf(array[i] - max_l);
        sum += p;
        array[i] = p;
    }

    for (size_t i = 0; i < size; ++i) {
        array[i] = logf(array[i] / sum);
    }
}
260
*/
261

262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
static void llama_sampler_temp_impl(llama_token_data_array * cur_p, float temp) {
    if (temp <= 0.0f) {
        // find the token with the highest logit and set the rest to -inf
        size_t max_i = 0;
        float  max_l = cur_p->data[0].logit;

        for (size_t i = 1; i < cur_p->size; ++i) {
            if (cur_p->data[i    ].logit > max_l) {
                cur_p->data[max_i].logit = -INFINITY;
                max_i = i;
                max_l = cur_p->data[i].logit;
            } else {
                cur_p->data[i].logit = -INFINITY;
            }
        }

        return;
    }

    for (size_t i = 0; i < cur_p->size; ++i) {
        cur_p->data[i].logit /= temp;
    }
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
286
static void llama_sampler_softmax_impl(llama_token_data_array * cur_p, bool do_sort) {
287
    GGML_ASSERT(cur_p->size > 0);
288

Daniel Hiltgen's avatar
Daniel Hiltgen committed
289
290
291
    // Sort the logits in descending order if requested
    if (do_sort && !cur_p->sorted) {
        llama_token_data_array_partial_sort_inplace(cur_p, cur_p->size);
292
293
    }

294
    float max_l = cur_p->data[0].logit;
Daniel Hiltgen's avatar
Daniel Hiltgen committed
295
296
297
298
299
300
    if (!cur_p->sorted) {
        for (size_t i = 1; i < cur_p->size; ++i) {
            max_l = std::max(max_l, cur_p->data[i].logit);
        }
    }

301
    float cum_sum = 0.0f;
302
303
304
305

    for (size_t i = 0; i < cur_p->size; ++i) {
        float p = expf(cur_p->data[i].logit - max_l);
        cur_p->data[i].p = p;
306
307
308
        cum_sum += p;
    }

309
310
    for (size_t i = 0; i < cur_p->size; ++i) {
        cur_p->data[i].p /= cum_sum;
311
312
313
    }
}

314
315
static void llama_sampler_top_k_impl(llama_token_data_array * cur_p, int32_t k) {
    // if (k >= (int32_t)cur_p->size) {
316
317
318
319
    //     return;
    // }

    if (k <= 0) {
320
        return;
321
322
    }

323
    k = std::min(k, (int) cur_p->size);
324
325

    // Sort scores in descending order
326
    if (!cur_p->sorted) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
327
        llama_token_data_array_partial_sort_inplace(cur_p, k);
328
    }
329

330
331
    cur_p->size = k;
}
332

333
334
335
336
337
338
339
340
341
static uint32_t get_rng_seed(uint32_t seed) {
    if (seed == LLAMA_DEFAULT_SEED) {
        // use system clock if std::random_device is not a true RNG
        static bool is_rd_prng = std::random_device().entropy() == 0;
        if (is_rd_prng) {
            return (uint32_t) std::chrono::system_clock::now().time_since_epoch().count();
        }
        std::random_device rd;
        return rd();
342
    }
343
    return seed;
344
345
}

346
347
// llama_sampler API

348
349
350
351
352
353
354
struct llama_sampler * llama_sampler_init(const struct llama_sampler_i * iface, llama_sampler_context_t ctx) {
    return new llama_sampler {
        /* .iface = */ iface,
        /* .ctx   = */ ctx,
    };
}

355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
const char * llama_sampler_name(const struct llama_sampler * smpl) {
    if (!smpl->iface) {
        return "(null)";
    }

    return smpl->iface->name(smpl);
}

void llama_sampler_accept(struct llama_sampler * smpl, llama_token token) {
    if (smpl->iface->accept) {
        smpl->iface->accept(smpl, token);
    }
}

void llama_sampler_apply(struct llama_sampler * smpl, struct llama_token_data_array * cur_p) {
    GGML_ASSERT(smpl->iface->apply);
    smpl->iface->apply(smpl, cur_p);
}

void llama_sampler_reset(struct llama_sampler * smpl) {
    if (smpl->iface->reset) {
        smpl->iface->reset(smpl);
    }
}

struct llama_sampler * llama_sampler_clone(const struct llama_sampler * smpl) {
    if (smpl->iface->clone) {
        return smpl->iface->clone(smpl);
    }

    if (smpl->ctx == nullptr) {
386
        return llama_sampler_init(
387
            /* .iface = */ smpl->iface,
388
389
            /* .ctx   = */ nullptr
        );
390
391
392
393
394
395
396
    }

    GGML_ABORT("the sampler does not support cloning");
}

void llama_sampler_free(struct llama_sampler * smpl) {
    if (smpl == nullptr) {
397
398
399
        return;
    }

400
401
402
403
404
405
406
407
408
409
    if (smpl->iface->free) {
        smpl->iface->free(smpl);
    }

    delete smpl;
}

llama_token llama_sampler_sample(struct llama_sampler * smpl, struct llama_context * ctx, int32_t idx) {
    const auto * logits = llama_get_logits_ith(ctx, idx);

410
411
412
413
    const llama_model * model = llama_get_model(ctx);
    const llama_vocab * vocab = llama_model_get_vocab(model);

    const int n_vocab = llama_vocab_n_tokens(vocab);
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510

    // TODO: do not allocate each time
    std::vector<llama_token_data> cur;
    cur.reserve(n_vocab);
    for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
        cur.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
    }

    llama_token_data_array cur_p = {
        /* .data       = */ cur.data(),
        /* .size       = */ cur.size(),
        /* .selected   = */ -1,
        /* .sorted     = */ false,
    };

    llama_sampler_apply(smpl, &cur_p);

    GGML_ASSERT(cur_p.selected >= 0 && cur_p.selected < (int32_t) cur_p.size);

    auto token = cur_p.data[cur_p.selected].id;

    llama_sampler_accept(smpl, token);

    return token;
}

// sampler chain

static const char * llama_sampler_chain_name(const struct llama_sampler * /*smpl*/) {
    return "chain";
}

static void llama_sampler_chain_accept(struct llama_sampler * smpl, llama_token token) {
    auto * chain = (llama_sampler_chain *) smpl->ctx;

    time_meas tm(chain->t_sample_us, chain->params.no_perf);

    for (auto * smpl : chain->samplers) {
        llama_sampler_accept(smpl, token);
    }

    chain->n_sample++;
}

static void llama_sampler_chain_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
    auto * chain = (llama_sampler_chain *) smpl->ctx;

    time_meas tm(chain->t_sample_us, chain->params.no_perf);

    for (auto * smpl : chain->samplers) {
        llama_sampler_apply(smpl, cur_p);
    }
}

static void llama_sampler_chain_reset(struct llama_sampler * smpl) {
    auto * chain = (llama_sampler_chain *) smpl->ctx;

    for (auto * smpl : chain->samplers) {
        llama_sampler_reset(smpl);
    }

    chain->t_sample_us = 0;
    chain->n_sample    = 0;
}

static struct llama_sampler * llama_sampler_chain_clone(const struct llama_sampler * smpl) {
    const auto * chain_src = (const llama_sampler_chain *) smpl->ctx;

    auto * result = llama_sampler_chain_init(chain_src->params);

    for (auto * smpl : chain_src->samplers) {
        llama_sampler_chain_add(result, llama_sampler_clone(smpl));
    }

    return result;
}

static void llama_sampler_chain_free(struct llama_sampler * smpl) {
    auto * chain = (llama_sampler_chain *) smpl->ctx;

    for (auto * smpl : chain->samplers) {
        llama_sampler_free(smpl);
    }

    delete chain;
}

static struct llama_sampler_i llama_sampler_chain_i = {
    /* .name   = */ llama_sampler_chain_name,
    /* .accept = */ llama_sampler_chain_accept,
    /* .apply  = */ llama_sampler_chain_apply,
    /* .reset  = */ llama_sampler_chain_reset,
    /* .clone  = */ llama_sampler_chain_clone,
    /* .free   = */ llama_sampler_chain_free,
};

struct llama_sampler * llama_sampler_chain_init(struct llama_sampler_chain_params params) {
511
    return llama_sampler_init(
512
513
514
515
516
517
        /* .iface = */ &llama_sampler_chain_i,
        /* .ctx   = */ new llama_sampler_chain {
            /* .params      = */ params,
            /* .samplers    = */ {},
            /* .t_sample_us = */ 0,
            /* .n_sample    = */ 0,
518
519
        }
    );
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
}

void llama_sampler_chain_add(struct llama_sampler * chain, struct llama_sampler * smpl) {
    auto * p = (llama_sampler_chain *) chain->ctx;
    p->samplers.push_back(smpl);
}

struct llama_sampler * llama_sampler_chain_get(const struct llama_sampler * chain, int32_t i) {
    const auto * p = (const llama_sampler_chain *) chain->ctx;

    if (i < 0 || (size_t) i >= p->samplers.size()) {
        return nullptr;
    }

    return p->samplers[i];
}

struct llama_sampler * llama_sampler_chain_remove(struct llama_sampler * chain, int32_t i) {
    auto * p = (llama_sampler_chain *) chain->ctx;

    if (i < 0 || (size_t) i >= p->samplers.size()) {
        return nullptr;
    }

    auto * result = p->samplers[i];
    p->samplers.erase(p->samplers.begin() + i);

    return result;
}

int llama_sampler_chain_n(const struct llama_sampler * chain) {
    const auto * p = (const llama_sampler_chain *) chain->ctx;

    return p->samplers.size();
}

//
// samplers
//

// greedy

static const char * llama_sampler_greedy_name(const struct llama_sampler * /*smpl*/) {
    return "greedy";
}

static void llama_sampler_greedy_apply(struct llama_sampler * /*smpl*/, llama_token_data_array * cur_p) {
    cur_p->selected = 0;
    for (size_t i = 1; i < cur_p->size; ++i) {
        if (cur_p->data[i].logit > cur_p->data[cur_p->selected].logit) {
            cur_p->selected = i;
        }
    }
}

static struct llama_sampler_i llama_sampler_greedy_i = {
    /* .name   = */ llama_sampler_greedy_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_greedy_apply,
    /* .reset  = */ nullptr,
    /* .clone  = */ nullptr,
    /* .free   = */ nullptr,
};

struct llama_sampler * llama_sampler_init_greedy() {
585
    return llama_sampler_init(
586
        /* .iface = */ &llama_sampler_greedy_i,
587
588
        /* .ctx   = */ nullptr
    );
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
}

// dist

struct llama_sampler_dist {
    const uint32_t seed;
          uint32_t seed_cur;

    std::mt19937 rng;
};

static const char * llama_sampler_dist_name(const struct llama_sampler * /*smpl*/) {
    return "dist";
}

static void llama_sampler_dist_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
    auto * ctx = (llama_sampler_dist *) smpl->ctx;
606

Daniel Hiltgen's avatar
Daniel Hiltgen committed
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
    // edge cases
    if (cur_p->size == 0) {
        cur_p->selected = -1;
        return;
    }

    cur_p->selected = 0;

    if (cur_p->size == 1) {
        cur_p->data[0].p = 1.0f;
        return;
    }

    // max logit for numerical stability
    float max_l = cur_p->data[0].logit;
    if (!cur_p->sorted) {
        for (size_t i = 1; i < cur_p->size; ++i) {
            max_l = std::max(max_l, cur_p->data[i].logit);
        }
    }

    // apply softmax to obtain the probabilities
    double sum_cum = 0.0f;
    for (size_t i = 0; i < cur_p->size; ++i) {
        float p = expf(cur_p->data[i].logit - max_l);
        cur_p->data[i].p = p;
        sum_cum += p;
    }

#if 1
    // sample from the obtained probabilities and normalize the probs in a single pass
    // this is ~3x faster on Mac with full gpt-oss vocab than the version below
    //
    std::uniform_real_distribution<double> dist(0.0f, 1.0f);
    const double rnd = dist(ctx->rng);

          double sum_run = 0.0f;
    const double sum_tgt = sum_cum*rnd;

    bool found = false;
    for (size_t i = 0; i < cur_p->size; ++i) {
        if (!found) {
            // accumulate probs until we reach the target sum
            sum_run += cur_p->data[i].p;
            if (sum_run >= sum_tgt) {
                cur_p->selected = i;
                found = true;
            }
        }

        // normalize probs
        cur_p->data[i].p /= sum_cum;
    }

    // fallback to the last token (don't think this can happen)
    assert(found);
    if (!found) {
        cur_p->selected = cur_p->size - 1;
    }
#else
    // for clarity, this is the same as above but does one pass for normalization and one extra pass for sampling
    for (size_t i = 0; i < cur_p->size; ++i) {
        cur_p->data[i].p /= sum_cum;
    }
671

672
    cur_p->selected = llama_sample_dist(cur_p, ctx->rng);
Daniel Hiltgen's avatar
Daniel Hiltgen committed
673
#endif
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
}

static struct llama_sampler * llama_sampler_dist_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_dist *) smpl->ctx;
    auto * result = llama_sampler_init_dist(ctx->seed);

    // copy the state
    {
        auto * result_ctx = (llama_sampler_dist *) result->ctx;

        result_ctx->rng = ctx->rng;
    }

    return result;
}

static void llama_sampler_dist_reset(struct llama_sampler * smpl) {
    auto * ctx = (llama_sampler_dist *) smpl->ctx;
    ctx->seed_cur = get_rng_seed(ctx->seed);
    ctx->rng.seed(ctx->seed_cur);
}

static void llama_sampler_dist_free(struct llama_sampler * smpl) {
    delete (llama_sampler_dist *) smpl->ctx;
}

static struct llama_sampler_i llama_sampler_dist_i = {
    /* .name   = */ llama_sampler_dist_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_dist_apply,
    /* .reset  = */ llama_sampler_dist_reset,
    /* .clone  = */ llama_sampler_dist_clone,
    /* .free   = */ llama_sampler_dist_free,
};

struct llama_sampler * llama_sampler_init_dist(uint32_t seed) {
    auto seed_cur = get_rng_seed(seed);
711
    return llama_sampler_init(
712
713
714
715
716
        /* .iface = */ &llama_sampler_dist_i,
        /* .ctx   = */ new llama_sampler_dist {
            /* .seed     = */ seed,
            /* .seed_cur = */ seed_cur,
            /* .rng      = */ std::mt19937(seed_cur),
717
718
        }
    );
719
720
721
722
723
724
725
726
727
728
729
730
731
}

// top-k

struct llama_sampler_top_k {
    const int32_t k;
};

static const char * llama_sampler_top_k_name(const struct llama_sampler * /*smpl*/) {
    return "top-k";
}

static void llama_sampler_top_k_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
732
    auto * ctx = (llama_sampler_top_k *) smpl->ctx;
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
    llama_sampler_top_k_impl(cur_p, ctx->k);
}

static struct llama_sampler * llama_sampler_top_k_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_top_k *) smpl->ctx;
    return llama_sampler_init_top_k(ctx->k);
}

static void llama_sampler_top_k_free(struct llama_sampler * smpl) {
    delete (llama_sampler_top_k *) smpl->ctx;
}

static struct llama_sampler_i llama_sampler_top_k_i = {
    /* .name   = */ llama_sampler_top_k_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_top_k_apply,
    /* .reset  = */ nullptr,
    /* .clone  = */ llama_sampler_top_k_clone,
    /* .free   = */ llama_sampler_top_k_free,
};

struct llama_sampler * llama_sampler_init_top_k(int32_t k) {
755
    return llama_sampler_init(
756
757
758
        /* .iface = */ &llama_sampler_top_k_i,
        /* .ctx   = */ new llama_sampler_top_k {
            /* .k = */ k,
759
760
        }
    );
761
762
763
764
765
766
767
}

// top-p

struct llama_sampler_top_p {
    const float  p;
    const size_t min_keep;
Daniel Hiltgen's avatar
Daniel Hiltgen committed
768
769

    std::vector<llama_token_data> buf_sort;
770
771
772
773
774
};

static const char * llama_sampler_top_p_name(const struct llama_sampler * /*smpl*/) {
    return "top-p";
}
775

776
static void llama_sampler_top_p_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
777
    auto * ctx = (llama_sampler_top_p *) smpl->ctx;
778
779
780
781
782

    if (ctx->p >= 1.0f) {
        return;
    }

Daniel Hiltgen's avatar
Daniel Hiltgen committed
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
    llama_sampler_softmax_impl(cur_p, false);

    size_t k = cur_p->size;
    auto * pdata = cur_p->data;

    auto & buf_sort = ctx->buf_sort;

    // if not sorted, try adaptive top-k sorting
    if (!cur_p->sorted && cur_p->size > 1024) {
        k = std::min<size_t>(256, cur_p->size);
        llama_token_data_array_partial_sort(*cur_p, k, buf_sort);
        pdata = buf_sort.data();
    } else if (!cur_p->sorted) {
        // small candidates -> sort inplace
        llama_token_data_array_partial_sort_inplace(cur_p, k);
    }
799
800
801

    // Compute the cumulative probabilities
    float cum_sum = 0.0f;
802
    size_t last_idx = cur_p->size;
803

804
    for (size_t i = 0; i < cur_p->size; ++i) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
805
        cum_sum += pdata[i].p;
806
807
808

        // Check if the running sum is at least p or if we have kept at least min_keep tokens
        // we set the last index to i+1 to indicate that the current iterate should be included in the set
809
        if (cum_sum >= ctx->p && i + 1 >= ctx->min_keep) {
810
811
812
            last_idx = i + 1;
            break;
        }
Daniel Hiltgen's avatar
Daniel Hiltgen committed
813
814
815
816
817
818
819

        // we exceeded the current top-k heuristic -> increase k and continue
        if (!cur_p->sorted && i == k - 1) {
            k = cur_p->size;
            llama_token_data_array_partial_sort(*cur_p, k, buf_sort);
            pdata = buf_sort.data();
        }
820
821
822
    }

    // Resize the output vector to keep only the top-p tokens
Daniel Hiltgen's avatar
Daniel Hiltgen committed
823
824
825
826
827
    if (!cur_p->sorted) {
        std::copy(buf_sort.data(), buf_sort.data() + last_idx, cur_p->data);
        cur_p->sorted = true;
    }

828
829
    cur_p->size = last_idx;
}
830

831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
static struct llama_sampler * llama_sampler_top_p_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_top_p *) smpl->ctx;
    return llama_sampler_init_top_p(ctx->p, ctx->min_keep);
}

static void llama_sampler_top_p_free(struct llama_sampler * smpl) {
    delete (llama_sampler_top_p *) smpl->ctx;
}

static struct llama_sampler_i llama_sampler_top_p_i = {
    /* .name   = */ llama_sampler_top_p_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_top_p_apply,
    /* .reset  = */ nullptr,
    /* .clone  = */ llama_sampler_top_p_clone,
    /* .free   = */ llama_sampler_top_p_free,
};

struct llama_sampler * llama_sampler_init_top_p(float p, size_t min_keep) {
850
    return llama_sampler_init(
851
852
853
854
        /* .iface = */ &llama_sampler_top_p_i,
        /* .ctx   = */ new llama_sampler_top_p {
            /* .p        = */ p,
            /* .min_keep = */ min_keep,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
855
            /* .buf_sort = */ {},
856
857
        }
    );
858
859
860
861
862
863
864
865
866
867
868
}

// min-p

struct llama_sampler_min_p {
    const float  p;
    const size_t min_keep;
};

static const char * llama_sampler_min_p_name(const struct llama_sampler * /*smpl*/) {
    return "min-p";
869
870
}

871
static void llama_sampler_min_p_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
872
    auto * ctx = (llama_sampler_min_p *) smpl->ctx;
873
874

    if (ctx->p <= 0.0f || !cur_p->size) {
875
876
877
878
879
        return;
    }

    bool min_p_applied = false;

880
881
    // if the cur_p aren't sorted, try the unsorted implementation first
    if (!cur_p->sorted) {
882
883
884
        std::vector<llama_token_data> filtered_tokens;

        float max_logit = -FLT_MAX;
885
886
        for (size_t i = 0; i < cur_p->size; ++i) {
            max_logit = std::max(max_logit, cur_p->data[i].logit);
887
        }
888
        const float min_logit = max_logit + logf(ctx->p); // min logit for p_i >= p * p_max
889

890
891
892
        for (size_t i = 0; i < cur_p->size; ++i) {
            if (cur_p->data[i].logit >= min_logit) {
                filtered_tokens.push_back(cur_p->data[i]);
893
894
895
896
            }
        }

        // if we have enough values the operation was a success
897
        if (!filtered_tokens.empty() && filtered_tokens.size() >= ctx->min_keep) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
898
            std::copy(filtered_tokens.begin(), filtered_tokens.end(), cur_p->data);
899
            cur_p->size = filtered_tokens.size();
900
901
902
903
            min_p_applied = true;
        }
    }

904
    // if the cur_p are sorted or the unsorted implementation failed, use this implementation
905
906
    if (!min_p_applied) {
        // Sort the logits in descending order
907
        if (!cur_p->sorted) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
908
            llama_token_data_array_partial_sort_inplace(cur_p, cur_p->size);
909
910
        }

911
        const float min_logit = cur_p->data[0].logit + logf(ctx->p); // min logit for p_i >= p * p_max
912
913
        size_t i = 1; // first token always matches

914
915
        for (; i < cur_p->size; ++i) {
            if (cur_p->data[i].logit < min_logit && i >= ctx->min_keep) {
916
917
918
919
920
                break; // prob too small
            }
        }

        // Resize the output vector to keep only the matching tokens
921
        cur_p->size = i;
922
    }
923
}
924

925
926
927
static struct llama_sampler * llama_sampler_min_p_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_min_p *) smpl->ctx;
    return llama_sampler_init_min_p(ctx->p, ctx->min_keep);
928
929
}

930
931
932
933
934
935
936
937
938
939
940
941
942
943
static void llama_sampler_min_p_free(struct llama_sampler * smpl) {
    delete (llama_sampler_min_p *) smpl->ctx;
}

static struct llama_sampler_i llama_sampler_min_p_i = {
    /* .name   = */ llama_sampler_min_p_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_min_p_apply,
    /* .reset  = */ nullptr,
    /* .clone  = */ llama_sampler_min_p_clone,
    /* .free   = */ llama_sampler_min_p_free,
};

struct llama_sampler * llama_sampler_init_min_p(float p, size_t min_keep) {
944
    return llama_sampler_init(
945
946
947
948
        /* .iface = */ &llama_sampler_min_p_i,
        /* .ctx   = */ new llama_sampler_min_p {
            /* .p        = */ p,
            /* .min_keep = */ min_keep,
949
950
        }
    );
951
952
953
954
955
956
957
958
959
960
961
}

// typical

struct llama_sampler_typical {
    const float  p;
    const size_t min_keep;
};

static const char * llama_sampler_typical_name(const struct llama_sampler * /*smpl*/) {
    return "typical";
962
963
}

964
static void llama_sampler_typical_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
965
    auto * ctx = (llama_sampler_typical *) smpl->ctx;
966

967
968
    // Reference implementation:
    // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
969
    if (ctx->p >= 1.0f) {
970
971
972
973
        return;
    }

    // Compute the softmax of logits and calculate entropy
Daniel Hiltgen's avatar
Daniel Hiltgen committed
974
    llama_sampler_softmax_impl(cur_p, true);
975
976

    float entropy = 0.0f;
977
978
    for (size_t i = 0; i < cur_p->size; ++i) {
        entropy += -cur_p->data[i].p * logf(cur_p->data[i].p);
979
980
981
982
    }

    // Compute the absolute difference between negative log probability and entropy for each candidate
    std::vector<float> shifted_scores;
983
984
    for (size_t i = 0; i < cur_p->size; ++i) {
        float shifted_score = fabsf(-logf(cur_p->data[i].p) - entropy);
985
986
987
988
        shifted_scores.push_back(shifted_score);
    }

    // Sort tokens based on the shifted_scores and their corresponding indices
989
    std::vector<size_t> indices(cur_p->size);
990
991
992
993
994
995
996
997
998
999
1000
1001
    std::iota(indices.begin(), indices.end(), 0);

    std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
        return shifted_scores[a] < shifted_scores[b];
    });

    // Compute the cumulative probabilities
    float cum_sum = 0.0f;
    size_t last_idx = indices.size();

    for (size_t i = 0; i < indices.size(); ++i) {
        size_t idx = indices[i];
1002
        cum_sum += cur_p->data[idx].p;
1003
1004

        // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
1005
        if (cum_sum > ctx->p && (ctx->min_keep == 0 || i >= ctx->min_keep - 1)) {
1006
1007
1008
1009
1010
1011
            last_idx = i + 1;
            break;
        }
    }

    // Resize the output vector to keep only the locally typical tokens
1012
    std::vector<llama_token_data> cur_p_new;
1013
1014
    for (size_t i = 0; i < last_idx; ++i) {
        size_t idx = indices[i];
1015
        cur_p_new.push_back(cur_p->data[idx]);
1016
1017
    }

1018
1019
1020
1021
1022
    // Replace the data in cur_p with the cur_p_new data
    std::copy(cur_p_new.begin(), cur_p_new.end(), cur_p->data);
    cur_p->size = cur_p_new.size();
    cur_p->sorted = false;
}
1023

1024
1025
1026
static struct llama_sampler * llama_sampler_typical_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_typical *) smpl->ctx;
    return llama_sampler_init_typical(ctx->p, ctx->min_keep);
1027
1028
}

1029
1030
1031
static void llama_sampler_typical_free(struct llama_sampler * smpl) {
    delete (llama_sampler_typical *) smpl->ctx;
}
1032

1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
static struct llama_sampler_i llama_sampler_typical_i = {
    /* .name   = */ llama_sampler_typical_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_typical_apply,
    /* .reset  = */ nullptr,
    /* .clone  = */ llama_sampler_typical_clone,
    /* .free   = */ llama_sampler_typical_free,
};

struct llama_sampler * llama_sampler_init_typical(float p, size_t min_keep) {
1043
    return llama_sampler_init(
1044
1045
1046
1047
        /* .iface = */ &llama_sampler_typical_i,
        /* .ctx   = */ new llama_sampler_typical {
            /* .p        = */ p,
            /* .min_keep = */ min_keep,
1048
1049
        }
    );
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
}

// temp

struct llama_sampler_temp {
    const float temp;
};

static const char * llama_sampler_temp_name(const struct llama_sampler * /*smpl*/) {
    return "temp";
}

static void llama_sampler_temp_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
    const auto * ctx = (llama_sampler_temp *) smpl->ctx;
1064
1065

    llama_sampler_temp_impl(cur_p, ctx->temp);
1066
}
1067

1068
1069
1070
1071
static struct llama_sampler * llama_sampler_temp_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_temp *) smpl->ctx;
    return llama_sampler_init_temp(ctx->temp);
}
1072

1073
1074
1075
static void llama_sampler_temp_free(struct llama_sampler * smpl) {
    delete (llama_sampler_temp *) smpl->ctx;
}
1076

1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
static struct llama_sampler_i llama_sampler_temp_i = {
    /* .name   = */ llama_sampler_temp_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_temp_apply,
    /* .reset  = */ nullptr,
    /* .clone  = */ llama_sampler_temp_clone,
    /* .free   = */ llama_sampler_temp_free,
};

struct llama_sampler * llama_sampler_init_temp(float temp) {
1087
    return llama_sampler_init(
1088
1089
1090
        /* .iface = */ &llama_sampler_temp_i,
        /* .ctx   = */ new llama_sampler_temp {
            /*.temp = */ temp,
1091
1092
        }
    );
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
}

// temp-ext

struct llama_sampler_temp_ext {
    const float temp;
    const float delta;
    const float exponent;
};

static const char * llama_sampler_temp_ext_name(const struct llama_sampler * /*smpl*/) {
    return "temp-ext";
}

static void llama_sampler_temp_ext_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1108
    auto * ctx = (llama_sampler_temp_ext *) smpl->ctx;
1109
1110
1111
    if (ctx->delta > 0) {
        const float min_temp = std::max(0.0f, ctx->temp - ctx->delta);
        const float max_temp = ctx->temp + ctx->delta;
1112

1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
        float exponent_val = ctx->exponent;

        // no need to do anything if there is only one (or zero) candidates
        if (cur_p->size <= 1) {
            return;
        }

        // Calculate maximum possible entropy
        float max_entropy = -logf(1.0f / cur_p->size);

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1123
        llama_sampler_softmax_impl(cur_p, true);
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149

        // Calculate entropy of the softmax probabilities
        float entropy = 0.0f;
        for (size_t i = 0; i < cur_p->size; ++i) {
            float prob = cur_p->data[i].p;
            if (prob > 0.0f) { // Ensure no log(0)
                entropy -= prob * logf(prob);
            }
        }

        // Normalize the entropy (max_entropy cannot be 0 here because we checked cur_p->size != 1 above)
        float normalized_entropy = entropy / max_entropy;

        // Map the normalized entropy to the desired temperature range using the power function
        float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);

    #ifdef DEBUG
        LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
        LLAMA_LOG_INFO("Entropy: %f\n", entropy);
        LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
        LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
        LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
        LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
    #endif

        // Apply the dynamically calculated temperature scaling
1150
        llama_sampler_temp_impl(cur_p, dyn_temp);
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173

        // Re-compute softmax probabilities after scaling logits with dynamic temperature
        const double max_l_double = cur_p->data[0].logit;

        double cum_sum_double = 0.0;
        for (size_t i = 0; i < cur_p->size; ++i) {
            double p = exp(cur_p->data[i].logit - max_l_double);
            cur_p->data[i].p = p; // Store the scaled probability
            cum_sum_double += p;
        }

        for (size_t i = 0; i < cur_p->size; ++i) {
            cur_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
        }

    #ifdef DEBUG
        // Print the updated top 25 probabilities after temperature scaling
        LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
        for (size_t i = 0; i < 25 && i < cur_p->size; ++i) {
            LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, cur_p->data[i].p * 100.0f);
        }
    #endif
    } else {
1174
        llama_sampler_temp_impl(cur_p, ctx->temp);
1175
    }
1176
}
1177

1178
1179
1180
1181
static struct llama_sampler * llama_sampler_temp_ext_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_temp_ext *) smpl->ctx;
    return llama_sampler_init_temp_ext(ctx->temp, ctx->delta, ctx->exponent);
}
1182

1183
1184
1185
static void llama_sampler_temp_ext_free(struct llama_sampler * smpl) {
    delete (llama_sampler_temp_ext *) smpl->ctx;
}
1186

1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
static struct llama_sampler_i llama_sampler_temp_ext_i = {
    /* .name   = */ llama_sampler_temp_ext_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_temp_ext_apply,
    /* .reset  = */ nullptr,
    /* .clone  = */ llama_sampler_temp_ext_clone,
    /* .free   = */ llama_sampler_temp_ext_free,
};

struct llama_sampler * llama_sampler_init_temp_ext(float temp, float delta, float exponent) {
1197
    return llama_sampler_init(
1198
1199
1200
1201
1202
        /* .iface = */ &llama_sampler_temp_ext_i,
        /* .ctx   = */ new llama_sampler_temp_ext {
            /* .temp     = */ temp,
            /* .delta    = */ delta,
            /* .exponent = */ exponent,
1203
1204
        }
    );
1205
1206
}

1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
// xtc

struct llama_sampler_xtc {
    const float    probability;
    const float    threshold;
    const size_t   min_keep;

    const uint32_t seed;
    uint32_t       seed_cur;

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1217
    std::mt19937    rng;
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
};

static const char * llama_sampler_xtc_name(const struct llama_sampler * /*smpl*/) {
    return "xtc";
}

static void llama_sample_xtc_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
    auto * ctx = (llama_sampler_xtc *) smpl->ctx;

    if (ctx->probability <= 0.0f
        || ctx->threshold > 0.5f
        || cur_p->size < 2) {
        return;
    }

    std::uniform_real_distribution<float> distribution(0.0f, 1.0f);
    float chance = distribution(ctx->rng);
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1235
1236
1237
    if (chance > ctx->probability) {
        return;
    }
1238

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1239
    llama_sampler_softmax_impl(cur_p, true);
1240
1241
1242
1243
1244
1245

    int pos_last = 0;

    for (size_t i = 0; i < cur_p->size; ++i) {
        if (cur_p->data[i].p >= ctx->threshold) {
            pos_last = i;
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1246
1247
1248
        } else {
            break;
        }
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
    }

    if (cur_p->size - pos_last >= ctx->min_keep && pos_last > 0) {
        cur_p->data += pos_last;
        cur_p->size -= pos_last;
    }
}

static struct llama_sampler * llama_sampler_xtc_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_xtc *) smpl->ctx;
    auto * result = llama_sampler_init_xtc(ctx->probability, ctx->threshold, ctx->min_keep, ctx->seed);

    // copy the state
    {
        auto * result_ctx = (llama_sampler_xtc *) result->ctx;

        result_ctx->rng = ctx->rng;
    }

    return result;
}

static void llama_sampler_xtc_free(struct llama_sampler * smpl) {
    delete (llama_sampler_xtc *) smpl->ctx;
}

static void llama_sampler_xtc_reset(struct llama_sampler * smpl) {
    auto * ctx = (llama_sampler_xtc *) smpl->ctx;
    ctx->seed_cur = get_rng_seed(ctx->seed);
    ctx->rng.seed(ctx->seed_cur);
}

static struct llama_sampler_i llama_sampler_xtc_i = {
    /* .name   = */ llama_sampler_xtc_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sample_xtc_apply,
    /* .reset  = */ llama_sampler_xtc_reset,
    /* .clone  = */ llama_sampler_xtc_clone,
    /* .free   = */ llama_sampler_xtc_free,
};

struct llama_sampler * llama_sampler_init_xtc(float p, float t, size_t min_keep, uint32_t seed) {
    auto seed_cur = get_rng_seed(seed);
1292
    return llama_sampler_init(
1293
1294
1295
1296
1297
1298
1299
1300
        /* .iface = */ &llama_sampler_xtc_i,
        /* .ctx   = */ new llama_sampler_xtc {
            /* .probability   = */ p,
            /* .threshold     = */ t,
            /* .min_keep      = */ min_keep,
            /* .seed          = */ seed,
            /* .seed_cur      = */ seed_cur,
            /* .rng           = */ std::mt19937(seed_cur),
1301
1302
        }
    );
1303
1304
}

1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
// mirostat

struct llama_sampler_mirostat {
    const int32_t n_vocab;

    const uint32_t seed;
          uint32_t seed_cur;

    const float tau;
    const float eta;

    const int32_t m;

    float mu;
1319

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1320
    std::mt19937    rng;
1321
1322
1323
1324
1325
1326
1327
1328
1329
};

static const char * llama_sampler_mirostat_name(const struct llama_sampler * /*smpl*/) {
    return "mirostat";
}

static void llama_sampler_mirostat_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
    auto * ctx = (llama_sampler_mirostat *) smpl->ctx;

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1330
    llama_sampler_softmax_impl(cur_p, true);
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340

    // Estimate s_hat using the most probable m tokens
    float s_hat = 0.0;
    float sum_ti_bi = 0.0;
    float sum_ti_sq = 0.0;
    for (size_t i = 0; i < size_t(ctx->m - 1) && i < cur_p->size - 1; ++i) {
        float t_i = logf(float(i + 2) / float(i + 1));
        float b_i = logf(cur_p->data[i].p / cur_p->data[i + 1].p);
        sum_ti_bi += t_i * b_i;
        sum_ti_sq += t_i * t_i;
1341
    }
1342
1343
1344
1345
1346
1347
1348
    s_hat = sum_ti_bi / sum_ti_sq;

    // Compute k from the estimated s_hat and target surprise value
    float epsilon_hat = s_hat - 1;
    float k = powf((epsilon_hat * powf(2, ctx->mu)) / (1 - powf(ctx->n_vocab, -epsilon_hat)), 1 / s_hat);

    llama_sampler_top_k_impl(cur_p, std::max(int(k), 1));
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1349
1350

    llama_sampler_softmax_impl(cur_p, true);
1351
1352
1353
1354
1355
1356
1357

    const int idx = llama_sample_dist(cur_p, ctx->rng);

    cur_p->selected = idx;

    float observed_surprise = -log2f(cur_p->data[idx].p);
    float e = observed_surprise - ctx->tau;
1358

1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
    // Update mu using the learning rate and error
    ctx->mu = ctx->mu - ctx->eta * e;
}

static struct llama_sampler * llama_sampler_mirostat_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_mirostat *) smpl->ctx;
    auto * result = llama_sampler_init_mirostat(ctx->n_vocab, ctx->seed, ctx->tau, ctx->eta, ctx->m);

    // copy the state
    {
        auto * result_ctx = (llama_sampler_mirostat *) smpl->ctx;

        result_ctx->mu  = ctx->mu;
        result_ctx->rng = ctx->rng;
1373
    }
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399

    return result;
}

static void llama_sampler_mirostat_reset(struct llama_sampler * smpl) {
    auto * ctx = (llama_sampler_mirostat *) smpl->ctx;
    ctx->mu = 2.0f*ctx->tau;
    ctx->seed_cur = get_rng_seed(ctx->seed);
    ctx->rng.seed(ctx->seed_cur);
}

static void llama_sampler_mirostat_free(struct llama_sampler * smpl) {
    delete (llama_sampler_mirostat *) smpl->ctx;
}

static struct llama_sampler_i llama_sampler_mirostat_i = {
    /* .name   = */ llama_sampler_mirostat_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_mirostat_apply,
    /* .reset  = */ llama_sampler_mirostat_reset,
    /* .clone  = */ llama_sampler_mirostat_clone,
    /* .free   = */ llama_sampler_mirostat_free,
};

struct llama_sampler * llama_sampler_init_mirostat(int32_t n_vocab, uint32_t seed, float tau, float eta, int32_t m) {
    auto seed_cur = get_rng_seed(seed);
1400
    return llama_sampler_init(
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
        /* .iface = */ &llama_sampler_mirostat_i,
        /* .ctx   = */ new llama_sampler_mirostat {
            /* .n_vocab  = */ n_vocab,
            /* .seed     = */ seed,
            /* .seed_cur = */ seed_cur,
            /* .tau      = */ tau,
            /* .eta      = */ eta,
            /* .m        = */ m,
            /* .mu       = */ 2.0f*tau,
            /* .rng      = */ std::mt19937(seed_cur),
1411
1412
        }
    );
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
}

// mirostat v2

struct llama_sampler_mirostat_v2 {
    const uint32_t seed;
          uint32_t seed_cur;

    const float tau;
    const float eta;

    float mu;

    std::mt19937 rng;
};

static const char * llama_sampler_mirostat_v2_name(const struct llama_sampler * /*smpl*/) {
    return "mirostat-v2";
}

static void llama_sampler_mirostat_v2_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
    auto * ctx = (llama_sampler_mirostat_v2 *) smpl->ctx;

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1436
    llama_sampler_softmax_impl(cur_p, true);
1437
1438
1439
1440
1441
1442
1443
1444

    // Truncate the words with surprise values greater than mu
    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) {
        return -log2f(candidate.p) > ctx->mu;
    }));

    if (cur_p->size == 0) {
        cur_p->size = 1;
1445
1446
    }

1447
    // Normalize the probabilities of the remaining words
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1448
    llama_sampler_softmax_impl(cur_p, true);
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478

    const int idx = llama_sample_dist(cur_p, ctx->rng);

    cur_p->selected = idx;

    float observed_surprise = -log2f(cur_p->data[idx].p);
    float e = observed_surprise - ctx->tau;

    // Update mu using the learning rate and error
    ctx->mu = ctx->mu - ctx->eta * e;
}

static void llama_sampler_mirostat_v2_reset(struct llama_sampler * smpl) {
    auto * ctx = (llama_sampler_mirostat_v2 *) smpl->ctx;
    ctx->mu = 2.0f*ctx->tau;
    ctx->seed_cur = get_rng_seed(ctx->seed);
    ctx->rng.seed(ctx->seed_cur);
}

static struct llama_sampler * llama_sampler_mirostat_v2_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_mirostat_v2 *) smpl->ctx;

    auto * result = llama_sampler_init_mirostat_v2(ctx->seed, ctx->tau, ctx->eta);

    // copy the state
    {
        auto * result_ctx = (llama_sampler_mirostat_v2 *) result->ctx;

        result_ctx->mu  = ctx->mu;
        result_ctx->rng = ctx->rng;
1479
1480
    }

1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
    return result;
}

static void llama_sampler_mirostat_v2_free(struct llama_sampler * smpl) {
    delete (llama_sampler_mirostat_v2 *) smpl->ctx;
}

static struct llama_sampler_i llama_sampler_mirostat_v2_i = {
    /* .name   = */ llama_sampler_mirostat_v2_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_mirostat_v2_apply,
    /* .reset  = */ llama_sampler_mirostat_v2_reset,
    /* .clone  = */ llama_sampler_mirostat_v2_clone,
    /* .free   = */ llama_sampler_mirostat_v2_free,
};

struct llama_sampler * llama_sampler_init_mirostat_v2(uint32_t seed, float tau, float eta) {
    auto seed_cur = get_rng_seed(seed);
1499
    return llama_sampler_init(
1500
1501
1502
1503
1504
1505
1506
1507
        /* .iface = */ &llama_sampler_mirostat_v2_i,
        /* .ctx   = */ new llama_sampler_mirostat_v2 {
            /* .seed     = */ seed,
            /* .seed_cur = */ seed_cur,
            /* .tau      = */ tau,
            /* .eta      = */ eta,
            /* .mu       = */ 2.0f*tau,
            /* .rng      = */ std::mt19937(seed_cur),
1508
1509
        }
    );
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
}

// grammar

struct llama_sampler_grammar {
    const struct llama_vocab * vocab;

    std::string grammar_str;
    std::string grammar_root;

    struct llama_grammar * grammar;
};

static const char * llama_sampler_grammar_name(const struct llama_sampler * /*smpl*/) {
    return "grammar";
}

static void llama_sampler_grammar_accept_impl(struct llama_sampler * smpl, llama_token token) {
    auto * ctx = (llama_sampler_grammar *) smpl->ctx;
    if (ctx->grammar) {
        llama_grammar_accept_impl(*ctx->grammar, token);
    }
}

static void llama_sampler_grammar_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
    auto * ctx = (llama_sampler_grammar *) smpl->ctx;
    if (ctx->grammar) {
        llama_grammar_apply_impl(*ctx->grammar, cur_p);
    }
}

1541
1542
1543
1544
1545
1546
1547
1548
1549
// Fwd declare to break reset --> init_impl --> llama_sampler_grammar_i --> reset cycle.
static struct llama_sampler * llama_sampler_init_grammar_impl(
        const struct llama_vocab * vocab,
                      const char * grammar_str,
                      const char * grammar_root,
                              bool lazy,
                     const char ** trigger_words,
                            size_t num_trigger_words,
               const llama_token * trigger_tokens,
1550
1551
1552
                            size_t num_trigger_tokens,
                     const char ** trigger_patterns,
                            size_t num_trigger_patterns);
1553

1554
1555
1556
1557
static void llama_sampler_grammar_reset(struct llama_sampler * smpl) {
    auto * ctx = (llama_sampler_grammar *) smpl->ctx;
    if (!ctx->grammar) {
        return;
1558
    }
1559

1560
1561
1562
1563
    std::vector<const char *>  trigger_patterns_c;
    trigger_patterns_c.reserve(ctx->grammar->trigger_patterns.size());
    for (auto & trigger_pattern : ctx->grammar->trigger_patterns) {
        trigger_patterns_c.push_back(trigger_pattern.pattern.c_str());
1564
    }
1565

1566
    auto * grammar_new = llama_grammar_init_impl(ctx->grammar->vocab, nullptr, ctx->grammar_str.c_str(), ctx->grammar_root.c_str(),
1567
                                                 ctx->grammar->lazy, trigger_patterns_c.data(), trigger_patterns_c.size(),
1568
                                                 ctx->grammar->trigger_tokens.data(), ctx->grammar->trigger_tokens.size());
1569
1570
1571

    llama_grammar_free_impl(ctx->grammar);
    ctx->grammar = grammar_new;
1572
1573
}

1574
1575
1576
static struct llama_sampler * llama_sampler_grammar_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_grammar *) smpl->ctx;

1577
1578
    auto * result = llama_sampler_init_grammar_impl(ctx->vocab, nullptr, nullptr, false, nullptr, 0, nullptr, 0, nullptr, 0);
    GGML_ASSERT(result);
1579
1580
1581
1582

    // copy the state
    {
        auto * result_ctx = (llama_sampler_grammar *) result->ctx;
1583

1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
        if (ctx->grammar) {
            result_ctx->grammar_str  = ctx->grammar_str;
            result_ctx->grammar_root = ctx->grammar_root;

            result_ctx->grammar = llama_grammar_clone_impl(*ctx->grammar);
        }
    }

    return result;
}

static void llama_sampler_grammar_free(struct llama_sampler * smpl) {
    const auto * ctx = (llama_sampler_grammar *) smpl->ctx;

    if (ctx->grammar) {
        llama_grammar_free_impl(ctx->grammar);
    }

    delete ctx;
}

static struct llama_sampler_i llama_sampler_grammar_i = {
    /* .name   = */ llama_sampler_grammar_name,
    /* .accept = */ llama_sampler_grammar_accept_impl,
    /* .apply  = */ llama_sampler_grammar_apply,
    /* .reset  = */ llama_sampler_grammar_reset,
    /* .clone  = */ llama_sampler_grammar_clone,
    /* .free   = */ llama_sampler_grammar_free,
};

1614
1615
1616
1617
1618
1619
1620
1621
static struct llama_sampler * llama_sampler_init_grammar_impl(
        const struct llama_vocab * vocab,
                      const char * grammar_str,
                      const char * grammar_root,
                              bool lazy,
                     const char ** trigger_words,
                            size_t num_trigger_words,
               const llama_token * trigger_tokens,
1622
1623
1624
                            size_t num_trigger_tokens,
                     const char ** trigger_patterns,
                            size_t num_trigger_patterns) {
1625
1626
1627
    auto * ctx = new llama_sampler_grammar;

    if (grammar_str != nullptr && grammar_str[0] != '\0') {
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
        // TODO: remove trigger_words support.
        if (trigger_words != nullptr && num_trigger_words > 0) {
            GGML_ASSERT(trigger_patterns == nullptr && num_trigger_patterns == 0);
            std::string trigger_pattern("[\\s\\S]*?(");
            for (size_t i = 0; i < num_trigger_words; ++i) {
                static const std::regex special_chars("[.^$|()*+?\\[\\]{}\\\\]");
                if (i > 0) {
                    trigger_pattern += "|";
                }
                trigger_pattern += std::regex_replace(trigger_words[i], special_chars, "\\$0");
            }
            trigger_pattern += ")[\\s\\S]*";
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1640
            const auto * trigger_pattern_c = trigger_pattern.c_str();
1641
1642
1643
            trigger_patterns = &trigger_pattern_c;
            num_trigger_patterns = 1;
        }
1644
        *ctx = {
1645
            /* .vocab        = */ vocab,
1646
1647
            /* .grammar_str  = */ grammar_str,
            /* .grammar_root = */ grammar_root,
1648
            /* .grammar      = */ llama_grammar_init_impl(vocab, nullptr, grammar_str, grammar_root, lazy, trigger_patterns, num_trigger_patterns, trigger_tokens, num_trigger_tokens),
1649
        };
1650
1651
1652
1653
        if (!ctx->grammar) {
            delete ctx;
            return nullptr;
        }
1654
1655
    } else {
        *ctx = {
1656
            /* .vocab        = */ vocab,
1657
1658
1659
1660
            /* .grammar_str  = */ {},
            /* .grammar_root = */ {},
            /* .grammar      = */ nullptr,
        };
1661
1662
    }

1663
    return llama_sampler_init(
1664
        /* .iface = */ &llama_sampler_grammar_i,
1665
1666
1667
1668
1669
1670
1671
1672
        /* .ctx   = */ ctx
    );
}

struct llama_sampler * llama_sampler_init_grammar(
        const struct llama_vocab * vocab,
                      const char * grammar_str,
                      const char * grammar_root) {
1673
    return llama_sampler_init_grammar_impl(vocab, grammar_str, grammar_root, /* lazy= */ false, nullptr, 0, nullptr, 0, nullptr, 0);
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
}

struct llama_sampler * llama_sampler_init_grammar_lazy(
        const struct llama_vocab * vocab,
                      const char * grammar_str,
                      const char * grammar_root,
                     const char ** trigger_words,
                            size_t num_trigger_words,
               const llama_token * trigger_tokens,
                            size_t num_trigger_tokens) {
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
    return llama_sampler_init_grammar_impl(vocab, grammar_str, grammar_root, /* lazy= */ true, trigger_words, num_trigger_words, trigger_tokens, num_trigger_tokens, nullptr, 0);
}

struct llama_sampler * llama_sampler_init_grammar_lazy_patterns(
        const struct llama_vocab * vocab,
                      const char * grammar_str,
                      const char * grammar_root,
                     const char ** trigger_patterns,
                            size_t num_trigger_patterns,
               const llama_token * trigger_tokens,
                            size_t num_trigger_tokens) {
    return llama_sampler_init_grammar_impl(vocab, grammar_str, grammar_root, /* lazy= */ true, nullptr, 0, trigger_tokens, num_trigger_tokens, trigger_patterns, num_trigger_patterns);
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
}

// penalties

struct llama_sampler_penalties {
    const int32_t penalty_last_n;
    const float   penalty_repeat;
    const float   penalty_freq;
    const float   penalty_present;

    ring_buffer<llama_token> prev;
1707
1708
1709

    // a frequency map to count token occurrences
    std::unordered_map<llama_token, int> token_count;
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
};

static const char * llama_sampler_penalties_name(const struct llama_sampler * /*smpl*/) {
    return "penalties";
}

static void llama_sampler_penalties_accept(struct llama_sampler * smpl, llama_token token) {
    auto * ctx = (llama_sampler_penalties *) smpl->ctx;
    if (ctx->penalty_last_n == 0) {
        return;
1720
    }
1721

1722
    ctx->token_count[token]++;
1723

1724
1725
1726
    // if the ring buffer is full, remove the oldest token
    if (ctx->prev.size() >= (size_t) ctx->penalty_last_n) {
        const auto old = ctx->prev.front();
1727

1728
1729
1730
        ctx->token_count[old]--;
        if (ctx->token_count[old] == 0) {
            ctx->token_count.erase(old);
1731
1732
1733
        }
    }

1734
    ctx->prev.push_back(token);
1735

1736
1737
1738
1739
1740
#if 0
    // sanity check
    std::unordered_map<llama_token, int> tmp;
    for (int i = 0; i < std::min<int>(ctx->penalty_last_n, ctx->prev.size()); ++i) {
        tmp[ctx->prev.rat(i)]++;
1741
    }
1742

1743
1744
1745
1746
1747
1748
    assert(ctx->token_count == tmp);
#endif
}

static void llama_sampler_penalties_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
    auto * ctx = (llama_sampler_penalties *) smpl->ctx;
1749

1750
1751
1752
    if ((ctx->penalty_last_n == 0) ||
        (ctx->penalty_repeat == 1.0f && ctx->penalty_freq == 0.0f && ctx->penalty_present == 0.0f)) {
        return;
1753
1754
    }

1755
1756
    // Apply frequency and presence penalties to the cur_p
    for (size_t i = 0; i < cur_p->size; ++i) {
1757
1758
        const auto token_iter = ctx->token_count.find(cur_p->data[i].id);
        if (token_iter == ctx->token_count.end()) {
1759
1760
1761
1762
1763
            continue;
        }

        const int count = token_iter->second;

1764
1765
        assert(count > 0 && count <= ctx->penalty_last_n);

1766
1767
        // 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.
        // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
1768
1769
        if (cur_p->data[i].logit <= 0) {
            cur_p->data[i].logit *= ctx->penalty_repeat;
1770
        } else {
1771
            cur_p->data[i].logit /= ctx->penalty_repeat;
1772
1773
        }

1774
        cur_p->data[i].logit -= float(count) * ctx->penalty_freq + float(count > 0) * ctx->penalty_present;
1775
1776
    }

1777
    cur_p->sorted = false;
1778
1779
}

1780
1781
1782
static void llama_sampler_penalties_reset(struct llama_sampler * smpl) {
    auto * ctx = (llama_sampler_penalties *) smpl->ctx;
    ctx->prev.clear();
1783
    ctx->token_count.clear();
1784
}
1785

1786
1787
1788
1789
1790
1791
static struct llama_sampler * llama_sampler_penalties_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_penalties *) smpl->ctx;
    auto * result = llama_sampler_init_penalties(
            ctx->penalty_last_n,
            ctx->penalty_repeat,
            ctx->penalty_freq,
1792
            ctx->penalty_present);
1793
1794
1795
1796

    // copy the state
    {
        auto * result_ctx = (llama_sampler_penalties *) result->ctx;
1797

1798
        result_ctx->prev = ctx->prev;
1799
1800
    }

1801
    return result;
1802
1803
}

1804
1805
1806
static void llama_sampler_penalties_free(struct llama_sampler * smpl) {
    delete (llama_sampler_penalties *) smpl->ctx;
}
1807

1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
static struct llama_sampler_i llama_sampler_penalties_i = {
    /* .name   = */ llama_sampler_penalties_name,
    /* .accept = */ llama_sampler_penalties_accept,
    /* .apply  = */ llama_sampler_penalties_apply,
    /* .reset  = */ llama_sampler_penalties_reset,
    /* .clone  = */ llama_sampler_penalties_clone,
    /* .free   = */ llama_sampler_penalties_free,
};

struct llama_sampler * llama_sampler_init_penalties(
        int32_t penalty_last_n,
        float penalty_repeat,
        float penalty_freq,
1821
        float penalty_present) {
1822
1823
    penalty_last_n = std::max(penalty_last_n, 0);

1824
    return llama_sampler_init(
1825
1826
1827
1828
1829
1830
1831
        /* .iface = */ &llama_sampler_penalties_i,
        /* .ctx   = */ new llama_sampler_penalties {
            /* .penalty_last_n  = */ penalty_last_n,
            /* .penalty_repeat  = */ penalty_repeat,
            /* .penalty_freq    = */ penalty_freq,
            /* .penalty_present = */ penalty_present,
            /* .prev            = */ ring_buffer<llama_token>(penalty_last_n),
1832
            /* .token_count     = */ {},
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
        }
    );
}

// top-n-sigma

struct llama_sampler_top_n_sigma {
    const float n;
};

static const char * llama_sampler_top_n_sigma_name(const struct llama_sampler * /*smpl*/) {
    return "top-n-sigma";
}

static void llama_sampler_top_n_sigma_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1848
    auto * ctx = (llama_sampler_top_n_sigma *) smpl->ctx;
1849

1850
1851
1852
1853
    if (ctx->n <= 0.0f || cur_p->size <= 1) {
        return;
    }

1854
1855
1856
    // find max logit and calculate mean
    float max = cur_p->data[0].logit;
    float logits_sum = 0;
1857
    size_t valid_count = 0;
1858
    for (size_t i = 0; i < cur_p->size; ++i) {
1859
1860
1861
1862
1863
1864
1865
        // Only count non-negative infinity values
        if (cur_p->data[i].logit != -INFINITY) {
            if (cur_p->data[i].logit > max) {
                max = cur_p->data[i].logit;
            }
            logits_sum += cur_p->data[i].logit;
            valid_count++;
1866
1867
        }
    }
1868
    float mean = valid_count > 0 ? logits_sum/valid_count : 0;
1869
1870
1871
1872

    // calculate standard deviation
    float acc = 0;
    for (size_t i = 0; i < cur_p->size; ++i) {
1873
1874
1875
1876
        // Skip -infinity in std calculation
        if (cur_p->data[i].logit != -INFINITY) {
            acc += pow(cur_p->data[i].logit - mean, 2);
        }
1877
    }
1878
    float std = valid_count > 0 ? sqrt(acc/valid_count) : 0;
1879

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1880
    // apply mask
1881
1882
1883
1884
1885
    for (size_t i = 0; i < cur_p->size; ++i) {
        if (cur_p->data[i].logit < max - (ctx->n * std)) {
            cur_p->data[i].logit = -INFINITY;
        }
    }
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1886
1887

    llama_sampler_softmax_impl(cur_p, true);
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
}

static struct llama_sampler * llama_sampler_top_n_sigma_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_top_n_sigma *) smpl->ctx;
    return llama_sampler_init_top_n_sigma(ctx->n);
}

static void llama_sampler_top_n_sigma_free(struct llama_sampler * smpl) {
    delete (llama_sampler_top_n_sigma *) smpl->ctx;
}

static struct llama_sampler_i llama_sampler_top_n_sigma_i = {
    /* .name   = */ llama_sampler_top_n_sigma_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_top_n_sigma_apply,
    /* .reset  = */ nullptr,
    /* .clone  = */ llama_sampler_top_n_sigma_clone,
    /* .free   = */ llama_sampler_top_n_sigma_free,
};

struct llama_sampler * llama_sampler_init_top_n_sigma(float n) {
    return llama_sampler_init(
        /* .iface = */ &llama_sampler_top_n_sigma_i,
        /* .ctx   = */ new llama_sampler_top_n_sigma {
            /* .n = */ n,
        }
    );
1915
}
1916

1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
// DRY

struct llama_sampler_dry {
    int32_t total_context_size;

    const float   dry_multiplier;
    const float   dry_base;
    const int32_t dry_allowed_length;
    const int32_t dry_penalty_last_n;

    std::unordered_multimap<llama_token, std::vector<llama_token>> dry_processed_breakers;
    std::vector<int> dry_repeat_count;
    std::unordered_map<llama_token, int> dry_max_token_repeat;
    ring_buffer<llama_token> last_tokens;
};

// Ported from Koboldcpp, original PR: https://github.com/LostRuins/koboldcpp/pull/982 (Original author: pi6am)
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) {
1935
1936
    for (llama_token token_id = 0; token_id < (llama_token) vocab.n_tokens(); token_id++) {
        std::string word = vocab.detokenize({token_id}, true);
1937
1938
1939
        if (word.find(str) != std::string::npos) {
            token_sequences.emplace(token_id, std::vector<llama_token>());
        } else {
1940
1941
            size_t word_len = word.size();
            size_t str_len = str.size();
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
            size_t pos = -1;
            while ((pos = word.find(str[0], pos + 1)) != std::string::npos) {
                bool match = true;
                size_t i;
                for (i = 1; i < str_len && i + pos < word_len; ++i) {
                    if (word[pos + i] != str[i]) {
                        match = false;
                        break;
                    }
                }
                if (match) {
1953
                    std::vector<llama_token> tokenization = vocab.tokenize(str.substr(i), false, false);
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
                    if (max_tail_len >= 0 && tokenization.size() > (size_t)max_tail_len) {
                        tokenization.resize(max_tail_len);
                    }

                    // Ensure we don't already have a duplicate matching tokenization
                    auto its = token_sequences.equal_range(token_id);
                    bool found = false;
                    for (auto it = its.first; it != its.second; ++it) {
                        if (tokenization == it->second) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        token_sequences.emplace(token_id, tokenization);
                    }
                }
            }
        }
    }
}

static const char * llama_sampler_dry_name(const struct llama_sampler * /*smpl*/) {
    return "dry";
}

static void llama_sampler_dry_accept(struct llama_sampler * smpl, llama_token token) {
    auto * ctx = (llama_sampler_dry *) smpl->ctx;
    if (ctx->dry_multiplier == 0.0f || ctx->dry_base < 1.0f || ctx->dry_penalty_last_n == 0) {
        return;
    }

    ctx->last_tokens.push_back(token);
}

// Ported from Koboldcpp, original PR: https://github.com/LostRuins/koboldcpp/pull/982 (Original author: pi6am)
static void llama_sampler_dry_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
    auto * ctx = (llama_sampler_dry *) smpl->ctx;

    if (ctx->dry_multiplier == 0.0f || ctx->dry_base < 1.0f || ctx->dry_penalty_last_n == 0) {
        return;
    }

    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);
    int last_n_repeat = std::min(std::min((int)ctx->last_tokens.size(), effective_dry_penalty_last_n), ctx->total_context_size);

    if (last_n_repeat <= ctx->dry_allowed_length) {
        return;
    }

    ctx->dry_repeat_count.assign(last_n_repeat, 0);
    ctx->dry_max_token_repeat.clear();

    // Step 1: Look for restart sequences to limit the maximum repetition length.
    // Work backwards through the context looking for any token that begins a restart sequence.
    //
    // The collection `restart_sequences` is a mapping from a "head" token to all "tail"
    // sequences that together comprise a restart sequence. This allows us to quickly check
    // whether each token is the head of a complete sequence. Most restart sequences are actually
    // a single token, and for these the "tail" is an empty vector.
    //
    // If the token is a "head", test all restart sequences that begin with this token
    // (there will often only be one sequence for each token, but if sequences like 'aaaq1' and
    // 'aaa1' are used as restart strings, both could start with 'aaa' when tokenized). The
    // longest matching sequence (if any) is used to limit the maximum repetition length.
    //
    // Note that in the case case of a short sequence contained in a longer one, this might fail to
    // find the smallest value for `rep_limit`. For example, if 'amniotic' and 'ni' are both used as
    // restart sequences, 'ni' will be found first, and since it's shorter it will fail to suppress
    // 'otic'. This is a minor issue since fully contained restart sequences are likely to be rare.
    //
    // This is theoretically worst-case O(N^2) for arbitrary restart sequences, which is why we
    // have already clamped the maximum tail sequence length when generating `restart_sequences`.
    // With clamping, this scan is O(N) in the context length.

    int rep_limit = last_n_repeat;
    for (int i = 0; i < last_n_repeat; ++i) {
        llama_token token = ctx->last_tokens.rat(i);
        auto its = ctx->dry_processed_breakers.equal_range(token);
        if (its.first == ctx->dry_processed_breakers.end()) {
            continue;
        }
        int longest_match = -1;
        for (auto it = its.first; it != its.second; ++it) {
            // Note that (*it) does not contain the head character, so seq_len will be
            // the restart sequence length minus 1.
            // In the common case of a single-token restart sequence, (*it) will be empty
            // and we will trivially match.
            int seq_len = (int)it->second.size();
            if (seq_len > longest_match && seq_len <= (int)i) {
                bool match = true;
                for (int offset = 0; offset < seq_len; ++offset) {
                    // The -1 when indexing `last_tokens` is because we already matched the head.
                    if (it->second[offset] != ctx->last_tokens.rat(i - offset - 1)) {
                        match = false;
                        break;
                    }
                }
                if (match) {
                    longest_match = seq_len;
                }
            }
        }
        if (longest_match >= 0) {
            // We found a restart sequence starting `i` tokens from the end and continuing for
            // `longest_match` tokens.
            rep_limit = i - longest_match;
            break;
        }
    }
    if (rep_limit < ctx->dry_allowed_length) {
        return;
    }

    // Step 2: Iterate in reverse over the last N tokens of the context, using the "Z-algorithm" (in
    // the reverse direction) to efficiently compute the positions and lengths of suffixes appearing
    // elsewhere in the context. We limit the suffix length to `rep_limit` to respect restart sequences.
    //
    // This algorithm is not currently documented on Wikipedia, but there is a clear description here:
    // https://ivanyu.me/blog/2014/10/15/z-algorithm/
    //
    // The code below is adapted from the public domain implementation by the same author here:
    // https://github.com/ivanyu/string-algorithms/blob/master/z_algorithm.py
    //
    // Example:
    // Last N tokens: a b c c b c y a b c
    // Repeat counts: 0 0 3 1 0 2 0 0 0 0
    //                    ^
    //   This `3` means that the last three tokens of the context (a b c) also appear here.
    //
    // This step is worst case O(N) since the Z-algorithm is linear, despite the appearance of nested
    // for/while loops. This can be seen by observing that the `lt` and `rt` bounds are set after each
    // repeated suffix is detected (i.e. after each while loop when n > 0). These bound variables
    // ensure that the inner while loops only examine each token in the context once as the outer
    // for loop iterates over the context.

    {
        const int last = last_n_repeat - 1;
Daniel Hiltgen's avatar
Daniel Hiltgen committed
2092
2093
2094

        int rt = 0;
        int lt = 0;
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105

        for (int k = 1; k < last_n_repeat; ++k) {
            if (k > rt) {
                // If k is outside the current Z-box, do naive computation.
                int n = 0;
                while (n + k < last_n_repeat && ctx->last_tokens.rat(n) == ctx->last_tokens.rat(n+k)) {
                    ++n;
                }
                ctx->dry_repeat_count[last - k] = std::min(n, rep_limit);
                if (n > 0) {
                    lt = k;
2106
                    rt = k + n - 1;
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
                }
            } else {
                // If k is inside the current Z-box, consider two cases.

                int p = k - lt; // Pair index.
                int right_part_len = rt - k + 1;

                if (ctx->dry_repeat_count[last - p] < right_part_len) {
                    int n = std::min(ctx->dry_repeat_count[last - p], rep_limit);
                    ctx->dry_repeat_count[last - k] = n;
                } else {
                    int i = rt + 1;
                    while (i < last_n_repeat && ctx->last_tokens.rat(i) == ctx->last_tokens.rat(i - k)) {
                        i += 1;
                    }

                    int n = std::min(i - k, rep_limit);
                    ctx->dry_repeat_count[last - k] = n;
                    lt = k;
                    rt = i - 1;
                }
            }
        }
    }

    // Step 3: Iterate over dry_repeat_count and last_tokens, examining the maximum repeat length
    // that would be generated by emitting each new token that would extend a sequence.
    //
    // Following the same example as above:
    // Last N tokens: a b c c b c y a b c
    // Repeat counts: 0 0 3 1 0 2 0 0 0 0
    //
    // For each non-zero, look ahead one token. This token, if emitted, would extend the repetition.
    // c: 3 -> 4 (from `a b c` to `a b c c`)
    // b: 1 -> 2 (from `c` to `c b`)
    // y: 2 -> 3 (from `b c` to `b c y`)

    for (int i = 0; i < last_n_repeat - 1; ++i) {
        int repeat_len = ctx->dry_repeat_count[i];
        if (repeat_len >= ctx->dry_allowed_length) {
            // This token ends a repeat, so the next token would continue one.
            // By convention, the value of `repeat_len` only includes the tokens currently
            // in the context, not the new token that would be added.
            llama_token token = ctx->last_tokens.rat(last_n_repeat - 2 - i);
            // Track the maximum sequence ending in this token.
            const auto& it = ctx->dry_max_token_repeat.find(token);
            if (it == ctx->dry_max_token_repeat.end() || it->second < repeat_len) {
                ctx->dry_max_token_repeat[token] = repeat_len;
            }
        }
    }

    // Step 4: Apply logit penalties based on the maximum repeat length for relevant tokens.

    // Prevent floating point overflow in `pow(penalty_base, exponent)` by clamping to `max_exponent`.
    // Compute it from `penalty_base` and the approximate log of `std::numeric_limits<float>::max()`
    const float FLOAT_MAX_LOG = 88.7228391f;
    int max_exponent = 0;
    if (ctx->dry_base > 1.000001f) {
        max_exponent = FLOAT_MAX_LOG / std::log(ctx->dry_base);
    }

    for (size_t i = 0; i < cur_p->size; ++i) {
        const auto& af_kvp = ctx->dry_max_token_repeat.find(cur_p->data[i].id);
        if (af_kvp != ctx->dry_max_token_repeat.end()) {
            // Check all sequence breakers starting with this token
            auto range = ctx->dry_processed_breakers.equal_range(cur_p->data[i].id);
            bool is_single_token_breaker = false;

            for (auto it = range.first; it != range.second; ++it) {
                if (it->second.empty()) {
                    is_single_token_breaker = true;
                    break;
                }
            }

            // Apply penalty only if it's not a single-token sequence breaker
            if (!is_single_token_breaker) {
                int repeat_exp = af_kvp->second - ctx->dry_allowed_length;
                if (max_exponent > 0 && repeat_exp > max_exponent) {
                    repeat_exp = max_exponent;
                }
                float penalty = ctx->dry_multiplier * std::pow(ctx->dry_base, repeat_exp);
                cur_p->data[i].logit -= penalty;
            }
        }
    }

    cur_p->sorted = false;
}

static void llama_sampler_dry_reset(struct llama_sampler * smpl) {
    auto * ctx = (llama_sampler_dry *) smpl->ctx;
    ctx->last_tokens.clear();
    ctx->dry_repeat_count.clear();
    ctx->dry_max_token_repeat.clear();
}

static struct llama_sampler * llama_sampler_dry_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (llama_sampler_dry *) smpl->ctx;

    llama_vocab dummy_vocab;

    // dummy vocab is passed because it is only needed for raw sequence breaker processing, which we have already done and will simply be copying
2211
    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);
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237

    // Copy the state, including the processed breakers
    {
        auto * result_ctx = (llama_sampler_dry *) result->ctx;
        result_ctx->dry_processed_breakers = ctx->dry_processed_breakers;
        result_ctx->dry_repeat_count = ctx->dry_repeat_count;
        result_ctx->dry_max_token_repeat = ctx->dry_max_token_repeat;
        result_ctx->last_tokens = ctx->last_tokens;
    }

    return result;
}

static void llama_sampler_dry_free(struct llama_sampler * smpl) {
    delete (llama_sampler_dry *) smpl->ctx;
}

static struct llama_sampler_i llama_sampler_dry_i = {
    /* .name   = */ llama_sampler_dry_name,
    /* .accept = */ llama_sampler_dry_accept,
    /* .apply  = */ llama_sampler_dry_apply,
    /* .reset  = */ llama_sampler_dry_reset,
    /* .clone  = */ llama_sampler_dry_clone,
    /* .free   = */ llama_sampler_dry_free,
};

Daniel Hiltgen's avatar
Daniel Hiltgen committed
2238
2239
struct llama_sampler * llama_sampler_init_dry(const struct llama_vocab * vocab, int32_t n_ctx_train, 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) {
    int32_t effective_dry_penalty_last_n = (dry_penalty_last_n == -1) ? n_ctx_train : std::max(dry_penalty_last_n, 0);
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
    std::unordered_multimap<llama_token, std::vector<llama_token>> processed_breakers;
    const int MAX_CHAR_LEN = 40;
    const int MAX_SEQ_LEN = 20;

    const bool dry_enabled = (dry_multiplier != 0.0f && dry_base >= 1.0f && dry_penalty_last_n != 0);

    if (dry_enabled && seq_breakers != nullptr && num_breakers > 0) {
        // Process sequence breakers
        for (size_t i = 0; i < num_breakers; ++i) {
            if (seq_breakers[i] == nullptr || std::strlen(seq_breakers[i]) == 0) {
                LLAMA_LOG_WARN("skipping null or empty DRY sequence breaker at index %zu\n", i);
                continue;
            }

            std::string sequence_break(seq_breakers[i]);
            if (sequence_break.empty()) {
                LLAMA_LOG_WARN("skipping empty DRY sequence breaker\n");
                continue;
            }

            if (sequence_break.size() > MAX_CHAR_LEN) {
                LLAMA_LOG_WARN("truncating DRY sequence breaker to %d characters\n", MAX_CHAR_LEN);
                sequence_break.resize(MAX_CHAR_LEN);
            }

2265
            get_overlapping_token_sequences(*vocab, sequence_break, processed_breakers, MAX_SEQ_LEN);
2266
2267
2268
        }
    }

2269
    return llama_sampler_init(
2270
2271
        /* .iface = */ &llama_sampler_dry_i,
        /* .ctx   = */ new llama_sampler_dry {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
2272
            /* .total_context_size     = */ n_ctx_train,
2273
2274
2275
2276
2277
2278
2279
2280
            /* .dry_multiplier         = */ dry_multiplier,
            /* .dry_base               = */ dry_base,
            /* .dry_allowed_length     = */ dry_allowed_length,
            /* .dry_penalty_last_n     = */ dry_penalty_last_n,
            /* .dry_processed_breakers = */ std::move(processed_breakers),
            /* .dry_repeat_count       = */ dry_enabled ? std::vector<int>(effective_dry_penalty_last_n, 0) : std::vector<int>{},
            /* .dry_max_token_repeat   = */ {},
            /* .last_tokens            = */ dry_enabled ? ring_buffer<llama_token>(effective_dry_penalty_last_n) : ring_buffer<llama_token>(0),
2281
2282
        }
    );
2283
2284
2285
2286
2287
}

// wrapper for test-sampling.cpp
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) {
    llama_vocab dummy_vocab;
2288
    auto * result = llama_sampler_init_dry(&dummy_vocab, context_size, dry_multiplier, dry_base, dry_allowed_length, dry_penalty_last_n, NULL, 0);
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
    auto * ctx = (llama_sampler_dry *) result->ctx;

    // Process the token-based sequence breakers
    ctx->dry_processed_breakers.clear();
    if (seq_breakers.empty()) {
        LLAMA_LOG_WARN("empty DRY sequence breakers list in llama_sampler_init_dry_testing\n");
    } else {
        for (const auto& breaker : seq_breakers) {
            if (breaker.empty()) {
                LLAMA_LOG_WARN("skipping DRY empty sequence breaker\n");
                continue;
            }
            llama_token head_token = breaker[0];
            std::vector<llama_token> tail_tokens(breaker.begin() + 1, breaker.end());
            ctx->dry_processed_breakers.emplace(head_token, std::move(tail_tokens));
        }

        if (ctx->dry_processed_breakers.empty()) {
            LLAMA_LOG_WARN("no valid DRY sequence breakers processed in llama_sampler_init_dry_testing\n");
        }
    }

    return result;
}

2314
// logit-bias
2315

2316
2317
struct llama_sampler_logit_bias {
    const int32_t n_vocab;
2318

2319
    const std::vector<llama_logit_bias> logit_bias;
2320

2321
2322
2323
2324
2325
    std::vector<llama_logit_bias> to_search;
};

static const char * llama_sampler_logit_bias_name(const struct llama_sampler * /*smpl*/) {
    return "logit-bias";
2326
2327
}

2328
2329
2330
2331
2332
2333
static void llama_sampler_logit_bias_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
    auto * ctx = (llama_sampler_logit_bias *) smpl->ctx;

    if (ctx->logit_bias.empty()) {
        return;
    }
2334

2335
    ctx->to_search.clear();
2336

2337
2338
2339
2340
2341
2342
2343
2344
    // update the candidates that have not been shuffled in the vocabulary (i.e. idx == id)
    for (const auto & lb : ctx->logit_bias) {
        if (lb.token >= 0 && cur_p->size > (size_t) lb.token && cur_p->data[lb.token].id == lb.token) {
            cur_p->data[lb.token].logit += lb.bias;
        } else {
            ctx->to_search.push_back(lb);
        }
    }
2345

2346
2347
    if (ctx->to_search.empty()) {
        return;
2348
2349
    }

2350
2351
2352
2353
2354
2355
2356
2357
    // search for the remaining candidates that were not found in the previous step
    for (size_t i = 0; i < cur_p->size; ++i) {
        for (const auto & lb : ctx->to_search) {
            if (cur_p->data[i].id == lb.token) {
                cur_p->data[i].logit += lb.bias;
                break;
            }
        }
2358
    }
2359
}
2360

2361
2362
2363
2364
static struct llama_sampler * llama_sampler_logit_bias_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_logit_bias *) smpl->ctx;
    return llama_sampler_init_logit_bias(ctx->n_vocab, ctx->logit_bias.size(), ctx->logit_bias.data());
}
2365

2366
2367
2368
static void llama_sampler_logit_bias_free(struct llama_sampler * smpl) {
    delete (llama_sampler_logit_bias *) smpl->ctx;
}
2369

2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
static struct llama_sampler_i llama_sampler_logit_bias_i = {
    /* .name   = */ llama_sampler_logit_bias_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_logit_bias_apply,
    /* .reset  = */ nullptr,
    /* .clone  = */ llama_sampler_logit_bias_clone,
    /* .free   = */ llama_sampler_logit_bias_free,
};

struct llama_sampler * llama_sampler_init_logit_bias(
                         int32_t   n_vocab,
                         int32_t   n_logit_bias,
          const llama_logit_bias * logit_bias) {
2383
    return llama_sampler_init(
2384
2385
2386
2387
2388
        /* .iface = */ &llama_sampler_logit_bias_i,
        /* .ctx   = */ new llama_sampler_logit_bias {
            /* .n_vocab    = */ n_vocab,
            /* .logit_bias = */ std::vector<llama_logit_bias>(logit_bias, logit_bias + n_logit_bias),
            /* .to_search  = */ {},
2389
2390
        }
    );
2391
}
2392

2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
// infill

//#define GGML_DEBUG_SAMPLER_INFILL

struct llama_sampler_infill {
    const struct llama_vocab * vocab;

    std::vector<char> buf0;
    std::vector<char> buf1;
};

static const char * llama_sampler_infill_name(const struct llama_sampler * /*smpl*/) {
    return "infill";
}

static void llama_sampler_infill_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
    auto * ctx = (llama_sampler_infill *) smpl->ctx;

Daniel Hiltgen's avatar
Daniel Hiltgen committed
2411
    llama_sampler_softmax_impl(cur_p, true);
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426

#if defined(GGML_DEBUG_SAMPLER_INFILL)
#define LOG_DBG_CUR LLAMA_LOG_DEBUG
#else
#define LOG_DBG_CUR(...)
#endif

    for (size_t i = 0; i < cur_p->size; ++i) {
        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);
    }

    float p_txt_sum = 0.0f;
    float p_eog_sum = 0.0f;

    for (size_t i = 0; i < cur_p->size; ++i) {
2427
        if (ctx->vocab->is_eog(cur_p->data[i].id)) {
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
            p_eog_sum += cur_p->data[i].p;
        } else {
            p_txt_sum += cur_p->data[i].p;
        }
    }

    const float rat = p_eog_sum == 0.0 ? INFINITY : p_txt_sum / p_eog_sum; GGML_UNUSED(rat);

    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);

    if (3*p_eog_sum*cur_p->size > p_txt_sum) {
        LOG_DBG_CUR("%s: the ratio p_txt/p_eog = %.2f is too low -> sampling EOG\n", __func__, p_txt_sum/p_eog_sum);

        // keep just the EOG tokens
        const auto size_org = cur_p->size;

        cur_p->size = 0;

        float p_sum = 0.0f;

        for (size_t i = 0; i < size_org; ++i) {
2449
            if (ctx->vocab->is_eog(cur_p->data[i].id)) {
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
                p_sum += cur_p->data[i].p;

                cur_p->data[cur_p->size++] = cur_p->data[i];
            }
        }

        // normalize probs
        for (size_t i = 0; i < cur_p->size; ++i) {
            cur_p->data[i].p /= p_sum;
        }

        return;
    }

    size_t n_combined = 0; GGML_UNUSED(n_combined);

    // combine tokens with common prefix
    for (size_t i0 = 0; i0 < cur_p->size; ++i0) {
        for (size_t i1 = 0; i1 < cur_p->size; ++i1) {
            if (cur_p->data[i0].logit == -INFINITY) {
                break;
            }

            if (i0 == i1 || cur_p->data[i1].logit == -INFINITY) {
                continue;
            }

2477
            int len0 = ctx->vocab->token_to_piece(cur_p->data[i0].id, ctx->buf0.data(), ctx->buf0.size(), 0, false);
2478
2479
            if (len0 < 0) {
                ctx->buf0.resize(len0);
2480
                len0 = ctx->vocab->token_to_piece(cur_p->data[i0].id, ctx->buf0.data(), ctx->buf0.size(), 0, false);
2481
2482
2483
                assert(len0 > 0);
            }

2484
            int len1 = ctx->vocab->token_to_piece(cur_p->data[i1].id, ctx->buf1.data(), ctx->buf1.size(), 0, false);
2485
2486
            if (len1 < 0) {
                ctx->buf1.resize(len1);
2487
                len1 = ctx->vocab->token_to_piece(cur_p->data[i1].id, ctx->buf1.data(), ctx->buf1.size(), 0, false);
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
                assert(len1 > 0);
            }

            // token i0 is a prefix of token i1
            if (len0 > 0 && len0 <= len1 && memcmp(ctx->buf0.data(), ctx->buf1.data(), len0) == 0) {
                int dst = i0;
                int src = i1;

                // merge into the token with higher probability
                if (cur_p->data[i1].p > cur_p->data[i0].p) {
                    std::swap(dst, src);
                }

                cur_p->data[dst].p += cur_p->data[src].p;
                cur_p->data[src].logit = -INFINITY;
                cur_p->data[src].p     = 0.0f;

                n_combined++;
            }
        }
    }

    size_t n_non_eog = 0;

    size_t size_org = cur_p->size;

    float p_sum = 0.0f;
    float thold = 0.2f;

    cur_p->size = 0;

    LOG_DBG_CUR("%s: n_combined = %zu, applying thold = %.3f\n", __func__, n_combined, thold);

    for (size_t i = 0; i < size_org; ++i) {
2522
        const bool is_eog = ctx->vocab->is_eog(cur_p->data[i].id);
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542

        if (cur_p->data[i].p < thold && !is_eog) {
            continue;
        }

        if (!is_eog) {
            ++n_non_eog;
        }

        p_sum += cur_p->data[i].p;

        // keep this token
        cur_p->data[cur_p->size++] = cur_p->data[i];
    }

    LOG_DBG_CUR("%s: n_non_eog = %zu\n", __func__, n_non_eog);

    // if no non-EOG tokens are left -> reduce cur_p to single EOT token
    if (n_non_eog == 0) {
        cur_p->size = 1;
2543
        cur_p->data[0].id = ctx->vocab->token_eot();
2544
2545
2546
        if (cur_p->data[0].id == LLAMA_TOKEN_NULL) {
            cur_p->data[0].id = ctx->vocab->token_eos();
        }
2547
2548
        cur_p->data[0].logit = 1.0f;

2549
2550
        GGML_ASSERT(cur_p->data[0].id != LLAMA_TOKEN_NULL);

2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
        return;
    }

    // normalize probs
    for (size_t i = 0; i < cur_p->size; ++i) {
        cur_p->data[i].p /= p_sum;

        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);
    }

    size_org = cur_p->size;
    p_sum = 0.0f;
    thold = 1.0/(n_non_eog + 1);

    cur_p->size = 0;

    LOG_DBG_CUR("%s: applying thold = %.3f\n", __func__, thold);

    for (size_t i = 0; i < size_org; ++i) {
2570
        const bool is_eog = ctx->vocab->is_eog(cur_p->data[i].id);
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592

        if (cur_p->data[i].p < thold && !is_eog) {
            continue;
        }

        p_sum += cur_p->data[i].p;

        cur_p->data[cur_p->size++] = cur_p->data[i];
    }

    // normalize probs
    for (size_t i = 0; i < cur_p->size; ++i) {
        cur_p->data[i].p /= p_sum;

        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);
    }

#undef LOG_DBG_CUR
}

static struct llama_sampler * llama_sampler_infill_clone(const struct llama_sampler * smpl) {
    const auto * ctx = (const llama_sampler_infill *) smpl->ctx;
2593
    return llama_sampler_init_infill(ctx->vocab);
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
}

static void llama_sampler_infill_free(struct llama_sampler * smpl) {
    delete (llama_sampler_infill *) smpl->ctx;
}

static struct llama_sampler_i llama_sampler_infill_i = {
    /* .name   = */ llama_sampler_infill_name,
    /* .accept = */ nullptr,
    /* .apply  = */ llama_sampler_infill_apply,
    /* .reset  = */ nullptr,
    /* .clone  = */ llama_sampler_infill_clone,
    /* .free   = */ llama_sampler_infill_free,
};

2609
2610
struct llama_sampler * llama_sampler_init_infill(const struct llama_vocab * vocab) {
    return llama_sampler_init(
2611
2612
        /* .iface = */ &llama_sampler_infill_i,
        /* .ctx   = */ new llama_sampler_infill {
2613
2614
2615
2616
2617
            /* .vocab = */ vocab,
            /* .buf0  = */ std::vector<char>(512),
            /* .buf1  = */ std::vector<char>(512),
        }
    );
2618
2619
}

2620
// utils
2621

2622
2623
2624
uint32_t llama_sampler_get_seed(const struct llama_sampler * smpl) {
    if (smpl->iface == &llama_sampler_dist_i) {
        return ((const llama_sampler_dist *) smpl->ctx)->seed_cur;
2625
2626
    }

2627
2628
2629
    if (smpl->iface == &llama_sampler_mirostat_i) {
        return ((const llama_sampler_mirostat *) smpl->ctx)->seed_cur;
    }
2630

2631
2632
2633
    if (smpl->iface == &llama_sampler_mirostat_v2_i) {
        return ((const llama_sampler_mirostat_v2 *) smpl->ctx)->seed_cur;
    }
2634

2635
2636
2637
2638
2639
2640
2641
2642
    if (smpl->iface == &llama_sampler_chain_i) {
        const auto * ctx = (const llama_sampler_chain *) smpl->ctx;
        for (auto it = ctx->samplers.rbegin(); it != ctx->samplers.rend(); ++it) {
            const uint32_t seed = llama_sampler_get_seed(*it);
            if (seed != LLAMA_DEFAULT_SEED) {
                return seed;
            }
        }
2643
    }
2644
2645

    return LLAMA_DEFAULT_SEED;
2646
2647
}

2648
// perf
2649

2650
2651
struct llama_perf_sampler_data llama_perf_sampler(const struct llama_sampler * chain) {
    struct llama_perf_sampler_data data = {};
2652

2653
2654
    if (chain == nullptr || chain->iface != &llama_sampler_chain_i) {
        GGML_ABORT("%s: invalid sampler passed - requires a sampler created with llama_sampler_chain_init()\n", __func__);
2655
2656
    }

2657
    const auto * ctx = (const struct llama_sampler_chain *) chain->ctx;
2658

2659
2660
    data.t_sample_ms = 1e-3 * ctx->t_sample_us;
    data.n_sample    = std::max(0, ctx->n_sample);
2661

2662
2663
    return data;
}
2664

2665
2666
2667
2668
2669
void llama_perf_sampler_print(const struct llama_sampler * chain) {
    const auto data = llama_perf_sampler(chain);

    LLAMA_LOG_INFO("%s:    sampling time = %10.2f ms / %5d runs   (%8.2f ms per token, %8.2f tokens per second)\n",
            __func__, data.t_sample_ms, data.n_sample, data.t_sample_ms / data.n_sample, 1e3 / data.t_sample_ms * data.n_sample);
2670
2671
}

2672
2673
2674
2675
2676
2677
2678
2679
void llama_perf_sampler_reset(struct llama_sampler * chain) {
    if (chain == nullptr || chain->iface != &llama_sampler_chain_i) {
        GGML_ABORT("%s: invalid sampler passed - requires a sampler created with llama_sampler_chain_init()\n", __func__);
    }

    auto * ctx = (struct llama_sampler_chain *) chain->ctx;

    ctx->t_sample_us = ctx->n_sample = 0;
2680
}