Coverage Report

Created: 2026-08-22 07:18

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 "fit.h"
5
#include "log.h"
6
#include "reasoning-budget.h"
7
8
#include "ggml.h"
9
10
#include <algorithm>
11
#include <cctype>
12
#include <climits>
13
#include <cmath>
14
#include <cstring>
15
#include <unordered_map>
16
#include <vector>
17
18
// the ring buffer works similarly to std::deque, but with a fixed capacity
19
// TODO: deduplicate with llama-impl.h
20
template<typename T>
21
struct ring_buffer {
22
0
    ring_buffer(size_t cap) : capacity(cap), data(cap) {}
23
24
    T & front() {
25
        if (sz == 0) {
26
            throw std::runtime_error("ring buffer is empty");
27
        }
28
        return data[first];
29
    }
30
31
    const T & front() const {
32
        if (sz == 0) {
33
            throw std::runtime_error("ring buffer is empty");
34
        }
35
        return data[first];
36
    }
37
38
    T & back() {
39
        if (sz == 0) {
40
            throw std::runtime_error("ring buffer is empty");
41
        }
42
        return data[pos];
43
    }
44
45
    const T & back() const {
46
        if (sz == 0) {
47
            throw std::runtime_error("ring buffer is empty");
48
        }
49
        return data[pos];
50
    }
51
52
0
    void push_back(const T & value) {
53
0
        if (sz == capacity) {
54
            // advance the start when buffer is full
55
0
            first = (first + 1) % capacity;
56
0
        } else {
57
0
            sz++;
58
0
        }
59
0
        data[pos] = value;
60
0
        pos = (pos + 1) % capacity;
61
0
    }
62
63
    T pop_front() {
64
        if (sz == 0) {
65
            throw std::runtime_error("ring buffer is empty");
66
        }
67
        T value = data[first];
68
        first = (first + 1) % capacity;
69
        sz--;
70
        return value;
71
    }
72
73
0
    const T & rat(size_t i) const {
74
0
        if (i >= sz) {
75
0
            throw std::runtime_error("ring buffer: index out of bounds");
76
0
        }
77
0
        return data[(first + sz - i - 1) % capacity];
78
0
    }
79
80
    std::vector<T> to_vector() const {
81
        std::vector<T> result;
82
        result.reserve(sz);
83
        for (size_t i = 0; i < sz; i++) {
84
            result.push_back(data[(first + i) % capacity]);
85
        }
86
        return result;
87
    }
88
89
0
    void clear() {
90
        // here only reset the status of the buffer
91
0
        sz = 0;
92
0
        first = 0;
93
0
        pos = 0;
94
0
    }
95
96
    bool empty() const {
97
        return sz == 0;
98
    }
99
100
0
    size_t size() const {
101
0
        return sz;
102
0
    }
103
104
    size_t capacity = 0;
105
    size_t sz = 0;
106
    size_t first = 0;
107
    size_t pos = 0;
108
    std::vector<T> data;
109
};
110
111
struct common_sampler {
112
    common_params_sampling params;
113
114
    struct llama_sampler * grmr;
115
    struct llama_sampler * rbudget;
116
    struct llama_sampler * chain;
117
118
    ring_buffer<llama_token> prev;
119
120
    std::vector<llama_token_data> cur;
121
122
    llama_token_data_array cur_p;
123
124
0
    void reset() {
125
0
        prev.clear();
126
127
0
        llama_sampler_reset(chain);
128
0
    }
129
130
0
    void set_logits(struct llama_context * ctx, int idx) {
131
0
        const float *       sampled_probs  = llama_get_sampled_probs_ith     (ctx, idx);
132
0
        const float *       sampled_logits = llama_get_sampled_logits_ith    (ctx, idx);
133
0
        const llama_token * sampled_ids    = llama_get_sampled_candidates_ith(ctx, idx);
134
135
0
        const llama_model * model = llama_get_model(ctx);
136
0
        const llama_vocab * vocab = llama_model_get_vocab(model);
137
138
0
        const int n_vocab = llama_vocab_n_tokens(vocab);
139
140
0
        if (sampled_probs) {
141
0
            const uint32_t sampled_probs_count = llama_get_sampled_probs_count_ith(ctx, idx);
142
0
            cur.resize(sampled_probs_count);
143
0
            for (uint32_t i = 0; i < sampled_probs_count; ++i) {
144
0
                cur[i] = llama_token_data{sampled_ids[i], sampled_logits[i], sampled_probs[i]};
145
0
            }
146
0
        } else if (sampled_logits) {
147
0
            const uint32_t sampled_logits_count = llama_get_sampled_logits_count_ith(ctx, idx);
148
0
            cur.resize(sampled_logits_count);
149
0
            for (uint32_t i = 0; i < sampled_logits_count; i++) {
150
0
                cur[i] = llama_token_data{sampled_ids[i], sampled_logits[i], 0.0f};
151
0
            }
152
0
        } else {
153
0
            const auto * logits = llama_get_logits_ith(ctx, idx);
154
0
            GGML_ASSERT(logits != nullptr);
155
0
            cur.resize(n_vocab);
156
0
            for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
157
0
                cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
158
0
            }
159
0
        }
160
161
0
        cur_p = { cur.data(), cur.size(), -1, false };
162
0
    }
