Coverage Report

Created: 2026-01-09 06:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/common/sampling.cpp
Line
Count
Source
1
#include "sampling.h"
2
3
#include "common.h"
4
#include "log.h"
5
6
#include <algorithm>
7
#include <cmath>
8
#include <cstring>
9
#include <unordered_map>
10
11
// the ring buffer works similarly to std::deque, but with a fixed capacity
12
// TODO: deduplicate with llama-impl.h
13
template<typename T>
14
struct ring_buffer {
15
0
    ring_buffer(size_t cap) : capacity(cap), data(cap) {}
16
17
    T & front() {
18
        if (sz == 0) {
19
            throw std::runtime_error("ring buffer is empty");
20
        }
21
        return data[first];
22
    }
23
24
    const T & front() const {
25
        if (sz == 0) {
26
            throw std::runtime_error("ring buffer is empty");
27
        }
28
        return data[first];
29
    }
30
31
    T & back() {
32
        if (sz == 0) {
33
            throw std::runtime_error("ring buffer is empty");
34
        }
35
        return data[pos];
36
    }
37
38
    const T & back() const {
39
        if (sz == 0) {
40
            throw std::runtime_error("ring buffer is empty");
41
        }
42
        return data[pos];
43
    }
44
45
0
    void push_back(const T & value) {
46
0
        if (sz == capacity) {
47
            // advance the start when buffer is full
48
0
            first = (first + 1) % capacity;
49
0
        } else {
50
0
            sz++;
51
0
        }
52
0
        data[pos] = value;
53
0
        pos = (pos + 1) % capacity;
54
0
    }
55
56
    T pop_front() {
57
        if (sz == 0) {
58
            throw std::runtime_error("ring buffer is empty");
59
        }
60
        T value = data[first];
61
        first = (first + 1) % capacity;
62
        sz--;
63
        return value;
64
    }
65
66
0
    const T & rat(size_t i) const {
67
0
        if (i >= sz) {
68
0
            throw std::runtime_error("ring buffer: index out of bounds");
69
0
        }
70
0
        return data[(first + sz - i - 1) % capacity];
71
0
    }
72
73
    std::vector<T> to_vector() const {
74
        std::vector<T> result;
75
        result.reserve(sz);
76
        for (size_t i = 0; i < sz; i++) {
77
            result.push_back(data[(first + i) % capacity]);
78
        }
79
        return result;
80
    }
81
82
0
    void clear() {
83
        // here only reset the status of the buffer
84
0
        sz = 0;
85
0
        first = 0;
86
0
        pos = 0;
87
0
    }
88
89
    bool empty() const {
90
        return sz == 0;
91
    }
92
93
0
    size_t size() const {
94
0
        return sz;
95
0
    }
96
97
    size_t capacity = 0;
98
    size_t sz = 0;
99
    size_t first = 0;
100
    size_t pos = 0;
101
    std::vector<T> data;
102
};
103
104
struct common_sampler {
105
    common_params_sampling params;
106
107
    struct llama_sampler * grmr;
108
    struct llama_sampler * chain;
109
110
    ring_buffer<llama_token> prev;
111
112
    std::vector<llama_token_data> cur;
113
114
    llama_token_data_array cur_p;
115
116
0
    void reset() {
117
0
        prev.clear();
118
119
0
        llama_sampler_reset(chain);
120
0
    }
121
122
0
    void set_logits(struct llama_context * ctx, int idx) {
123
0
        const float *       sampled_probs  = llama_get_sampled_probs_ith     (ctx, idx);
124
0
        const float *       sampled_logits = llama_get_sampled_logits_ith    (ctx, idx);
125
0
        const llama_token * sampled_ids    = llama_get_sampled_candidates_ith(ctx, idx);
126
127
0
        const llama_model * model = llama_get_model(ctx);
128
0
        const llama_vocab * vocab = llama_model_get_vocab(model);
129
130
0
        const int n_vocab = llama_vocab_n_tokens(vocab);
131
132
0
        if (sampled_probs) {
133
0
            const uint32_t sampled_probs_count = llama_get_sampled_probs_count_ith(ctx, idx);
134
0
            cur.resize(sampled_probs_count);
135
0
            for (uint32_t i = 0; i < sampled_probs_count; ++i) {
136
0
                cur[i] = llama_token_data{sampled_ids[i], sampled_logits[i], sampled_probs[i]};
137
0
            }
138
0
        } else if (sampled_logits) {
139
0
            const uint32_t sampled_logits_count = llama_get_sampled_logits_count_ith(ctx, idx);
140
0
            cur.resize(sampled_logits_count);
141
0
            for (uint32_t i = 0; i < sampled_logits_count; i++) {
142
0
                cur[i] = llama_token_data{sampled_ids[i], sampled_logits[i], 0.0f};
143
0
            }
144
0
        } else {
145
0
            const auto * logits = llama_get_logits_ith(ctx, idx);
146
0
            GGML_ASSERT(logits != nullptr);
147
0
            cur.resize(n_vocab);
148
0
            for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
149
0
                cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
150
0
            }
151
0
        }
152
153
0
        cur_p = { cur.data(), cur.size(), -1, false };
154
0
    }
155
156
0
    common_time_meas tm() {
157
0
        return common_time_meas(t_total_us, params.no_perf);
158
0
    }
159
160
    mutable int64_t t_total_us = 0;
161
};
162
163
0
std::string common_params_sampling::print() const {
164
0
    char result[1024];
165
166
0
    snprintf(result, sizeof(result),
167
0
            "\trepeat_last_n = %d, repeat_penalty = %.3f, frequency_penalty = %.3f, presence_penalty = %.3f\n"
168
0
            "\tdry_multiplier = %.3f, dry_base = %.3f, dry_allowed_length = %d, dry_penalty_last_n = %d\n"
169
0
            "\ttop_k = %d, top_p = %.3f, min_p = %.3f, xtc_probability = %.3f, xtc_threshold = %.3f, typical_p = %.3f, top_n_sigma = %.3f, temp = %.3f\n"
170
0
            "\tmirostat = %d, mirostat_lr = %.3f, mirostat_ent = %.3f",
171
0
            penalty_last_n, penalty_repeat, penalty_freq, penalty_present,
172
0
            dry_multiplier, dry_base, dry_allowed_length, dry_penalty_last_n,
173
0
            top_k, top_p, min_p, xtc_probability, xtc_threshold, typ_p, top_n_sigma, temp,
174
0
            mirostat, mirostat_eta, mirostat_tau);
175
176
0
    return std::string(result);
177
0
}
178
179
0
struct common_sampler * common_sampler_init(const struct llama_model * model, struct common_params_sampling & params) {
180
0
    const llama_vocab * vocab = llama_model_get_vocab(model);
181
182
0
    llama_sampler_chain_params lparams = llama_sampler_chain_default_params();
183
184
0
    lparams.no_perf = params.no_perf;
185
186
0
    llama_sampler * grmr = nullptr;
187
0
    llama_sampler * chain = llama_sampler_chain_init(lparams);
188
189
0
    std::vector<llama_sampler *> samplers;
190
191
0
    if (params.grammar.compare(0, 11, "%llguidance") == 0) {
192
#ifdef LLAMA_USE_LLGUIDANCE
193
        grmr = llama_sampler_init_llg(vocab, "lark", params.grammar.c_str());
194
#else
195
0
        GGML_ABORT("llguidance (cmake -DLLAMA_LLGUIDANCE=ON) is not enabled");
196
0
#endif // LLAMA_USE_LLGUIDANCE
197
0
    } else {
198
0
        std::vector<std::string> trigger_patterns;
199
0
        std::vector<llama_token> trigger_tokens;
200
0
        for (const auto & trigger : params.grammar_triggers) {
201
0
            switch (trigger.type) {
202
0
                case COMMON_GRAMMAR_TRIGGER_TYPE_WORD:
203
0
                {
204
0
                    const auto & word = trigger.value;
205
0
                    trigger_patterns.push_back(regex_escape(word));
206
0
                    break;
207
0
                }
208
0
                case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN:
209
0
                {
210
0
                    trigger_patterns.push_back(trigger.value);
211
0
                    break;
212
0
                }
213
0
                case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL:
214
0
                {
215
0
                    const auto & pattern = trigger.value;
216
0
                    std::string anchored = "^$";
217
0
                    if (!pattern.empty()) {
218
0
                        anchored = (pattern.front() != '^' ? "^" : "")
219
0
                            + pattern
220
0
                            + (pattern.back() != '$' ? "$" : "");
221
0
                    }
222
0
                    trigger_patterns.push_back(anchored);
223
0
                    break;
224
0
                }
225
0
                case COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN:
226
0
                {
227
0
                    const auto token = trigger.token;
228
0
                    trigger_tokens.push_back(token);
229
0
                    break;
230
0
                }
231
0
                default:
232
0
                    GGML_ASSERT(false && "unknown trigger type");
233
0
            }
234
0
        }
235
236
0
        std::vector<const char *> trigger_patterns_c;
237
0
        trigger_patterns_c.reserve(trigger_patterns.size());
238
0
        for (const auto & regex : trigger_patterns) {
239
0
            trigger_patterns_c.push_back(regex.c_str());
240
0
        }
241
242
0
        if (!params.grammar.empty()) {
243
0
             if (params.grammar_lazy) {
244
0
                 grmr = llama_sampler_init_grammar_lazy_patterns(vocab, params.grammar.c_str(), "root",
245
0
                         trigger_patterns_c.data(), trigger_patterns_c.size(),
246
0
                         trigger_tokens.data(), trigger_tokens.size());
247
0
             } else {
248
0
                 grmr = llama_sampler_init_grammar(vocab, params.grammar.c_str(), "root");
249
0
             }
250
0
        }
251
0
    }
252
253
0
    if (params.has_logit_bias()) {
254
0
        samplers.push_back(llama_sampler_init_logit_bias(llama_vocab_n_tokens(vocab), params.logit_bias.size(), params.logit_bias.data()));
255
0
    }
256
257
0
    if (params.mirostat == 0) {
258
0
        for (const auto & cnstr : params.samplers) {
259
0
            switch (cnstr) {
260
0
                case COMMON_SAMPLER_TYPE_DRY:
261
0
                    {
262
0
                        std::vector<const char *> c_breakers;
263
0
                        c_breakers.reserve(params.dry_sequence_breakers.size());
264
0
                        for (const auto & str : params.dry_sequence_breakers) {
265
0
                            c_breakers.push_back(str.c_str());
266
0
                        }
267
268
0
                        samplers.push_back(llama_sampler_init_dry    (vocab, llama_model_n_ctx_train(model), params.dry_multiplier, params.dry_base, params.dry_allowed_length, params.dry_penalty_last_n, c_breakers.data(), c_breakers.size()));
269
0
                    }
270
0
                    break;
271
0
                case COMMON_SAMPLER_TYPE_TOP_K:
272
0
                    samplers.push_back(llama_sampler_init_top_k      (params.top_k));
273
0
                    break;
274
0
                case COMMON_SAMPLER_TYPE_TOP_P:
275
0
                    samplers.push_back(llama_sampler_init_top_p      (params.top_p, params.min_keep));
276
0
                    break;
277
0
                case COMMON_SAMPLER_TYPE_TOP_N_SIGMA:
278
0
                    samplers.push_back(llama_sampler_init_top_n_sigma(params.top_n_sigma));
279
0
                    break;
280
0
                case COMMON_SAMPLER_TYPE_MIN_P:
281
0
                    samplers.push_back(llama_sampler_init_min_p      (params.min_p, params.min_keep));
282
0
                    break;
283
0
                case COMMON_SAMPLER_TYPE_XTC:
284
0
                    samplers.push_back(llama_sampler_init_xtc        (params.xtc_probability, params.xtc_threshold, params.min_keep, params.seed));
285
0
                    break;
286
0
                case COMMON_SAMPLER_TYPE_TYPICAL_P:
287
0
                    samplers.push_back(llama_sampler_init_typical    (params.typ_p, params.min_keep));
288
0
                    break;
289
0
                case COMMON_SAMPLER_TYPE_TEMPERATURE:
290
0
                    samplers.push_back(llama_sampler_init_temp_ext   (params.temp, params.dynatemp_range, params.dynatemp_exponent));
291
0
                    break;
292
0
                case COMMON_SAMPLER_TYPE_INFILL:
293
0
                    samplers.push_back(llama_sampler_init_infill     (vocab));
294
0
                    break;
295
0
                case COMMON_SAMPLER_TYPE_PENALTIES:
296
0
                    samplers.push_back(llama_sampler_init_penalties  (params.penalty_last_n, params.penalty_repeat, params.penalty_freq, params.penalty_present));
297
0
                    break;
298
0
                default:
299
0
                    GGML_ASSERT(false && "unknown sampler type");
300
0
            }
301
0
        }
302
303
0
        samplers.push_back(llama_sampler_init_dist(params.seed));
304
0
    } else if (params.mirostat == 1) {
305
0
        samplers.push_back(llama_sampler_init_temp(params.temp));
306
0
        samplers.push_back(llama_sampler_init_mirostat(llama_vocab_n_tokens(vocab), params.seed, params.mirostat_tau, params.mirostat_eta, 100));
307
0
    } else if (params.mirostat == 2) {
308
0
        samplers.push_back(llama_sampler_init_temp(params.temp));
309
0
        samplers.push_back(llama_sampler_init_mirostat_v2(params.seed, params.mirostat_tau, params.mirostat_eta));
310
0
    } else {
311
0
        GGML_ASSERT(false && "unknown mirostat version");
312
0
    }
313
314
0
    for (auto * smpl : samplers) {
315
0
        llama_sampler_chain_add(chain, smpl);
316
0
    }
317
318
0
    if (grmr && params.backend_sampling) {
319
0
        LOG_WRN("%s: backend sampling is not compatible with grammar, disabling\n", __func__);
320
321
0
        params.backend_sampling = false;
322
0
    }
323
324
0
    auto * result = new common_sampler {
325
0
        /* .params  = */ params,
326
0
        /* .grmr    = */ grmr,
327
0
        /* .chain   = */ chain,
328
0
        /* .prev    = */ ring_buffer<llama_token>(std::max(32, params.n_prev)),
329
0
        /* .cur     = */ {},
330
0
        /* .cur_p   = */ {},
331
0
    };
332
333
0
    return result;
334
0
}
335
336
0
void common_sampler_free(struct common_sampler * gsmpl) {
337
0
    if (gsmpl) {
338
0
        llama_sampler_free(gsmpl->grmr);
339
0
        llama_sampler_free(gsmpl->chain);
340
341
0
        delete gsmpl;
342
0
    }
343
0
}
344
345
0
void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, bool accept_grammar) {
346
0
    const auto tm = gsmpl->tm();
347
348
0
    if (gsmpl->grmr && accept_grammar) {
349
0
        llama_sampler_accept(gsmpl->grmr, token);
350
0
    }
351
352
0
    llama_sampler_accept(gsmpl->chain, token);
353
354
0
    gsmpl->prev.push_back(token);
355
0
}
356
357
0
void common_sampler_reset(struct common_sampler * gsmpl) {
358
0
    gsmpl->reset();
359
0
}
360
361
0
struct common_sampler * common_sampler_clone(common_sampler * gsmpl) {
362
0
    return new common_sampler {
363
0
        /* .params  = */ gsmpl->params,
364
0
        /* .grmr    = */ llama_sampler_clone(gsmpl->grmr),
365
0
        /* .chain   = */ llama_sampler_clone(gsmpl->chain),
366
0
        /* .prev    = */ gsmpl->prev,
367
0
        /* .cur     = */ gsmpl->cur,
368
0
        /* .cur_p   = */ gsmpl->cur_p,
369
0
    };
370
0
}
371
372
0
void common_perf_print(const struct llama_context * ctx, const struct common_sampler * gsmpl) {
373
    // TODO: measure grammar performance
374
375
0
    const double t_sampling_ms = gsmpl ? 1e-3*gsmpl->t_total_us : 0;
376
377
0
    llama_perf_sampler_data data_smpl;
378
0
    llama_perf_context_data data_ctx;
379
380
0
    memset(&data_smpl, 0, sizeof(data_smpl));
381
0
    memset(&data_ctx,  0, sizeof(data_ctx));
382
383
0
    if (gsmpl) {
384
0
        auto & data = data_smpl;
385
386
0
        data = llama_perf_sampler(gsmpl->chain);
387
388
        // note: the sampling time includes the samplers time + extra time spent in common/sampling
389
0
        LOG_INF("%s:    sampling time = %10.2f ms\n", __func__, t_sampling_ms);
390
0
        LOG_INF("%s:    samplers time = %10.2f ms / %5d tokens\n", __func__, data.t_sample_ms, data.n_sample);
391
0
    }
392
393
0
    if (ctx) {
394
0
        auto & data = data_ctx;
395
396
0
        data = llama_perf_context(ctx);
397
398
0
        const double t_end_ms = 1e-3 * ggml_time_us();
399
400
0
        const double t_total_ms = t_end_ms - data.t_start_ms;
401
0
        const double t_unacc_ms = t_total_ms - (t_sampling_ms + data.t_p_eval_ms + data.t_eval_ms);
402
0
        const double t_unacc_pc = 100.0 * t_unacc_ms /  t_total_ms;
403
404
0
        LOG_INF("%s:        load time = %10.2f ms\n", __func__, data.t_load_ms);
405
0
        LOG_INF("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
406
0
                __func__, data.t_p_eval_ms, data.n_p_eval, data.t_p_eval_ms / data.n_p_eval, 1e3 / data.t_p_eval_ms * data.n_p_eval);
407
0
        LOG_INF("%s:        eval time = %10.2f ms / %5d runs   (%8.2f ms per token, %8.2f tokens per second)\n",
408
0
                __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
409
0
        LOG_INF("%s:       total time = %10.2f ms / %5d tokens\n", __func__, (t_end_ms - data.t_start_ms), (data.n_p_eval + data.n_eval));
410
0
        LOG_INF("%s: unaccounted time = %10.2f ms / %5.1f %%      (total - sampling - prompt eval - eval) / (total)\n", __func__, t_unacc_ms, t_unacc_pc);
411
0
        LOG_INF("%s:    graphs reused = %10d\n", __func__, data.n_reused);
412
413
0
        llama_memory_breakdown_print(ctx);
414
0
    }
415
0
}
416
417
0
struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl) {
418
0
    return gsmpl->chain;
419
0
}
420
421
0
llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) {
422
0
    llama_synchronize(ctx);
423
424
    // start measuring sampling time after the llama_context synchronization in order to not measure any ongoing async operations
425
0
    const auto tm = gsmpl->tm();
426
427
0
    llama_token id = LLAMA_TOKEN_NULL;
428
429
0
    auto & grmr  = gsmpl->grmr;
430
0
    auto & chain = gsmpl->chain;
431
0
    auto & cur_p = gsmpl->cur_p; // initialized by set_logits
432
433
    // Check if a backend sampler has already sampled a token in which case we
434
    // return that token id directly.
435
0
    {
436
0
        id = llama_get_sampled_token_ith(ctx, idx);
437
438
0
        if (id != LLAMA_TOKEN_NULL) {
439
0
            LOG_DBG("%s: Backend sampler selected token: '%d'. Will not run any CPU samplers\n", __func__, id);
440
441
0
            GGML_ASSERT(!gsmpl->grmr && "using grammar in combination with backend sampling is not supported");
442
443
            // TODO: simplify
444
0
            gsmpl->cur.resize(1);
445
0
            gsmpl->cur[0] = { id, 0.0f, 1.0f };
446
0
            cur_p = { gsmpl->cur.data(), gsmpl->cur.size(), 0, true };
447
448
0
            return id;
449
0
        }
450
0
    }
451
452
0
    gsmpl->set_logits(ctx, idx);
453
454
0
    if (grammar_first) {
455
0
        llama_sampler_apply(grmr, &cur_p);
456
0
    }
457
458
0
    llama_sampler_apply(chain, &cur_p);
459
460
0
    id = cur_p.data[cur_p.selected].id;
461
462
0
    if (grammar_first) {
463
0
        return id;
464
0
    }
465
466
    // check if it the sampled token fits the grammar (grammar-based rejection sampling)
467
0
    {
468
0
        llama_token_data       single_token_data       = { id, 1.0f, 0.0f };
469
0
        llama_token_data_array single_token_data_array = { &single_token_data, 1, -1, false };
470
471
0
        llama_sampler_apply(grmr, &single_token_data_array);
472
473
0
        const bool is_valid = single_token_data_array.data[0].logit != -INFINITY;
474
0
        if (is_valid) {
475
0
            return id;
476
0
        }
477
0
    }
478
479
    // resampling:
480
    // if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain
481
0
    gsmpl->set_logits(ctx, idx);
482
483
0
    llama_sampler_apply(grmr,  &cur_p);
484
0
    llama_sampler_apply(chain, &cur_p);
485
486
0
    GGML_ASSERT(cur_p.selected != -1 && "no selected token during sampling - check your sampling configuration");
487
488
0
    id = cur_p.data[cur_p.selected].id;
489
490
0
    return id;
491
0
}
492
493
0
std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector<int> & idxs, const llama_tokens & draft, bool grammar_first) {
494
0
    GGML_ASSERT(idxs.size() == draft.size() + 1 && "idxs.size() must be draft.size() + 1");
495
496
0
    std::vector<llama_token> result;
497
0
    result.reserve(idxs.size());
498
499
0
    size_t i = 0;
500
0
    for (; i < draft.size(); i++) {
501
0
        const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
502
503
0
        common_sampler_accept(gsmpl, id, true);
504
505
0
        result.push_back(id);
506
507
0
        if (draft[i] != id) {
508
0
            break;
509
0
        }
510
0
    }
511
512
0
    if (i == draft.size()) {
513
0
        const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
514
515
0
        common_sampler_accept(gsmpl, id, true);
516
517
0
        result.push_back(id);
518
0
    }
519
520
0
    return result;
521
0
}
522
523
0
std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const llama_tokens & draft, bool grammar_first) {
524
0
    std::vector<int> idxs(draft.size() + 1);
525
0
    for (size_t i = 0; i < idxs.size(); ++i) {
526
0
        idxs[i] = i;
527
0
    }
528
529
0
    return common_sampler_sample_and_accept_n(gsmpl, ctx, idxs, draft, grammar_first);
530
0
}
531
532
0
uint32_t common_sampler_get_seed(const struct common_sampler * gsmpl) {
533
0
    return llama_sampler_get_seed(gsmpl->chain);
534
0
}
535
536
// helpers
537
538
0
llama_token_data_array * common_sampler_get_candidates(struct common_sampler * gsmpl, bool do_sort) {
539
0
    const auto tm = gsmpl->tm();
540
541
0
    auto * res = &gsmpl->cur_p;
542
543
0
    if (do_sort && !res->sorted) {
544
        // remember the selected token before sorting
545
0
        const llama_token id = res->data[res->selected].id;
546
547
0
        std::sort(res->data, res->data + res->size, [](const llama_token_data & a, const llama_token_data & b) {
548
0
            return a.p > b.p;
549
0
        });
550
551
        // restore the selected token after sorting
552
0
        for (size_t i = 0; i < res->size; ++i) {
553
0
            if (res->data[i].id == id) {
554
0
                res->selected = i;
555
0
                break;
556
0
            }
557
0
        }
558
559
0
        res->sorted = true;
560
0
    }
561
562
0
    return res;
563
0
}
564
565
0
llama_token common_sampler_last(const struct common_sampler * gsmpl) {
566
0
    return gsmpl->prev.rat(0);
567
0
}
568
569
0
std::string common_sampler_print(const struct common_sampler * gsmpl) {
570
0
    std::string result = "logits ";
571
572
0
    for (int i = 0; i < llama_sampler_chain_n(gsmpl->chain); i++) {
573
0
        const auto * smpl = llama_sampler_chain_get(gsmpl->chain, i);
574
0
        result += std::string("-> ");
575
0
        result += std::string(llama_sampler_name(smpl)) + " ";
576
0
    }
577
578
0
    return result;
579
0
}
580
581
0
std::string common_sampler_prev_str(common_sampler * gsmpl, llama_context * ctx_main, int n) {
582
0
    n = std::min(n, (int) gsmpl->prev.size());
583
584
0
    if (n <= 0) {
585
0
        return "";
586
0
    }
587
588
0
    std::string result;
589
0
    result.reserve(8*n); // 8 is the average length of a token [citation needed], TODO: compute this from the vocab
590
591
0
    for (int i = n - 1; i >= 0; i--) {
592
0
        const llama_token id = gsmpl->prev.rat(i);
593
594
0
        GGML_ASSERT(id != LLAMA_TOKEN_NULL && "null token in the sampling history - should not happen");
595
596
0
        result += common_token_to_piece(ctx_main, id);
597
0
    }
598
599
0
    return result;
600
0
}
601
602
0
char common_sampler_type_to_chr(enum common_sampler_type cnstr) {
603
0
    switch (cnstr) {
604
0
        case COMMON_SAMPLER_TYPE_DRY:         return 'd';
605
0
        case COMMON_SAMPLER_TYPE_TOP_K:       return 'k';
606
0
        case COMMON_SAMPLER_TYPE_TYPICAL_P:   return 'y';
607
0
        case COMMON_SAMPLER_TYPE_TOP_P:       return 'p';
608
0
        case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: return 's';
609
0
        case COMMON_SAMPLER_TYPE_MIN_P:       return 'm';
610
0
        case COMMON_SAMPLER_TYPE_TEMPERATURE: return 't';
611
0
        case COMMON_SAMPLER_TYPE_XTC:         return 'x';
612
0
        case COMMON_SAMPLER_TYPE_INFILL:      return 'i';
613
0
        case COMMON_SAMPLER_TYPE_PENALTIES:   return 'e';
614
0
        default : return '?';
615
0
    }
616
0
}
617
618
0
std::string common_sampler_type_to_str(enum common_sampler_type cnstr) {
619
0
    switch (cnstr) {
620
0
        case COMMON_SAMPLER_TYPE_DRY:         return "dry";
621
0
        case COMMON_SAMPLER_TYPE_TOP_K:       return "top_k";
622
0
        case COMMON_SAMPLER_TYPE_TYPICAL_P:   return "typ_p";
623
0
        case COMMON_SAMPLER_TYPE_TOP_P:       return "top_p";
624
0
        case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: return "top_n_sigma";
625
0
        case COMMON_SAMPLER_TYPE_MIN_P:       return "min_p";
626
0
        case COMMON_SAMPLER_TYPE_TEMPERATURE: return "temperature";
627
0
        case COMMON_SAMPLER_TYPE_XTC:         return "xtc";
628
0
        case COMMON_SAMPLER_TYPE_INFILL:      return "infill";
629
0
        case COMMON_SAMPLER_TYPE_PENALTIES:   return "penalties";
630
0
        default : return "";
631
0
    }
632
0
}
633
634
0
std::vector<common_sampler_type> common_sampler_types_from_names(const std::vector<std::string> & names, bool allow_alt_names) {
635
0
    std::unordered_map<std::string, common_sampler_type> sampler_canonical_name_map {
636
0
        { "dry",         COMMON_SAMPLER_TYPE_DRY },
637
0
        { "top_k",       COMMON_SAMPLER_TYPE_TOP_K },
638
0
        { "top_p",       COMMON_SAMPLER_TYPE_TOP_P },
639
0
        { "top_n_sigma", COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
640
0
        { "typ_p",       COMMON_SAMPLER_TYPE_TYPICAL_P },
641
0
        { "min_p",       COMMON_SAMPLER_TYPE_MIN_P },
642
0
        { "temperature", COMMON_SAMPLER_TYPE_TEMPERATURE },
643
0
        { "xtc",         COMMON_SAMPLER_TYPE_XTC },
644
0
        { "infill",      COMMON_SAMPLER_TYPE_INFILL },
645
0
        { "penalties",   COMMON_SAMPLER_TYPE_PENALTIES },
646
0
    };
647
648
    // since samplers names are written multiple ways
649
    // make it ready for both system names and input names
650
0
    std::unordered_map<std::string, common_sampler_type> sampler_alt_name_map {
651
0
        { "top-k",       COMMON_SAMPLER_TYPE_TOP_K },
652
0
        { "top-p",       COMMON_SAMPLER_TYPE_TOP_P },
653
0
        { "top-n-sigma", COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
654
0
        { "nucleus",     COMMON_SAMPLER_TYPE_TOP_P },
655
0
        { "typical-p",   COMMON_SAMPLER_TYPE_TYPICAL_P },
656
0
        { "typical",     COMMON_SAMPLER_TYPE_TYPICAL_P },
657
0
        { "typ-p",       COMMON_SAMPLER_TYPE_TYPICAL_P },
658
0
        { "typ",         COMMON_SAMPLER_TYPE_TYPICAL_P },
659
0
        { "min-p",       COMMON_SAMPLER_TYPE_MIN_P },
660
0
        { "temp",        COMMON_SAMPLER_TYPE_TEMPERATURE },
661
0
    };
662
663
0
    std::vector<common_sampler_type> samplers;
664
0
    samplers.reserve(names.size());
665
666
0
    for (const auto & name : names) {
667
0
        auto sampler = sampler_canonical_name_map.find(name);
668
0
        if (sampler != sampler_canonical_name_map.end()) {
669
0
            samplers.push_back(sampler->second);
670
0
            continue;
671
0
        }
672
0
        if (allow_alt_names) {
673
0
            sampler = sampler_alt_name_map.find(name);
674
0
            if (sampler != sampler_alt_name_map.end()) {
675
0
                samplers.push_back(sampler->second);
676
0
                continue;
677
0
            }
678
0
        }
679
0
        LOG_WRN("%s: unable to match sampler by name '%s'\n", __func__, name.c_str());
680
0
    }
681
682
0
    return samplers;
683
0
}
684
685
0
std::vector<common_sampler_type> common_sampler_types_from_chars(const std::string & chars) {
686
0
    std::unordered_map<char, common_sampler_type> sampler_name_map = {
687
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_DRY),         COMMON_SAMPLER_TYPE_DRY },
688
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_K),       COMMON_SAMPLER_TYPE_TOP_K },
689
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TYPICAL_P),   COMMON_SAMPLER_TYPE_TYPICAL_P },
690
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_P),       COMMON_SAMPLER_TYPE_TOP_P },
691
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_N_SIGMA), COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
692
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_MIN_P),       COMMON_SAMPLER_TYPE_MIN_P },
693
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TEMPERATURE), COMMON_SAMPLER_TYPE_TEMPERATURE },
694
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_XTC),         COMMON_SAMPLER_TYPE_XTC },
695
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_INFILL),      COMMON_SAMPLER_TYPE_INFILL },
696
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_PENALTIES),   COMMON_SAMPLER_TYPE_PENALTIES },
697
0
    };
698
699
0
    std::vector<common_sampler_type> samplers;
700
0
    samplers.reserve(chars.size());
701
702
0
    for (const auto & c : chars) {
703
0
        const auto sampler = sampler_name_map.find(c);
704
0
        if (sampler != sampler_name_map.end()) {
705
0
            samplers.push_back(sampler->second);
706
0
        } else {
707
0
            LOG_WRN("%s: unable to match sampler by char '%c'\n", __func__, c);
708
0
        }
709
0
    }
710
711
0
    return samplers;
712
0
}