163
164
0
    common_time_meas tm() {
165
0
        return common_time_meas(t_total_us, params.no_perf);
166
0
    }
167
168
    mutable int64_t t_total_us = 0;
169
};
170
171
0
std::string common_params_sampling::print() const {
172
0
    char result[1024];
173
174
0
    snprintf(result, sizeof(result),
175
0
            "\trepeat_last_n = %d, repeat_penalty = %.3f, frequency_penalty = %.3f, presence_penalty = %.3f\n"
176
0
            "\tdry_multiplier = %.3f, dry_base = %.3f, dry_allowed_length = %d, dry_penalty_last_n = %d\n"
177
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"
178
0
            "\tmirostat = %d, mirostat_lr = %.3f, mirostat_ent = %.3f, adaptive_target = %.3f, adaptive_decay = %.3f",
179
0
            penalty_last_n, penalty_repeat, penalty_freq, penalty_present,
180
0
            dry_multiplier, dry_base, dry_allowed_length, dry_penalty_last_n,
181
0
            top_k, top_p, min_p, xtc_probability, xtc_threshold, typ_p, top_n_sigma, temp,
182
0
            mirostat, mirostat_eta, mirostat_tau, adaptive_target, adaptive_decay);
183
184
0
    return std::string(result);
185
0
}
186
187
struct common_sampler * common_sampler_init(
188
        const struct llama_model * model,
189
0
        struct common_params_sampling & params) {
190
0
    if (!std::isfinite(params.penalty_repeat) ||
191
0
        params.penalty_repeat <= 0.0f ||
192
0
        !std::isfinite(1.0f/params.penalty_repeat)) {
193
0
        throw std::invalid_argument("penalty_repeat must be finite and greater than 0");
194
0
    }
195
0
    if (!std::isfinite(params.penalty_freq)) {
196
0
        throw std::invalid_argument("penalty_freq must be finite");
197
0
    }
198
0
    if (!std::isfinite(params.penalty_present)) {
199
0
        throw std::invalid_argument("penalty_present must be finite");
200
0
    }
201
0
    const llama_vocab * vocab = llama_model_get_vocab(model);
202
0
    llama_sampler_chain_params lparams = llama_sampler_chain_default_params();
203
204
0
    lparams.no_perf = params.no_perf;
205
206
0
    llama_sampler * grmr = nullptr;
207
0
    llama_sampler * rbudget = nullptr;
208
0
    llama_sampler * chain = llama_sampler_chain_init(lparams);
209
210
0
    std::vector<llama_sampler *> samplers;
211
212
0
    const std::string & grammar_str = common_grammar_value(params.grammar);
213
0
    if (grammar_str.compare(0, 11, "%llguidance") == 0) {
214
#ifdef LLAMA_USE_LLGUIDANCE
215
        grmr = llama_sampler_init_llg(vocab, "lark", grammar_str.c_str());
216
#else
217
0
        GGML_ABORT("llguidance (cmake -DLLAMA_LLGUIDANCE=ON) is not enabled");
218
0
#endif // LLAMA_USE_LLGUIDANCE
219
0
    } else {
220
0
        std::vector<std::string> trigger_patterns;
221
0
        std::vector<llama_token> trigger_tokens;
222
0
        for (const auto & trigger : params.grammar_triggers) {
223
0
            switch (trigger.type) {
224
0
                case COMMON_GRAMMAR_TRIGGER_TYPE_WORD:
225
0
                {
226
0
                    const auto & word = trigger.value;
227
0
                    trigger_patterns.push_back(regex_escape(word));
228
0
                    break;
229
0
                }
230
0
                case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN:
231
0
                {
232
0
                    trigger_patterns.push_back(trigger.value);
233
0
                    break;
234
0
                }
235
0
                case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL:
236
0
                {
237
0
                    const auto & pattern = trigger.value;
238
0
                    std::string anchored = "^$";
239
0
                    if (!pattern.empty()) {
240
0
                        anchored = (pattern.front() != '^' ? "^" : "")
241
0
                            + pattern
242
0
                            + (pattern.back() != '$' ? "$" : "");
243
0
                    }
244
0
                    trigger_patterns.push_back(anchored);
245
0
                    break;
246
0
                }
247
0
                case COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN:
248
0
                {
249
0
                    const auto token = trigger.token;
250
0
                    trigger_tokens.push_back(token);
251
0
                    break;
252
0
                }
253
0
                default:
254
0
                    GGML_ASSERT(false && "unknown trigger type");
255
0
            }
256
0
        }
257
258
0
        std::vector<const char *> trigger_patterns_c;
259
0
        trigger_patterns_c.reserve(trigger_patterns.size());
260
0
        for (const auto & regex : trigger_patterns) {
261
0
            trigger_patterns_c.push_back(regex.c_str());
262
0
        }
263
264
0
        if (!grammar_str.empty()) {
265
0
             if (params.grammar_lazy) {
266
0
                 grmr = llama_sampler_init_grammar_lazy_patterns(vocab, grammar_str.c_str(), "root",
267
0
                         trigger_patterns_c.data(), trigger_patterns_c.size(),
268
0
                         trigger_tokens.data(), trigger_tokens.size());
269
0
             } else {
270
0
                 grmr = llama_sampler_init_grammar(vocab, grammar_str.c_str(), "root");
271
0
             }
272
0
        }
273
0
    }
274
0
    if (!grmr && !grammar_str.empty()) {
275
0
        throw std::runtime_error("failed to parse grammar");
276
0
    }
277
278
    // Compute prefill tokens from the generation prompt
279
0
    std::vector<llama_token> prefill_tokens;
280
0
    if (!params.generation_prompt.empty()) {
281
0
        GGML_ASSERT(vocab != nullptr);
282
0
        auto tokens = common_tokenize(vocab, params.generation_prompt, false, true);
283
0
        for (size_t i = 0; i < tokens.size(); i++) {
284
0
            std::string piece = common_token_to_piece(vocab, tokens[i], true);
285
0
            if (i == 0 && std::isspace(piece[0]) && !std::isspace(params.generation_prompt[0])) {
286
                // Some tokenizers will add a space before the first special token, need to exclude
287
0
                continue;
288
0
            }
289
0
            LOG_DBG("%s: prefill token: %d = %s\n", __func__, tokens[i], piece.c_str());
290
0
            prefill_tokens.push_back(tokens[i]);
291
0
        }
292
0
    }
293
294
    // Feed generation prompt tokens to the grammar sampler so it advances past
295
    // tokens the template already placed in the prompt.
296
    // Only applies to output-format and tool-call grammars; user-supplied grammars must not be prefilled.
297
0
    if (grmr && !params.grammar_lazy && common_grammar_needs_prefill(params.grammar)) {
298
0
        try {
299
0
            for (const auto & token : prefill_tokens) {
300
0
                llama_sampler_accept(grmr, token);
301
0
                LOG_DBG("%s: grammar accepted prefill token (%d)\n", __func__, token);
302
0
            }
303
0
        } catch (std::exception &e) {
304
0
            LOG_ERR("%s: error initializing grammar sampler for grammar:\n%s\n\nGeneration prompt:\n'%s'\n", __func__,
305
0
                common_grammar_value(params.grammar).c_str(), params.generation_prompt.c_str());
306
0
            throw e;
307
0
        }
308
0
    }
309
310
    // reasoning budget sampler (skip when budget is unlimited unless a lazy grammar is active, which needs rbudget for thinking-block suppression)
311
0
    if (!params.reasoning_budget_start.empty() && !params.reasoning_budget_end.empty() && (params.grammar_lazy || params.reasoning_budget_tokens >= 0 || params.reasoning_control)) {
312
0
        rbudget = common_reasoning_budget_init(
313
0
            vocab,
314
0
            {params.reasoning_budget_start},
315
0
            params.reasoning_budget_end,
316
0
            params.reasoning_budget_forced,
317
0
            params.reasoning_budget_tokens < 0 ? INT_MAX : params.reasoning_budget_tokens);
318
319
0
        for (const auto & token : prefill_tokens) {
320
0
            llama_sampler_accept(rbudget, token);
321
0
            LOG_DBG("%s: reasoning-budget accepted prefill token (%d)\n", __func__, token);
322
0
        }
323
0
    }
324
325
    // logit bias: user biases + model suppress tokens (-INFINITY)
326
0
    {
327
0
        std::vector<llama_logit_bias> merged = params.logit_bias;
328
329
0
        int32_t n_suppress = 0;
330
0
        const llama_token * suppress = llama_vocab_get_suppress_tokens(vocab, &n_suppress);
331
0
        for (int32_t i = 0; i < n_suppress; ++i) {
332
0
            merged.push_back({ suppress[i], -INFINITY });
333
0
        }
334
335
0
        if (!merged.empty()) {
336
0
            samplers.push_back(llama_sampler_init_logit_bias(llama_vocab_n_tokens(vocab), merged.size(), merged.data()));
337
0
        }
338
0
    }
339
340
0
    if (params.mirostat == 0) {
341
342
0
        bool use_adaptive_p = false; // see below
343
344
0
        for (const auto & cnstr : params.samplers) {
345
0
            switch (cnstr) {
346
0
                case COMMON_SAMPLER_TYPE_DRY:
347
0
                    {
348
0
                        std::vector<const char *> c_breakers;
349
0
                        c_breakers.reserve(params.dry_sequence_breakers.size());
350
0
                        for (const auto & str : params.dry_sequence_breakers) {
351
0
                            c_breakers.push_back(str.c_str());
352
0
                        }
353
0
                        samplers.push_back(llama_sampler_init_dry(vocab, params.dry_multiplier, params.dry_base, params.dry_allowed_length, params.dry_penalty_last_n, c_breakers.data(), c_breakers.size()));
354
0
                    }
355
0
                    break;
356
0
                case COMMON_SAMPLER_TYPE_TOP_K:
357
0
                    samplers.push_back(llama_sampler_init_top_k(params.top_k));
358
0
                    break;
359
0
                case COMMON_SAMPLER_TYPE_TOP_P:
360
0
                    samplers.push_back(llama_sampler_init_top_p(params.top_p, params.min_keep));
361
0
                    break;
362
0
                case COMMON_SAMPLER_TYPE_TOP_N_SIGMA:
363
0
                    samplers.push_back(llama_sampler_init_top_n_sigma(params.top_n_sigma));
364
0
                    break;
365
0
                case COMMON_SAMPLER_TYPE_MIN_P:
366
0
                    samplers.push_back(llama_sampler_init_min_p(params.min_p, params.min_keep));
367
0
                    break;
368
0
                case COMMON_SAMPLER_TYPE_XTC:
369
0
                    samplers.push_back(llama_sampler_init_xtc(params.xtc_probability, params.xtc_threshold, params.min_keep, params.seed));
370
0
                    break;
371
0
                case COMMON_SAMPLER_TYPE_TYPICAL_P:
372
0
                    samplers.push_back(llama_sampler_init_typical(params.typ_p, params.min_keep));
373
0
                    break;
374
0
                case COMMON_SAMPLER_TYPE_TEMPERATURE:
375
0
                    samplers.push_back(llama_sampler_init_temp_ext(params.temp, params.dynatemp_range, params.dynatemp_exponent));
376
0
                    break;
377
0
                case COMMON_SAMPLER_TYPE_INFILL:
378
0
                    samplers.push_back(llama_sampler_init_infill(vocab));
379
0
                    break;
380
0
                case COMMON_SAMPLER_TYPE_PENALTIES:
381
0
                    samplers.push_back(llama_sampler_init_penalties(llama_vocab_n_tokens(vocab), params.penalty_last_n, params.penalty_repeat, params.penalty_freq, params.penalty_present));
382
0
                    break;
383
0
                case COMMON_SAMPLER_TYPE_ADAPTIVE_P:
384
                    // the `adaptive-p` sampler is like `dist` and `mirostat` in that it selects
385
                    // a single token, so we will add `dist` at the end of the chain by default,
386
                    // unless the user specifically included `adaptive-p`. we set this flag here
387
                    // so we know to add the sampler at the very end.
388
0
                    use_adaptive_p = true;
389
0
                    break;
390
0
                default:
391
0
                    GGML_ASSERT(false && "unknown sampler type");
392
0
            }
393
0
        }
394
0
        if (use_adaptive_p) {
395
            // only if user explicitly included adaptive-p sampler
396
0
            samplers.push_back(llama_sampler_init_adaptive_p(params.adaptive_target, params.adaptive_decay, params.seed));
397
0
        } else {
398
            // default: sample from distribution
399
0
            samplers.push_back(llama_sampler_init_dist(params.seed));
400
0
        }
401
0
    } else if (params.mirostat == 1) {
402
0
        samplers.push_back(llama_sampler_init_temp(params.temp));
403
0
        samplers.push_back(llama_sampler_init_mirostat(llama_vocab_n_tokens(vocab), params.seed, params.mirostat_tau, params.mirostat_eta, 100));
404
0
    } else if (params.mirostat == 2) {
405
0
        samplers.push_back(llama_sampler_init_temp(params.temp));
406
0
        samplers.push_back(llama_sampler_init_mirostat_v2(params.seed, params.mirostat_tau, params.mirostat_eta));
407
0
    } else {
408
0
        GGML_ASSERT(false && "unknown mirostat version");
409
0
    }
410
411
0
    for (auto * smpl : samplers) {
412
0
        llama_sampler_chain_add(chain, smpl);
413
0
    }
414
415
0
    if (grmr && params.backend_sampling) {
416
0
        LOG_WRN("%s: backend sampling is not compatible with grammar, disabling\n", __func__);
417
418
0
        params.backend_sampling = false;
419
0
    }
420
421
0
    if (rbudget && params.backend_sampling) {
422
0
        LOG_WRN("%s: backend sampling is not compatible with reasoning budget, disabling\n", __func__);
423
424
0
        params.backend_sampling = false;
425
0
    }
426
427
0
    auto * result = new common_sampler {
428
0
        /* .params  = */ params,
429
0
        /* .grmr    = */ grmr,
430
0
        /* .rbudget = */ rbudget,
431
0
        /* .chain   = */ chain,
432
0
        /* .prev    = */ ring_buffer<llama_token>(std::max(32, params.n_prev)),
433
0
        /* .cur     = */ {},
434
0
        /* .cur_p   = */ {},
435
0
    };
436
437
0
    return result;
438
0
}
439
440
0
void common_sampler_free(struct common_sampler * gsmpl) {
441
0
    if (!gsmpl) {
442
0
        return;
443
0
    }
444
445
0
    llama_sampler_free(gsmpl->grmr);
446
0
    llama_sampler_free(gsmpl->rbudget);
447
0
    llama_sampler_free(gsmpl->chain);
448
449
0
    delete gsmpl;
450
0
}
451
452
0
static bool grammar_should_apply(struct common_sampler * gsmpl) {
453
0
    if (!gsmpl->grmr) {
454
0
        return false;
455
0
    }
456
0
    if (!gsmpl->rbudget) {
457
0
        return true;
458
0
    }
459
0
    if (gsmpl->params.grammar_lazy) {
460
        // if grammar is lazy, only apply when reasoning budget is not active
461
0
        const auto state = common_reasoning_budget_get_state(gsmpl->rbudget);
462
0
        return state == REASONING_BUDGET_IDLE || state == REASONING_BUDGET_DONE;
463
0
    }
464
0
    return true;
465
0
}
466
467
0
void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, bool is_generated) {
468
0
    if (!gsmpl) {
469
0
        return;
470
0
    }
471
472
0
    const auto tm = gsmpl->tm();
473
474
    // grammar_should_apply() checks the reasoning budget state, so calculate this before we accept
475
0
    const auto accept_grammar = is_generated && grammar_should_apply(gsmpl);
476
477
0
    if (gsmpl->rbudget && is_generated) {
478
0
        llama_sampler_accept(gsmpl->rbudget, token);
479
480
        // if done, replay end sequence which may contain a grammar trigger
481
0
        const bool is_done = common_reasoning_budget_get_state(gsmpl->rbudget) == REASONING_BUDGET_DONE;
482
0
        if (gsmpl->grmr && !accept_grammar && is_done) {
483
0
            const llama_tokens * end_seq = common_reasoning_budget_get_end_match(gsmpl->rbudget);
484
0
            if (end_seq) {
485
0
                for (const llama_token end_token : *end_seq) {
486
0
                    llama_sampler_accept(gsmpl->grmr, end_token);
487
0
                }
488
0
            }
489
0
        }
490
0
    }
491
492
0
    if (gsmpl->grmr && accept_grammar) {
493
0
        llama_sampler_accept(gsmpl->grmr, token);
494
0
    }
495
496
0
    llama_sampler_accept(gsmpl->chain, token);
497
498
0
    gsmpl->prev.push_back(token);
499
0
}
500
501
0
void common_sampler_reset(struct common_sampler * gsmpl) {
502
0
    if (!gsmpl) {
503
0
        return;
504
0
    }
505
506
0
    gsmpl->reset();
507
0
}
508
509
0
struct common_sampler * common_sampler_clone(common_sampler * gsmpl) {
510
0
    return new common_sampler {
511
0
        /* .params  = */ gsmpl->params,
512
0
        /* .grmr    = */ llama_sampler_clone(gsmpl->grmr),
513
0
        /* .rbudget = */ llama_sampler_clone(gsmpl->rbudget),
514
0
        /* .chain   = */ llama_sampler_clone(gsmpl->chain),
515
0
        /* .prev    = */ gsmpl->prev,
516
0
        /* .cur     = */ gsmpl->cur,
517
0
        /* .cur_p   = */ gsmpl->cur_p,
518
0
    };
519
0
}
520
521
0
void common_sampler_copy(const common_sampler * src, common_sampler * dst) {
522
0
    if (!src || !dst || src == dst) {
523
0
        return;
524
0
    }
525
526
0
    GGML_ASSERT((src->grmr == nullptr) == (dst->grmr == nullptr));
527
0
    GGML_ASSERT((src->rbudget == nullptr) == (dst->rbudget == nullptr));
528
529
0
    llama_sampler_copy(src->grmr,    dst->grmr);
530
0
    llama_sampler_copy(src->rbudget, dst->rbudget);
531
0
    llama_sampler_copy(src->chain,   dst->chain);
532
533
0
    dst->params     = src->params;
534
0
    dst->prev       = src->prev;
535
0
    dst->cur        = src->cur;
536
0
    dst->cur_p      = src->cur_p;
537
0
    dst->cur_p.data = src->cur_p.data ? dst->cur.data() : nullptr; // re-point to dst's buffer
538
0
    dst->t_total_us = src->t_total_us;
539
0
}
540
541
0
void common_perf_print(const struct llama_context * ctx, const struct common_sampler * gsmpl) {
542
    // TODO: measure grammar performance
543
544
0
    const double t_sampling_ms = gsmpl ? 1e-3*gsmpl->t_total_us : 0;
545
546
0
    llama_perf_sampler_data data_smpl;
547
0
    llama_perf_context_data data_ctx;
548
549
0
    memset(&data_smpl, 0, sizeof(data_smpl));
550
0
    memset(&data_ctx,  0, sizeof(data_ctx));
551
552
0
    if (gsmpl) {
553
0
        auto & data = data_smpl;
554
555
0
        data = llama_perf_sampler(gsmpl->chain);
556
557
        // note: the sampling time includes the samplers time + extra time spent in common/sampling
558
0
        LOG_INF("%s:    sampling time = %10.2f ms\n", __func__, t_sampling_ms);
559
0
        LOG_INF("%s:    samplers time = %10.2f ms / %5d tokens\n", __func__, data.t_sample_ms, data.n_sample);
560
0
    }
561
562
0
    if (ctx) {
563
0
        auto & data = data_ctx;
564
565
0
        data = llama_perf_context(ctx);
566
567
0
        const double t_end_ms = 1e-3 * ggml_time_us();
568
569
0
        const double t_total_ms = t_end_ms - data.t_start_ms;
570
0
        const double t_unacc_ms = t_total_ms - (t_sampling_ms + data.t_p_eval_ms + data.t_eval_ms);
571
0
        const double t_unacc_pc = 100.0 * t_unacc_ms /  t_total_ms;
572
573
0
        LOG_INF("%s:        load time = %10.2f ms\n", __func__, data.t_load_ms);
574
0
        LOG_INF("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
575
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);
576
0
        LOG_INF("%s:        eval time = %10.2f ms / %5d runs   (%8.2f ms per token, %8.2f tokens per second)\n",
577
0
                __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
578
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));
579
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);
580
0
        LOG_INF("%s:    graphs reused = %10d\n", __func__, data.n_reused);
581
582
0
        common_memory_breakdown_print(ctx);
583
0
    }
584
0
}
585
586
0
struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl) {
587
0
    if (!gsmpl) {
588
0
        return nullptr;
589
0
    }
590
591
0
    return gsmpl->chain;
592
0
}
593
594
0
llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) {
595
0
    llama_synchronize(ctx);
596
597
    // start measuring sampling time after the llama_context synchronization in order to not measure any ongoing async operations
598
0
    const auto tm = gsmpl->tm();
599
600
0
    llama_token id = LLAMA_TOKEN_NULL;
601
602
0
    auto & grmr  = gsmpl->grmr;
603
0
    auto & rbudget = gsmpl->rbudget;
604
0
    auto & chain = gsmpl->chain;
605
0
    auto & cur_p = gsmpl->cur_p; // initialized by set_logits
606
607
0
    gsmpl->set_logits(ctx, idx);
608
609
    // Check if a backend sampler has already sampled a token in which case we
610
    // return that token id directly.
611
0
    {
612
0
        id = llama_get_sampled_token_ith(ctx, idx);
613
614
0
        if (id != LLAMA_TOKEN_NULL) {
615
0
            LOG_DBG("%s: Backend sampler selected token: '%d'. Will not run any CPU samplers\n", __func__, id);
616
617
0
            GGML_ASSERT(!gsmpl->grmr    && "using grammar in combination with backend sampling is not supported");
618
0
            GGML_ASSERT(!gsmpl->rbudget && "using reasoning budget in combination with backend sampling is not supported");
619
620
0
            for (size_t i = 0; i < cur_p.size; ++i) {
621
0
                if (cur_p.data[i].id == id) {
622
0
                    cur_p.selected = i;
623
0
                    break;
624
0
                }
625
0
            }
626
627
0
            return id;
628
0
        }
629
0
    }
630
631
    // apply reasoning budget first
632
0
    llama_sampler_apply(rbudget, &cur_p);
633
634
0
    if (grammar_first && grammar_should_apply(gsmpl)) {
635
0
        llama_sampler_apply(grmr, &cur_p);
636
0
    }
637
638
0
    llama_sampler_apply(chain, &cur_p);
639
640
0
    id = cur_p.data[cur_p.selected].id;
641
642
0
    if (grammar_first || !grammar_should_apply(gsmpl)) {
643
0
        return id;
644
0
    }
645
646
    // check if it the sampled token fits the grammar (grammar-based rejection sampling)
647
0
    {
648
0
        llama_token_data       single_token_data       = { id, 1.0f, 0.0f };
649
0
        llama_token_data_array single_token_data_array = { &single_token_data, 1, -1, false };
650
651
0
        llama_sampler_apply(grmr, &single_token_data_array);
652
653
0
        const bool is_valid = single_token_data_array.data[0].logit != -INFINITY;
654
0
        if (is_valid) {
655
0
            return id;
656
0
        }
657
0
    }
658
659
    // resampling:
660
    // if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain
661
0
    gsmpl->set_logits(ctx, idx);
662
663
0
    llama_sampler_apply(rbudget,  &cur_p);
664
665
0
    if (grammar_should_apply(gsmpl)) {
666
0
        llama_sampler_apply(grmr,  &cur_p);
667
0
    }
668
669
0
    llama_sampler_apply(chain, &cur_p);
670
671
0
    GGML_ASSERT(cur_p.selected != -1 && "no selected token during sampling - check your sampling configuration");
672
673
0
    id = cur_p.data[cur_p.selected].id;
674
675
0
    return id;
676
0
}
677
678
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) {
679
0
    GGML_ASSERT(idxs.size() == draft.size() + 1 && "idxs.size() must be draft.size() + 1");
680
681
0
    std::vector<llama_token> result;
682
0
    result.reserve(idxs.size());
683
684
0
    size_t i = 0;
685
0
    for (; i < draft.size(); i++) {
686
0
        const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
687
688
0
        common_sampler_accept(gsmpl, id, true);
689
690
0
        result.push_back(id);
691
692
0
        if (draft[i] != id) {
693
0
            break;
694
0
        }
695
0
    }
696
697
0
    if (i == draft.size()) {
698
0
        const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
699
700
0
        common_sampler_accept(gsmpl, id, true);
701
702
0
        result.push_back(id);
703
0
    }
704
705
0
    return result;
706
0
}
707
708
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) {
709
0
    std::vector<int> idxs(draft.size() + 1);
710
0
    for (size_t i = 0; i < idxs.size(); ++i) {
711
0
        idxs[i] = i;
712
0
    }
713
714
0
    return common_sampler_sample_and_accept_n(gsmpl, ctx, idxs, draft, grammar_first);
715
0
}
716
717
0
uint32_t common_sampler_get_seed(const struct common_sampler * gsmpl) {
718
0
    return llama_sampler_get_seed(gsmpl->chain);
719
0
}
720
721
0
bool common_sampler_reasoning_budget_force(struct common_sampler * gsmpl) {
722
0
    if (!gsmpl) {
723
0
        return false;
724
0
    }
725
726
0
    return common_reasoning_budget_force(gsmpl->rbudget);
727
0
}
728
729
// helpers
730
731
0
llama_token_data_array * common_sampler_get_candidates(struct common_sampler * gsmpl, bool do_sort) {
732
0
    const auto tm = gsmpl->tm();
733
734
0
    auto * res = &gsmpl->cur_p;
735
736
0
    if (do_sort && !res->sorted) {
737
        // remember the selected token before sorting
738
0
        const llama_token id = res->data[res->selected].id;
739
740
0
        std::sort(res->data, res->data + res->size, [](const llama_token_data & a, const llama_token_data & b) {
741
0
            return a.p > b.p;
742
0
        });
743
744
        // restore the selected token after sorting
745
0
        for (size_t i = 0; i < res->size; ++i) {
746
0
            if (res->data[i].id == id) {
747
0
                res->selected = i;
748
0
                break;
749
0
            }
750
0
        }
751
752
0
        res->sorted = true;
753
0
    }
754
755
0
    return res;
756
0
}
757
758
0
llama_token common_sampler_last(const struct common_sampler * gsmpl) {
759
0
    return gsmpl->prev.rat(0);
760
0
}
761
762
0
std::string common_sampler_print(const struct common_sampler * gsmpl) {
763
0
    std::string result = "logits ";
764
765
0
    for (int i = 0; i < llama_sampler_chain_n(gsmpl->chain); i++) {
766
0
        const auto * smpl = llama_sampler_chain_get(gsmpl->chain, i);
767
0
        result += std::string("-> ");
768
0
        result += std::string(llama_sampler_name(smpl)) + " ";
769
0
    }
770
771
0
    return result;
772
0
}
773
774
0
std::string common_sampler_prev_str(common_sampler * gsmpl, llama_context * ctx_main, int n) {
775
0
    n = std::min(n, (int) gsmpl->prev.size());
776
777
0
    if (n <= 0) {
778
0
        return "";
779
0
    }
780
781
0
    std::string result;
782
0
    result.reserve(8*n); // 8 is the average length of a token [citation needed], TODO: compute this from the vocab
783
784
0
    for (int i = n - 1; i >= 0; i--) {
785
0
        const llama_token id = gsmpl->prev.rat(i);
786
787
0
        GGML_ASSERT(id != LLAMA_TOKEN_NULL && "null token in the sampling history - should not happen");
788
789
0
        result += common_token_to_piece(ctx_main, id);
790
0
    }
791
792
0
    return result;
793
0
}
794
795
0
char common_sampler_type_to_chr(enum common_sampler_type cnstr) {
796
0
    switch (cnstr) {
797
0
        case COMMON_SAMPLER_TYPE_DRY:         return 'd';
798
0
        case COMMON_SAMPLER_TYPE_TOP_K:       return 'k';
799
0
        case COMMON_SAMPLER_TYPE_TYPICAL_P:   return 'y';
800
0
        case COMMON_SAMPLER_TYPE_TOP_P:       return 'p';
801
0
        case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: return 's';
802
0
        case COMMON_SAMPLER_TYPE_MIN_P:       return 'm';
803
0
        case COMMON_SAMPLER_TYPE_TEMPERATURE: return 't';
804
0
        case COMMON_SAMPLER_TYPE_XTC:         return 'x';
805
0
        case COMMON_SAMPLER_TYPE_INFILL:      return 'i';
806
0
        case COMMON_SAMPLER_TYPE_PENALTIES:   return 'e';
807
0
        case COMMON_SAMPLER_TYPE_ADAPTIVE_P:  return 'a';
808
0
        default : return '?';
809
0
    }
810
0
}
811
812
0
std::string common_sampler_type_to_str(enum common_sampler_type cnstr) {
813
0
    switch (cnstr) {
814
0
        case COMMON_SAMPLER_TYPE_DRY:         return "dry";
815
0
        case COMMON_SAMPLER_TYPE_TOP_K:       return "top_k";
816
0
        case COMMON_SAMPLER_TYPE_TYPICAL_P:   return "typ_p";
817
0
        case COMMON_SAMPLER_TYPE_TOP_P:       return "top_p";
818
0
        case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: return "top_n_sigma";
819
0
        case COMMON_SAMPLER_TYPE_MIN_P:       return "min_p";
820
0
        case COMMON_SAMPLER_TYPE_TEMPERATURE: return "temperature";
821
0
        case COMMON_SAMPLER_TYPE_XTC:         return "xtc";
822
0
        case COMMON_SAMPLER_TYPE_INFILL:      return "infill";
823
0
        case COMMON_SAMPLER_TYPE_PENALTIES:   return "penalties";
824
0
        case COMMON_SAMPLER_TYPE_ADAPTIVE_P:  return "adaptive_p";
825
0
        default : return "";
826
0
    }
827
0
}
828
829
0
std::vector<common_sampler_type> common_sampler_types_from_names(const std::vector<std::string> & names) {
830
    // sampler names can be written multiple ways; generate aliases from canonical names
831
0
    static const auto sampler_name_map = []{
832
        // canonical sampler name mapping
833
0
        std::unordered_map<std::string, common_sampler_type> canonical_name_map {
834
0
            { "dry",         COMMON_SAMPLER_TYPE_DRY         },
835
0
            { "top_k",       COMMON_SAMPLER_TYPE_TOP_K       },
836
0
            { "top_p",       COMMON_SAMPLER_TYPE_TOP_P       },
837
0
            { "top_n_sigma", COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
838
0
            { "typ_p",       COMMON_SAMPLER_TYPE_TYPICAL_P   },
839
0
            { "min_p",       COMMON_SAMPLER_TYPE_MIN_P       },
840
0
            { "temperature", COMMON_SAMPLER_TYPE_TEMPERATURE },
841
0
            { "xtc",         COMMON_SAMPLER_TYPE_XTC         },
842
0
            { "infill",      COMMON_SAMPLER_TYPE_INFILL      },
843
0
            { "penalties",   COMMON_SAMPLER_TYPE_PENALTIES   },
844
0
            { "adaptive_p",  COMMON_SAMPLER_TYPE_ADAPTIVE_P  }
845
0
        };
846
0
        std::unordered_map<std::string, common_sampler_type> alias_name_map;
847
0
        for (const auto & entry : canonical_name_map) {
848
0
            const std::string & canonical = entry.first;
849
0
            if (canonical.find('_') == std::string::npos) {
850
0
                continue;
851
0
            }
852
            // kebab-case: "top-k", "min-p", etc.
853
0
            {
854
0
                std::string kebab_case = canonical;
855
0
                std::replace(kebab_case.begin(), kebab_case.end(), '_', '-');
856
0
                alias_name_map.insert({kebab_case, entry.second});
857
0
            }
858
            // no dash: "topk", "minp", etc.
859
0
            {
860
0
                std::string no_dash = canonical;
861
0
                no_dash.erase(std::remove(no_dash.begin(), no_dash.end(), '_'), no_dash.end());
862
0
                alias_name_map.insert({no_dash, entry.second});
863
0
            }
864
0
        }
865
        // misc. aliases
866
0
        alias_name_map.insert({"nucleus", COMMON_SAMPLER_TYPE_TOP_P});
867
0
        alias_name_map.insert({"temp",    COMMON_SAMPLER_TYPE_TEMPERATURE});
868
0
        alias_name_map.insert({"typ",     COMMON_SAMPLER_TYPE_TYPICAL_P});
869
        // include aliases + canonical names in the complete mapping
870
0
        alias_name_map.merge(canonical_name_map);
871
0
        return alias_name_map;
872
0
    }();
873
874
0
    std::vector<common_sampler_type> samplers;
875
0
    samplers.reserve(names.size());
876
877
0
    for (const auto & name : names) {
878
0
        std::string name_lower = name;
879
0
        std::transform(name_lower.begin(), name_lower.end(), name_lower.begin(), ::tolower);
880
0
        auto sampler = sampler_name_map.find(name_lower);
881
0
        if (sampler != sampler_name_map.end()) {
882
0
            samplers.push_back(sampler->second);
883
0
            continue;
884
0
        }
885
0
        LOG_WRN("%s: unable to match sampler by name '%s'\n", __func__, name_lower.c_str());
886
0
    }
887
888
0
    return samplers;
889
0
}
890
891
0
std::vector<common_sampler_type> common_sampler_types_from_chars(const std::string & chars) {
892
0
    std::unordered_map<char, common_sampler_type> sampler_name_map = {
893
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_DRY),         COMMON_SAMPLER_TYPE_DRY },
894
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_K),       COMMON_SAMPLER_TYPE_TOP_K },
895
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TYPICAL_P),   COMMON_SAMPLER_TYPE_TYPICAL_P },
896
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_P),       COMMON_SAMPLER_TYPE_TOP_P },
897
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_N_SIGMA), COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
898
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_MIN_P),       COMMON_SAMPLER_TYPE_MIN_P },
899
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TEMPERATURE), COMMON_SAMPLER_TYPE_TEMPERATURE },
900
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_XTC),         COMMON_SAMPLER_TYPE_XTC },
901
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_INFILL),      COMMON_SAMPLER_TYPE_INFILL },
902
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_PENALTIES),   COMMON_SAMPLER_TYPE_PENALTIES },
903
0
        { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_ADAPTIVE_P),  COMMON_SAMPLER_TYPE_ADAPTIVE_P },
904
0
    };
905
906
0
    std::vector<common_sampler_type> samplers;
907
0
    samplers.reserve(chars.size());
908
909
0
    for (const auto & c : chars) {
910
0
        const auto sampler = sampler_name_map.find(c);
911
0
        if (sampler != sampler_name_map.end()) {
912
0
            samplers.push_back(sampler->second);
913
0
        } else {
914
0
            LOG_WRN("%s: unable to match sampler by char '%c'\n", __func__, c);
915
0
        }
916
0
    }
917
918
0
    return samplers;
919
0
}