Coverage Report

Created: 2026-08-22 07:18

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/common/common.h
Line
Count
Source
1
// Various helper functions and utilities
2
3
#pragma once
4
5
#include "llama-cpp.h"
6
7
#include "ggml-opt.h"
8
#include "ggml.h"
9
#include "llama.h"
10
11
#include <set>
12
#include <sstream>
13
#include <string>
14
#include <string_view>
15
#include <vector>
16
#include <map>
17
#include <algorithm>
18
#include <fstream>
19
20
#if defined(_WIN32) && !defined(_WIN32_WINNT)
21
#define _WIN32_WINNT 0x0A00
22
#endif
23
24
#ifdef _WIN32
25
#define DIRECTORY_SEPARATOR '\\'
26
#else
27
0
#define DIRECTORY_SEPARATOR '/'
28
#endif // _WIN32
29
30
#define COM_DBG(fmt, ...) LOG_DBG("cmn  %12.*s: " fmt, 12, __func__, __VA_ARGS__)
31
0
#define COM_TRC(fmt, ...) LOG_TRC("cmn  %12.*s: " fmt, 12, __func__, __VA_ARGS__)
32
0
#define COM_INF(fmt, ...) LOG_INF("cmn  %12.*s: " fmt, 12, __func__, __VA_ARGS__)
33
0
#define COM_WRN(fmt, ...) LOG_WRN("cmn  %12.*s: " fmt, 12, __func__, __VA_ARGS__)
34
0
#define COM_ERR(fmt, ...) LOG_ERR("cmn  %12.*s: " fmt, 12, __func__, __VA_ARGS__)
35
#define COM_CNT(fmt, ...) LOG_CNT(""              fmt,               __VA_ARGS__)
36
37
#define die(msg)          do { fputs("error: " msg "\n", stderr);                exit(1); } while (0)
38
#define die_fmt(fmt, ...) do { fprintf(stderr, "error: " fmt "\n", __VA_ARGS__); exit(1); } while (0)
39
40
struct common_time_meas {
41
    common_time_meas(int64_t & t_acc, bool disable = false);
42
    ~common_time_meas();
43
44
    const int64_t t_start_us;
45
46
    int64_t & t_acc;
47
};
48
49
struct common_adapter_lora_info {
50
    std::string path;
51
    float scale;
52
53
    std::string task_name;
54
    std::string prompt_prefix;
55
56
    struct llama_adapter_lora * ptr;
57
};
58
59
using llama_tokens = std::vector<llama_token>;
60
61
struct common_control_vector_load_info;
62
63
//
64
// CPU utils
65
//
66
67
struct common_cpu_params {
68
    int      n_threads                   = -1;
69
    bool     cpumask[GGML_MAX_N_THREADS] = {false}; // CPU affinity mask.
70
    bool     mask_valid                  = false;   // Default: any CPU
71
    enum ggml_sched_priority  priority   = GGML_SCHED_PRIO_NORMAL;  // Scheduling prio : (0 - normal, 1 - medium, 2 - high, 3 - realtime)
72
    bool     strict_cpu                  = false;   // Use strict CPU placement
73
    uint32_t poll                        = 50;      // Polling (busywait) level (0 - no polling, 100 - mostly polling)
74
};
75
76
int32_t common_cpu_get_num_physical_cores();
77
int32_t common_cpu_get_num_math();
78
79
//
80
// Common params
81
//
82
83
enum llama_example {
84
    LLAMA_EXAMPLE_BATCHED,
85
    LLAMA_EXAMPLE_DEBUG,
86
    LLAMA_EXAMPLE_COMMON,
87
    LLAMA_EXAMPLE_SPECULATIVE,
88
    LLAMA_EXAMPLE_COMPLETION,
89
    LLAMA_EXAMPLE_CLI,
90
    LLAMA_EXAMPLE_EMBEDDING,
91
    LLAMA_EXAMPLE_PERPLEXITY,
92
    LLAMA_EXAMPLE_RETRIEVAL,
93
    LLAMA_EXAMPLE_PASSKEY,
94
    LLAMA_EXAMPLE_IMATRIX,
95
    LLAMA_EXAMPLE_BENCH,
96
    LLAMA_EXAMPLE_SERVER,
97
    LLAMA_EXAMPLE_CVECTOR_GENERATOR,
98
    LLAMA_EXAMPLE_EXPORT_LORA,
99
    LLAMA_EXAMPLE_MTMD,
100
    LLAMA_EXAMPLE_LOOKUP,
101
    LLAMA_EXAMPLE_PARALLEL,
102
    LLAMA_EXAMPLE_TTS,
103
    LLAMA_EXAMPLE_DIFFUSION,
104
    LLAMA_EXAMPLE_FINETUNE,
105
    LLAMA_EXAMPLE_FIT_PARAMS,
106
    LLAMA_EXAMPLE_RESULTS,
107
    LLAMA_EXAMPLE_EXPORT_GRAPH_OPS,
108
    LLAMA_EXAMPLE_DOWNLOAD,
109
    LLAMA_EXAMPLE_TOKENIZE,
110
111
    LLAMA_EXAMPLE_COUNT,
112
};
113
114
enum common_sampler_type {
115
    COMMON_SAMPLER_TYPE_NONE        = 0,
116
    COMMON_SAMPLER_TYPE_DRY         = 1,
117
    COMMON_SAMPLER_TYPE_TOP_K       = 2,
118
    COMMON_SAMPLER_TYPE_TOP_P       = 3,
119
    COMMON_SAMPLER_TYPE_MIN_P       = 4,
120
  //COMMON_SAMPLER_TYPE_TFS_Z       = 5,
121
    COMMON_SAMPLER_TYPE_TYPICAL_P   = 6,
122
    COMMON_SAMPLER_TYPE_TEMPERATURE = 7,
123
    COMMON_SAMPLER_TYPE_XTC         = 8,
124
    COMMON_SAMPLER_TYPE_INFILL      = 9,
125
    COMMON_SAMPLER_TYPE_PENALTIES   = 10,
126
    COMMON_SAMPLER_TYPE_TOP_N_SIGMA = 11,
127
    COMMON_SAMPLER_TYPE_ADAPTIVE_P  = 12,
128
};
129
130
// dimensionality reduction methods, used by cvector-generator
131
enum dimre_method {
132
    DIMRE_METHOD_PCA,
133
    DIMRE_METHOD_MEAN,
134
};
135
136
enum common_conversation_mode {
137
    COMMON_CONVERSATION_MODE_DISABLED = 0,
138
    COMMON_CONVERSATION_MODE_ENABLED  = 1,
139
    COMMON_CONVERSATION_MODE_AUTO     = 2,
140
};
141
142
enum common_grammar_trigger_type {
143
    COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN,
144
    COMMON_GRAMMAR_TRIGGER_TYPE_WORD,
145
    COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN,
146
    COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL,
147
};
148
149
struct common_grammar_trigger {
150
    common_grammar_trigger_type type;
151
    std::string value;
152
    llama_token token = LLAMA_TOKEN_NULL;
153
};
154
155
enum common_params_sampling_config : uint64_t {
156
    COMMON_PARAMS_SAMPLING_CONFIG_SAMPLERS        = 1 << 0,
157
    COMMON_PARAMS_SAMPLING_CONFIG_TOP_K           = 1 << 1,
158
    COMMON_PARAMS_SAMPLING_CONFIG_TOP_P           = 1 << 2,
159
    COMMON_PARAMS_SAMPLING_CONFIG_MIN_P           = 1 << 3,
160
    COMMON_PARAMS_SAMPLING_CONFIG_XTC_PROBABILITY = 1 << 4,
161
    COMMON_PARAMS_SAMPLING_CONFIG_XTC_THRESHOLD   = 1 << 5,
162
    COMMON_PARAMS_SAMPLING_CONFIG_TEMP            = 1 << 6,
163
    COMMON_PARAMS_SAMPLING_CONFIG_PENALTY_LAST_N  = 1 << 7,
164
    COMMON_PARAMS_SAMPLING_CONFIG_PENALTY_REPEAT  = 1 << 8,
165
    COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT        = 1 << 9,
166
    COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT_TAU    = 1 << 10,
167
    COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT_ETA    = 1 << 11,
168
};
169
170
enum common_speculative_type {
171
    COMMON_SPECULATIVE_TYPE_NONE,          // no speculative decoding
172
    COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE,  // standalone draft model speculative decoding
173
    COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3,  // Eagle3 speculative decoding
174
    COMMON_SPECULATIVE_TYPE_DRAFT_MTP,     // Multi-token prediction
175
    COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH,  // DFlash speculative decoding
176
    COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK,  // DSpark speculative decoding (DFlash + Markov head)
177
    COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE,  // simple self-speculative decoding based on n-grams
178
    COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K,   // self-speculative decoding with n-gram keys only
179
    COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V, // self-speculative decoding with n-gram keys and 4 m-gram values
180
    COMMON_SPECULATIVE_TYPE_NGRAM_MOD,
181
    COMMON_SPECULATIVE_TYPE_NGRAM_CACHE,   // self-speculative decoding with 3-level n-gram cache
182
    COMMON_SPECULATIVE_TYPE_COUNT          // number of types, unknown type
183
};
184
185
// Grammar type enumeration
186
enum common_grammar_type {
187
    COMMON_GRAMMAR_TYPE_NONE,           // no grammar set
188
    COMMON_GRAMMAR_TYPE_USER,           // user-provided GBNF (--grammar / "grammar" API field)
189
    COMMON_GRAMMAR_TYPE_OUTPUT_FORMAT,  // auto-generated from JSON schema (--json-schema / "json_schema" API field)
190
    COMMON_GRAMMAR_TYPE_TOOL_CALLS,     // auto-generated by chat template parser for function calling
191
};
192
193
// Grammar variant struct with type and grammar string
194
struct common_grammar {
195
    common_grammar_type type = COMMON_GRAMMAR_TYPE_NONE;
196
    std::string grammar;
197
198
    // Default constructor - no grammar
199
6.55k
    common_grammar() = default;
200
201
    // Constructor with type and grammar string
202
0
    common_grammar(common_grammar_type t, std::string g) : type(t), grammar(std::move(g)) {
203
0
        GGML_ASSERT(type != COMMON_GRAMMAR_TYPE_NONE || !grammar.empty());
204
0
    }
205
206
    // Check if a grammar is set
207
0
    bool empty() const { return type == COMMON_GRAMMAR_TYPE_NONE || grammar.empty(); }
208
};
209
210
// Returns the raw grammar string, or empty string if no grammar is set.
211
0
inline const std::string & common_grammar_value(const common_grammar & g) {
212
0
    return g.grammar;
213
0
}
214
215
// Returns true when the generation_prompt should be prefilled into the grammar sampler.
216
// Only output-format and tool-call grammars need prefill; user-supplied grammars must not be prefilled.
217
0
inline bool common_grammar_needs_prefill(const common_grammar & g) {
218
0
    return g.type == COMMON_GRAMMAR_TYPE_OUTPUT_FORMAT
219
0
        || g.type == COMMON_GRAMMAR_TYPE_TOOL_CALLS;
220
0
}
221
222
// sampling parameters
223
struct common_params_sampling {
224
    uint32_t seed = LLAMA_DEFAULT_SEED; // the seed used to initialize llama_sampler
225
226
    int32_t n_prev             = 64;     // number of previous tokens to remember
227
    int32_t n_probs            = 0;      // if greater than 0, output the probabilities of top n_probs tokens.
228
    int32_t min_keep           = 0;      // 0 = disabled, otherwise samplers should return at least min_keep tokens
229
    int32_t top_k              = 40;     // <= 0 to use vocab size
230
    float   top_p              = 0.95f;  // 1.0 = disabled
231
    float   min_p              = 0.05f;  // 0.0 = disabled
232
    float   xtc_probability    = 0.00f;  // 0.0 = disabled
233
    float   xtc_threshold      = 0.10f;  // > 0.5 disables XTC
234
    float   typ_p              = 1.00f;  // typical_p, 1.0 = disabled
235
    float   temp               = 0.80f;  // <= 0.0 to sample greedily, 0.0 to not output probabilities
236
    float   dynatemp_range     = 0.00f;  // 0.0 = disabled
237
    float   dynatemp_exponent  = 1.00f;  // controls how entropy maps to temperature in dynamic temperature sampler
238
    int32_t penalty_last_n     = 64;     // last n tokens to penalize (0 = disable penalty)
239
    float   penalty_repeat     = 1.00f;  // 1.0 = disabled
240
    float   penalty_freq       = 0.00f;  // 0.0 = disabled
241
    float   penalty_present    = 0.00f;  // 0.0 = disabled
242
    float   dry_multiplier     = 0.0f;   // 0.0 = disabled;      DRY repetition penalty for tokens extending repetition:
243
    float   dry_base           = 1.75f;  // 0.0 = disabled;      multiplier * base ^ (length of sequence before token - allowed length)
244
    int32_t dry_allowed_length = 2;      // tokens extending repetitions beyond this receive penalty
245
    int32_t dry_penalty_last_n = 64;     // how many tokens to scan for repetitions (0 = disable penalty)
246
    float   adaptive_target    = -1.0f;  // select tokens near this probability (valid range 0.0 to 1.0; negative = disabled)
247
    float   adaptive_decay     = 0.90f;  // EMA decay for adaptation; history ≈ 1/(1-decay) tokens (0.0 - 0.99)
248
    int32_t mirostat           = 0;      // 0 = disabled, 1 = mirostat, 2 = mirostat 2.0
249
    float   top_n_sigma        = -1.00f; // -1.0 = disabled
250
    float   mirostat_tau       = 5.00f;  // target entropy
251
    float   mirostat_eta       = 0.10f;  // learning rate
252
    bool    ignore_eos         = false;
253
    bool    no_perf            = false;  // disable performance metrics
254
    bool    timing_per_token   = false;
255
256
    uint64_t user_sampling_config = 0; // bitfield to track user-specified samplers
257
258
    std::vector<std::string> dry_sequence_breakers = {"\n", ":", "\"", "*"};     // default sequence breakers for DRY
259
260
    std::vector<enum common_sampler_type> samplers = {
261
        COMMON_SAMPLER_TYPE_PENALTIES,
262
        COMMON_SAMPLER_TYPE_DRY,
263
        COMMON_SAMPLER_TYPE_TOP_N_SIGMA,
264
        COMMON_SAMPLER_TYPE_TOP_K,
265
        COMMON_SAMPLER_TYPE_TYPICAL_P,
266
        COMMON_SAMPLER_TYPE_TOP_P,
267
        COMMON_SAMPLER_TYPE_MIN_P,
268
        COMMON_SAMPLER_TYPE_XTC,
269
        COMMON_SAMPLER_TYPE_TEMPERATURE,
270
    };
271
272
    common_grammar              grammar;      // optional grammar constraint (user / output-format / tool-calls)
273
    bool                                grammar_lazy = false;
274
    std::vector<common_grammar_trigger> grammar_triggers; // optional triggers (for lazy grammars)
275
    std::set<llama_token>               preserved_tokens;
276
277
    std::vector<llama_logit_bias> logit_bias;     // logit biases to apply
278
    std::vector<llama_logit_bias> logit_bias_eog; // pre-calculated logit biases for EOG tokens
279
280
    // The assistant generation prompt already prefilled into the prompt.
281
    // Fed to the grammar sampler (to advance past pre-existing tokens) and used
282
    // to determine the reasoning budget sampler's initial state.
283
    // Only applied when the grammar is of output-format or tool-calls type.
284
    std::string generation_prompt;
285
286
    // reasoning budget sampler parameters
287
    // these are populated by the server/CLI based on chat template params
288
    int32_t                   reasoning_budget_tokens   = -1;  // -1 = disabled, >= 0 = token budget
289
    std::vector<llama_token>  reasoning_budget_start;          // start tag token sequence
290
    std::vector<llama_tokens> reasoning_budget_end;            // end tag token sequences; the first tag is used as the forcing sequence
291
    std::vector<llama_token>  reasoning_budget_forced;         // forced sequence (message + first end tag)
292
    std::string               reasoning_budget_message;        // message injected before end tag when budget exhausted
293
    bool                      reasoning_control = false;       // create the budget sampler on demand so reasoning can be ended at runtime
294
295
    bool backend_sampling = false;
296
297
    // print the parameters into a string
298
    std::string print() const;
299
};
300
301
struct common_params_model {
302
    std::string path        = ""; // model local path
303
    std::string url         = ""; // model url to download
304
    std::string hf_repo     = ""; // HF repo
305
    std::string hf_file     = ""; // HF file
306
    std::string docker_repo = ""; // Docker repo
307
308
0
    std::string get_name() const {
309
0
        if (!hf_repo.empty()) {
310
0
            return hf_repo;
311
0
        }
312
0
        if (!docker_repo.empty()) {
313
0
            return docker_repo;
314
0
        }
315
0
        return path;
316
0
    }
317
318
0
    bool empty() const {
319
0
        return get_name().empty();
320
0
    }
321
};
322
323
// draft-model-based speculative decoding parameters
324
struct common_params_speculative_draft {
325
    int32_t n_max = 3; // maximum number of tokens to draft during speculative decoding
326
    int32_t n_min = 0; // minimum number of draft tokens to use for speculative decoding
327
328
    float p_split = 0.1f; // speculative decoding split probability
329
    float p_min   = 0.0f; // minimum speculative decoding probability (greedy)
330
331
    bool backend_sampling = true; // offload draft sampling to the backend (default: on)
332
333
    common_params_model mparams;
334
335
    llama_context * ctx_tgt = nullptr;
336
    llama_context * ctx_dft = nullptr;
337
338
    int32_t n_gpu_layers = -1; // number of layers to store in VRAM for the draft model (-1 - use default)
339
340
    ggml_type cache_type_k = GGML_TYPE_F16; // KV cache data type for the K
341
    ggml_type cache_type_v = GGML_TYPE_F16; // KV cache data type for the V
342
343
    common_cpu_params cpuparams;
344
    common_cpu_params cpuparams_batch;
345
346
    std::vector<ggml_backend_dev_t> devices; // devices to use for offloading
347
348
    std::vector<llama_model_tensor_buft_override> tensor_buft_overrides;
349
};
350
351
struct common_params_speculative_ngram_mod {
352
    int32_t n_match = 24;
353
354
    int32_t n_max = 64;
355
    int32_t n_min = 48;
356
};
357
358
struct common_params_speculative_ngram_map {
359
    uint16_t size_n   = 12; // ngram size for lookup
360
    uint16_t size_m   = 48; // mgram size for speculative tokens
361
    uint16_t min_hits = 1;  // minimum hits at ngram/mgram lookup for mgram to be proposed
362
};
363
364
struct common_params_speculative_ngram_cache {
365
    std::string lookup_cache_static;  // path of static ngram cache file for lookup decoding
366
    std::string lookup_cache_dynamic; // path of dynamic ngram cache file for lookup decoding
367
};
368
369
struct common_params_speculative {
370
    std::vector<enum common_speculative_type> types = { COMMON_SPECULATIVE_TYPE_NONE };
371
372
    // used by Simple, MTP, Eagle3, etc. - all methods that require some kind of draft model
373
    common_params_speculative_draft draft;
374
375
    common_params_speculative_ngram_mod ngram_mod;
376
    common_params_speculative_ngram_map ngram_simple;
377
    common_params_speculative_ngram_map ngram_map_k;
378
    common_params_speculative_ngram_map ngram_map_k4v;
379
380
    common_params_speculative_ngram_cache ngram_cache;
381
382
0
    bool has_dft() const {
383
0
        return !draft.mparams.empty();
384
0
    }
385
386
0
    uint32_t need_n_rs_seq() const {
387
0
        bool needs_rs_seq = std::any_of(types.begin(), types.end(), [&](auto t) {
388
0
            return t == COMMON_SPECULATIVE_TYPE_DRAFT_MTP || t == COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3 || t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK;
389
0
        });
390
391
0
        return needs_rs_seq ? draft.n_max : 0u;
392
0
    }
393
};
394
395
struct common_params_diffusion {
396
    int32_t steps         = 128;
397
    bool    visual_mode   = false;
398
399
    float   eps           = 0;        // epsilon for timesteps
400
    int32_t block_length  = 0;        // block length for generation
401
402
    int32_t algorithm     = 4;        // default algorithm: low-confidence
403
    float   alg_temp      = 0.0f;     // algorithm temperature
404
405
    float   cfg_scale     = 0;        // classifier-free guidance scale
406
    bool    add_gumbel_noise = false; // add gumbel noise to the logits if temp > 0.0
407
};
408
409
// reasoning API response format (not to be confused as chat template's reasoning format)
410
// only used by server
411
enum common_reasoning_format {
412
    COMMON_REASONING_FORMAT_NONE,
413
    COMMON_REASONING_FORMAT_AUTO,            // Same as deepseek, using `message.reasoning_content`
414
    COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY, // Extract thinking tag contents and return as `message.reasoning_content`, or leave inline in <think> tags in stream mode
415
    COMMON_REASONING_FORMAT_DEEPSEEK,        // Extract thinking tag contents and return as `message.reasoning_content`, including in streaming deltas.
416
    // do not extend this enum unless you absolutely have to
417
    // in most cases, use COMMON_REASONING_FORMAT_AUTO
418
    // see: https://github.com/ggml-org/llama.cpp/pull/15408
419
};
420
421
422
struct lr_opt {
423
    float    lr0          = 1e-5; // learning rate at first epoch
424
    float    lr_min       = -1;
425
    float    decay_epochs = -1;   // if >0, the learning rate starts at lr0 and decays to lr_min after this many epochs
426
    float    scale_epoch  = 0;
427
    float    wd           = 0;
428
    unsigned epochs       = 2;
429
430
    unsigned epoch; // set by optimizer outer (epochs) loop
431
    // learning rate decay - constant LR per epoch only for now
432
    float get_lr(float e) const;
433
0
    float get_lr() const { return get_lr(epoch); }
434
    // must call after arg parse, before get_lr
435
    void init();
436
};
437
438
struct ggml_opt_optimizer_params common_opt_lr_pars(void * userdata);
439
440
struct common_params {
441
    int32_t n_predict             =    -1; // max. number of new tokens to predict, -1 == no limit
442
    int32_t n_ctx                 =     0; // context size, 0 == context the model was trained with
443
    int32_t n_batch               =  2048; // logical batch size for prompt processing (must be >=32 to use BLAS)
444
    int32_t n_ubatch              =   512; // physical batch size for prompt processing (must be >=32 to use BLAS)
445
    int32_t n_keep                =     0; // number of tokens to keep from initial prompt
446
    int32_t n_chunks              =    -1; // max number of chunks to process (-1 = unlimited)
447
    int32_t n_parallel            =     1; // number of parallel sequences to decode
448
    int32_t n_sequences           =     1; // number of sequences to decode
449
    int32_t n_outputs_max         =     0; // max outputs in a batch (0 = n_batch)
450
    int32_t n_outputs_max_per_seq =     1; // max outputs per sequence
451
    int32_t grp_attn_n            =     1; // group-attention factor
452
    int32_t grp_attn_w            =   512; // group-attention width
453
    int32_t n_print               =    -1; // print token count every n tokens (-1 = disabled)
454
    float   rope_freq_base        =  0.0f; // RoPE base frequency
455
    float   rope_freq_scale       =  0.0f; // RoPE frequency scaling factor
456
    float   yarn_ext_factor       = -1.0f; // YaRN extrapolation mix factor
457
    float   yarn_attn_factor      = -1.0f; // YaRN magnitude scaling factor
458
    float   yarn_beta_fast        = -1.0f; // YaRN low correction dim
459
    float   yarn_beta_slow        = -1.0f; // YaRN high correction dim
460
    int32_t yarn_orig_ctx         =     0; // YaRN original context length
461
462
    // offload params
463
    std::vector<ggml_backend_dev_t> devices; // devices to use for offloading
464
465
    int32_t n_gpu_layers       = -1;    // number of layers to store in VRAM, -1 is auto, <= -2 is all
466
    int32_t main_gpu           = 0;     // the GPU that is used for scratch and small tensors
467
    float   tensor_split[128]  = {0};   // how split tensors should be distributed across GPUs
468
    bool    fit_params         = true;  // whether to fit unset model/context parameters to free device memory
469
    bool    fit_params_print   = false; // print the estimated required memory to run the model
470
    int32_t fit_params_min_ctx = 4096;  // minimum context size to set when trying to reduce memory use
471
472
    // margin per device in bytes for fitting parameters to free memory:
473
    std::vector<size_t> fit_params_target = std::vector<size_t>(llama_max_devices(), 1024 * 1024*1024);
474
475
    enum llama_split_mode split_mode = LLAMA_SPLIT_MODE_LAYER; // how to split the model across GPUs
476
    enum llama_load_mode  load_mode  = LLAMA_LOAD_MODE_AUTO; // how to load the model
477
478
    common_cpu_params cpuparams;
479
    common_cpu_params cpuparams_batch;
480
481
    ggml_backend_sched_eval_callback cb_eval = nullptr;
482
    void * cb_eval_user_data                 = nullptr;
483
484
    ggml_numa_strategy numa = GGML_NUMA_STRATEGY_DISABLED;
485
486
    enum llama_rope_scaling_type rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
487
    enum llama_pooling_type      pooling_type      = LLAMA_POOLING_TYPE_UNSPECIFIED; // pooling type for embeddings
488
    enum llama_attention_type    attention_type    = LLAMA_ATTENTION_TYPE_UNSPECIFIED; // attention type for embeddings
489
    enum llama_flash_attn_type   flash_attn_type   = LLAMA_FLASH_ATTN_TYPE_AUTO; // whether to use Flash Attention
490
491
    struct common_params_sampling    sampling;
492
    struct common_params_speculative speculative;
493
    struct common_params_diffusion   diffusion;
494
495
    struct common_params_model model;
496
497
    std::set<std::string> model_alias;     // model aliases                                                 // NOLINT
498
    std::set<std::string> model_tags;      // model tags (informational, not used for routing)              // NOLINT
499
    std::string hf_token             = ""; // HF token (aka bearer token)                                   // NOLINT
500
    std::string prompt               = "";                                                                  // NOLINT
501
    std::string system_prompt        = "";                                                                  // NOLINT
502
    std::string prompt_file          = ""; // store the external prompt file name                           // NOLINT
503
    std::string path_prompt_cache    = ""; // path to file for saving/loading prompt eval state             // NOLINT
504
    std::string input_prefix         = ""; // string to prefix user inputs with                             // NOLINT
505
    std::string input_suffix         = ""; // string to suffix user inputs with                             // NOLINT
506
    std::string logits_file          = ""; // file for saving *all* logits                                  // NOLINT
507
    std::string path_prompts_log_dir = ""; // directory with logged prompts                                 // NOLINT
508
509
    // llama-debug specific options
510
    std::string logits_output_dir = "data"; // directory for saving logits output files                     // NOLINT
511
    bool        save_logits       = false;  // whether to save logits to files                              // NOLINT
512
    std::vector<std::string> tensor_filter; // filter tensor names for debug output (regex)                 // NOLINT
513
514
    std::vector<std::string> in_files;   // all input files
515
    std::vector<std::string> antiprompt; // strings upon which more user input is prompted (a.k.a. reverse prompts)
516
    std::vector<llama_model_kv_override> kv_overrides;
517
    std::vector<llama_model_tensor_buft_override> tensor_buft_overrides;
518
519
    bool lora_init_without_apply = false; // only load lora to memory, but do not apply it to ctx (user can manually apply lora later using llama_adapter_lora_apply)
520
    std::vector<common_adapter_lora_info> lora_adapters; // lora adapter path with user defined scale
521
522
    std::vector<common_control_vector_load_info> control_vectors; // control vector with user defined scale
523
524
    int32_t verbosity                  = 3;  // LOG_LEVEL_INFO
525
    int32_t control_vector_layer_start = -1; // layer range for control vector
526
    int32_t control_vector_layer_end   = -1; // layer range for control vector
527
    bool    offline                    = false;
528
529
    int32_t ppl_stride      = 0;     // stride for perplexity calculations. If left at 0, the pre-existing approach will be used.
530
    int32_t ppl_output_type = 0;     // = 0 -> ppl output is as usual, = 1 -> ppl output is num_tokens, ppl, one per line
531
                                     //                                       (which is more convenient to use for plotting)
532
                                     //
533
    bool   hellaswag        = false; // compute HellaSwag score over random tasks from datafile supplied in prompt
534
    size_t hellaswag_tasks  = 400;   // number of tasks to use when computing the HellaSwag score
535
536
    bool   winogrande       = false; // compute Winogrande score over random tasks from datafile supplied in prompt
537
    size_t winogrande_tasks = 0;     // number of tasks to use when computing the Winogrande score. If 0, all tasks will be computed
538
539
    bool   multiple_choice  = false;  // compute TruthfulQA score over random tasks from datafile supplied in prompt
540
    size_t multiple_choice_tasks = 0; // number of tasks to use when computing the TruthfulQA score. If 0, all tasks will be computed
541
542
    bool   kl_divergence    = false; // compute KL divergence
543
544
    bool check             = false; // check rather than generate results for llama-results
545
546
    bool usage             = false; // print usage
547
    bool completion        = false; // print source-able completion script
548
    bool use_color         = false; // use color to distinguish generations and inputs
549
    bool special           = false; // enable special token output
550
    bool interactive       = false; // interactive mode
551
    bool interactive_first = false; // wait for user input immediately
552
    bool prompt_cache_all  = false; // save user input and generations to prompt cache
553
    bool prompt_cache_ro   = false; // open the prompt cache read-only and do not update it
554
555
    bool escape            = true;  // escape "\n", "\r", "\t", "\'", "\"", and "\\"
556
    bool multiline_input   = false; // reverse the usage of `\`
557
    bool simple_io         = false; // improves compatibility with subprocesses and limited consoles
558
    bool cont_batching     = true;  // insert new sequences for decoding on-the-fly
559
    bool no_perf           = false; // disable performance metrics
560
    bool show_timings      = true;  // show timing information on CLI
561
    bool ctx_shift         = false; // context shift on infinite text generation
562
    bool swa_full          = false; // use full-size SWA cache (https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)
563
    bool kv_unified        = false; // enable unified KV cache
564
565
    bool input_prefix_bos  = false; // prefix BOS to user inputs, preceding input_prefix
566
    bool verbose_prompt    = false; // print prompt tokens before generation
567
    bool display_prompt    = true;  // print prompt before generation
568
    bool no_kv_offload     = false; // disable KV offloading
569
    bool warmup            = true;  // warmup run
570
    bool check_tensors     = false; // validate tensor data
571
    bool no_op_offload     = false; // globally disable offload host tensor operations to device
572
    bool no_extra_bufts    = false; // disable extra buffer types (used for weight repacking)
573
    bool no_host           = false; // bypass host buffer allowing extra buffers to be used
574
575
    bool single_turn       = false; // single turn chat conversation
576
577
    ggml_type cache_type_k = GGML_TYPE_F16; // KV cache data type for the K
578
    ggml_type cache_type_v = GGML_TYPE_F16; // KV cache data type for the V
579
580
    common_conversation_mode conversation_mode = COMMON_CONVERSATION_MODE_AUTO;
581
582
    // multimodal models (see tools/mtmd)
583
    struct common_params_model mmproj;
584
    bool mmproj_use_gpu = true;                 // use GPU for multimodal model
585
    ggml_backend_dev_t mmproj_device = nullptr; // GPU device to use for multimodal model
586
    bool no_mmproj = false;                     // explicitly disable multimodal model
587
    std::vector<std::string> image;             // path to image file(s) ; TODO: change the name to "media"
588
    int image_min_tokens = -1;
589
    int image_max_tokens = -1;
590
    int mtmd_batch_max_tokens = 1024;
591
592
    // finetune
593
    struct lr_opt lr;
594
    enum ggml_opt_optimizer_type optimizer = GGML_OPT_OPTIMIZER_TYPE_ADAMW;
595
    float val_split = 0.05f; // fraction of the data used for the validation set
596
597
    // embedding
598
    bool embedding         = false; // get only sentence embedding
599
    int32_t embd_normalize = 2;     // normalisation for embeddings (-1=none, 0=max absolute int16, 1=taxicab, 2=euclidean, >2=p-norm)
600
    std::string embd_out   = "";    // empty = default, "array" = [[],[]...], "json" = openai style, "json+" = same "json" + cosine similarity matrix
601
    std::string embd_sep   = "\n";  // separator of embeddings
602
    std::string cls_sep    = "\t";  // separator of classification sequences
603
604
    // server params
605
    int32_t port                = 8080;          // server listens on this network port
606
    bool    reuse_port          = false;         // allow multiple sockets to bind to the same port
607
    int32_t timeout_read        = 3600;          // http read timeout in seconds
608
    int32_t timeout_write       = timeout_read;  // http write timeout in seconds
609
    int32_t sse_ping_interval   = 30;            // SSE ping interval in seconds
610
    int32_t n_threads_http      = -1;    // number of threads to process HTTP requests (TODO: support threadpool)
611
    int32_t n_cache_reuse       = 0;     // min chunk size to reuse from the cache via KV shifting
612
    bool    cache_prompt        = true;  // whether to enable prompt caching
613
    bool    cache_idle_slots    = true;  // save and clear idle slots upon starting a new task
614
    int32_t n_ctx_checkpoints   = 32;    // max number of context checkpoints per slot
615
    int32_t checkpoint_min_step = 8192;  // minimum spacing between context checkpoints
616
    int32_t cache_ram_mib       = 8192;  // -1 = no limit, 0 - disable, 1 = 1 MiB, etc.
617
618
    std::string hostname      = "127.0.0.1";
619
    std::string public_path   = "";                                                                         // NOLINT
620
    std::string api_prefix    = "";                                                                         // NOLINT
621
    std::string chat_template = "";                                                                         // NOLINT
622
    bool use_jinja = true;                                                                                  // NOLINT
623
624
    // server CORS params
625
    std::string cors_origins = "*";
626
    std::string cors_methods = "GET, POST, DELETE, OPTIONS";
627
    std::string cors_headers = "*";
628
    bool cors_credentials = true;
629
    bool cors_origins_explicit = false; // for --agent option
630
631
    bool enable_chat_template = true;
632
    bool force_pure_content_parser = false;
633
    common_reasoning_format reasoning_format = COMMON_REASONING_FORMAT_DEEPSEEK;
634
    int enable_reasoning = -1; // -1 = auto, 0 = disable, 1 = enable
635
    bool prefill_assistant = true; // if true, any trailing assistant message will be prefilled into the response
636
    int sleep_idle_seconds = -1;   // if >0, server will sleep after this many seconds of idle time
637
638
    std::vector<std::string> api_keys;
639
640
    std::string ssl_file_key  = "";                                                                         // NOLINT
641
    std::string ssl_file_cert = "";                                                                         // NOLINT
642
643
    std::map<std::string, std::string> default_template_kwargs;
644
645
    // CLI params
646
    std::string server_base; // if set, connect to this server instead of starting a new one
647
648
    // UI configs
649
    bool ui = true;
650
    bool ui_mcp_proxy = false;
651
    std::string ui_config_json;
652
653
    // "advanced" endpoints are disabled by default for better security
654
    bool endpoint_slots   = true;
655
    bool endpoint_props   = false; // only control POST requests, not GET
656
    bool endpoint_metrics = false;
657
658
    // enable built-in tools
659
    std::vector<std::string> server_tools;
660
    std::string server_tools_runtime;
661
662
    // MCP server configs (Cursor-compatible JSON)
663
    std::string mcp_servers_config;   // path to JSON file with MCP server definitions
664
    std::string mcp_servers_json;     // inline JSON with MCP server definitions
665
666
    // router server configs
667
    std::string models_dir    = "";     // directory containing models for the router server
668
    std::string models_preset = "";     // directory containing model presets for the router server
669
    int models_max = 4;                 // maximum number of models to load simultaneously
670
    bool models_autoload = true;        // automatically load models when requested via the router server
671
    std::string models_preset_hf = "";  // show a warning about remote presets on router loaded (if not empty)
672
673
    bool log_json = false;
674
675
    std::string slot_save_path;
676
    std::string media_path; // path to directory for loading media files
677
678
    float slot_prompt_similarity = 0.1f;
679
680
    // batched-bench params
681
    bool is_pp_shared   = false;
682
    bool is_tg_separate = false;
683
684
    std::vector<int32_t> n_pp;
685
    std::vector<int32_t> n_tg;
686
    std::vector<int32_t> n_pl;
687
688
    // retrieval params
689
    std::vector<std::string> context_files; // context files to embed
690
691
    int32_t chunk_size = 64; // chunk size for context embedding
692
693
    std::string chunk_separator = "\n"; // chunk separator for context embedding
694
695
    // passkey params
696
    int32_t n_junk = 250; // number of times to repeat the junk text
697
    int32_t i_pos  = -1;  // position of the passkey in the junk text
698
699
    // imatrix params
700
    int32_t n_out_freq  = 10; // output the imatrix every n_out_freq iterations
701
    int32_t n_save_freq =  0; // save the imatrix every n_save_freq iterations
702
    int32_t i_chunk     =  0; // start processing from this chunk
703
    int8_t  imat_dat    =  0; // whether the legacy imatrix.dat format should be output (gguf <= 0 < dat)
704
705
    bool process_output  = false; // collect data for the output tensor
706
    bool compute_ppl     = true;  // whether to compute perplexity
707
    bool show_statistics = false; // show imatrix statistics per tensor
708
    bool parse_special   = false; // whether to parse special tokens during imatrix tokenization
709
710
    // cvector-generator params
711
    int n_pca_batch = 100;
712
    int n_pca_iterations = 1000;
713
    dimre_method cvector_dimre_method = DIMRE_METHOD_PCA;
714
    std::string cvector_positive_file = "tools/cvector-generator/positive.txt";
715
    std::string cvector_negative_file = "tools/cvector-generator/negative.txt";
716
717
    bool spm_infill = false; // suffix/prefix/middle pattern for infill
718
719
    // batched-bench params
720
    bool batched_bench_output_jsonl = false;
721
722
    // tokenize params
723
    bool tokenize_ids        = false; // if true, only print the token IDs
724
    bool tokenize_stdin      = false; // if true, read the prompt from stdin
725
    bool tokenize_no_bos     = false; // if true, do not add the BOS token
726
    bool tokenize_show_count = false; // if true, print the total token count
727
728
    // common params
729
    std::string out_file; // output filename for all example programs
730
    // optional callback for model loading progress and cancellation:
731
    // called with a progress value between 0.0 and 1.0.
732
    // return false from callback to abort model loading or true to continue
733
    llama_progress_callback load_progress_callback = NULL;
734
    void *                  load_progress_callback_user_data = NULL;
735
    bool no_alloc = false; // Don't allocate model buffers
736
737
    // TTS params
738
    std::string tts_lang = "";
739
    std::string tts_speaker_file = "";
740
741
    bool is_gen_docs = false; // whether we are running inside llama-gen-docs
742
};
743
744
// call once at the start of a program if it uses libcommon
745
// initializes the logging system and prints info about the build
746
void common_init();
747
748
void common_params_print_info(const common_params & params, bool print_devices = true);
749
std::string common_params_get_system_info(const common_params & params);
750
751
bool parse_cpu_range(const std::string & range, bool(&boolmask)[GGML_MAX_N_THREADS]);
752
bool parse_cpu_mask(const std::string & mask, bool(&boolmask)[GGML_MAX_N_THREADS]);
753
void postprocess_cpu_params(common_cpu_params & cpuparams, const common_cpu_params * role_model = nullptr);
754
bool set_process_priority(enum ggml_sched_priority prio);
755
756
//
757
// String utils
758
//
759
760
#ifdef __GNUC__
761
#    if defined(__MINGW32__) && !defined(__clang__)
762
#        define LLAMA_COMMON_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
763
#    else
764
#        define LLAMA_COMMON_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
765
#    endif
766
#else
767
#    define LLAMA_COMMON_ATTRIBUTE_FORMAT(...)
768
#endif
769
770
LLAMA_COMMON_ATTRIBUTE_FORMAT(1, 2)
771
std::string string_format(const char * fmt, ...);
772
773
std::string string_strip(const std::string & str);
774
std::string string_get_sortable_timestamp();
775
std::string string_lcs(std::string_view a, std::string_view b);
776
777
std::string string_join(const std::vector<std::string> & values, const std::string & separator);
778
std::vector<std::string> string_split(const std::string & str, const std::string & delimiter);
779
std::string string_repeat(const std::string & str, size_t n);
780
781
void string_replace_all(std::string & s, const std::string & search, const std::string & replace);
782
783
std::string regex_escape(const std::string & s);
784
785
template<class T>
786
static std::vector<T> string_split(const std::string & str, char delim) {
787
    static_assert(!std::is_same<T, std::string>::value, "Please use the specialized version for std::string");
788
    std::vector<T> values;
789
    std::istringstream str_stream(str);
790
    std::string token;
791
    while (std::getline(str_stream, token, delim)) {
792
        T value;
793
        std::istringstream token_stream(token);
794
        token_stream >> value;
795
        values.push_back(value);
796
    }
797
    return values;
798
}
799
800
template<>
801
inline std::vector<std::string> string_split<std::string>(const std::string & str, char delim)
802
0
{
803
0
    std::vector<std::string> parts;
804
0
    size_t begin_pos = 0;
805
0
    size_t delim_pos = str.find(delim);
806
0
    while (delim_pos != std::string::npos) {
807
0
        std::string part = str.substr(begin_pos, delim_pos - begin_pos);
808
0
        parts.emplace_back(part);
809
0
        begin_pos = delim_pos + 1;
810
0
        delim_pos = str.find(delim, begin_pos);
811
0
    }
812
0
    parts.emplace_back(str.substr(begin_pos));
813
0
    return parts;
814
0
}
Unexecuted instantiation: fuzz_inference.cpp:std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > string_split<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, char)
Unexecuted instantiation: common.cpp:std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > string_split<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, char)
Unexecuted instantiation: log.cpp:std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > string_split<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, char)
Unexecuted instantiation: sampling.cpp:std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > string_split<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, char)
Unexecuted instantiation: reasoning-budget.cpp:std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > string_split<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, char)
Unexecuted instantiation: json-schema-to-grammar.cpp:std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > string_split<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, char)
815
816
// remove when moving to c++20
817
0
inline bool string_starts_with(std::string_view str, std::string_view prefix) {
818
0
    return str.size() >= prefix.size() &&
819
0
           str.compare(0, prefix.size(), prefix) == 0;
820
0
}
821
822
// remove when moving to c++20
823
0
inline bool string_starts_with(std::string_view str, char prefix) {
824
0
    return !str.empty() && str.front() == prefix;
825
0
}
826
827
// remove when moving to c++20
828
0
inline bool string_ends_with(std::string_view str, std::string_view suffix) {
829
0
    return str.size() >= suffix.size() &&
830
0
           str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
831
0
}
832
833
0
inline bool string_remove_suffix(std::string & str, std::string_view suffix) {
834
0
    if (string_ends_with(str, suffix)) {
835
0
        str.resize(str.size() - suffix.size());
836
0
        return true;
837
0
    }
838
0
    return false;
839
0
}
840
841
0
inline size_t string_find_partial_stop(std::string_view str, std::string_view stop) {
842
0
    if (!str.empty() && !stop.empty()) {
843
0
        const size_t max_len = std::min(str.size(), stop.size());
844
0
        const char last_char = str.back();
845
0
        for (size_t len = max_len; len > 0; --len) {
846
0
            if (stop[len - 1] == last_char) {
847
0
                if (string_ends_with(str, stop.substr(0, len))) {
848
0
                    return str.size() - len;
849
0
                }
850
0
            }
851
0
        }
852
0
    }
853
0
    return std::string::npos;
854
0
}
855
856
bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides);
857
void string_process_escapes(std::string & input);
858
859
std::string string_from(bool value);
860
std::string string_from(const std::vector<int> & values);
861
std::string string_from(const struct llama_context * ctx, const std::vector<llama_token> & tokens);
862
std::string string_from(const struct llama_context * ctx, const struct llama_batch & batch);
863
864
bool glob_match(const std::string & pattern, const std::string & str);
865
866
//
867
// Environment utils
868
//
869
870
// portable environment access, an unset variable reads as an empty string
871
// and setting an empty value unsets the variable
872
std::string common_get_env(const std::string & name);
873
void        common_set_env(const std::string & name, const std::string & value);
874
875
//
876
// Filesystem utils
877
//
878
879
bool fs_validate_filename(const std::string & filename, bool allow_subdirs = false);
880
bool fs_create_directory_with_parents(const std::string & path);
881
bool fs_is_directory(const std::string & path);
882
883
std::string fs_get_cache_directory();
884
std::string fs_get_cache_file(const std::string & filename);
885
std::string fs_get_config_directory();
886
887
struct common_file_info {
888
    std::string path;
889
    std::string name;
890
    size_t      size = 0; // in bytes
891
    bool        is_dir = false;
892
};
893
std::vector<common_file_info> fs_list(const std::string & path, bool include_directories);
894
895
// fs open, also handle UTF8 on Windows
896
std::ifstream fs_open_ifstream(const std::string & fname, std::ios_base::openmode mode);
897
898
//
899
// TTY utils
900
//
901
902
// Auto-detect if colors can be enabled based on terminal and environment
903
bool tty_can_use_colors();
904
905
//
906
// Model utils
907
//
908
909
struct common_sampler;
910
911
// note: defines the model, context, samplers, ets. lifetimes
912
struct common_init_result {
913
    common_init_result(common_params & params, bool model_only = false);
914
    ~common_init_result();
915
916
    llama_model * model();
917
    llama_context * context();
918
919
    common_sampler * sampler(llama_seq_id seq_id);
920
    void reset_samplers();
921
922
    std::vector<llama_adapter_lora_ptr> & lora();
923
924
private:
925
    struct impl;
926
    std::unique_ptr<impl> pimpl;
927
};
928
929
using common_init_result_ptr = std::unique_ptr<common_init_result>;
930
931
common_init_result_ptr common_init_from_params(common_params & params, bool model_only = false);
932
933
struct llama_model_params   common_model_params_to_llama  (      common_params & params);
934
struct llama_context_params common_context_params_to_llama(const common_params & params);
935
936
// clear LoRA adapters from context, then apply new list of adapters
937
void common_set_adapter_lora(struct llama_context * ctx, std::vector<common_adapter_lora_info> & lora);
938
939
// model endpoint from env
940
std::string common_get_model_endpoint();
941
942
// for testing purposes
943
char * common_get_model_or_exit(int, char*[]);
944
945
//
946
// Threadpool utils
947
//
948
949
struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const common_cpu_params & params);
950
951
struct common_threadpools {
952
0
    common_threadpools() = default;
953
    ~common_threadpools();
954
955
    common_threadpools(const common_threadpools &) = delete;
956
    common_threadpools & operator=(const common_threadpools &) = delete;
957
958
    void init(llama_context * ctx, const common_params & params);
959
960
private:
961
    ggml_threadpool * threadpool       = nullptr;
962
    ggml_threadpool * threadpool_batch = nullptr;
963
964
    decltype(ggml_threadpool_free) * free_fn = nullptr;
965
};
966
967
//
968
// Context utils
969
//
970
971
enum common_context_seq_rm_type {
972
    COMMON_CONTEXT_SEQ_RM_TYPE_NO           = 0, // seq_rm not supported (e.g. no memory module)
973
    COMMON_CONTEXT_SEQ_RM_TYPE_PART         = 1, // can seq_rm partial sequences
974
    COMMON_CONTEXT_SEQ_RM_TYPE_FULL         = 2, // can seq_rm full sequences only
975
    COMMON_CONTEXT_SEQ_RM_TYPE_RS = 3, // can seq_rm partial sequences, bounded by n_rs_seq
976
};
977
978
// check if the llama_context can remove sequences
979
// note: clears the memory of the context
980
common_context_seq_rm_type common_context_can_seq_rm(llama_context * ctx);
981
982
struct common_memory {
983
    llama_context * ctx_tgt = nullptr;
984
    llama_context * ctx_dft = nullptr;
985
986
    void init(llama_context * ctx_tgt, llama_context * ctx_dft = nullptr);
987
988
    // aborts execution on failure
989
    void seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) const;
990
    void seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) const;
991
    void seq_cp (llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) const;
992
};
993
994
//
995
// Batch utils
996
//
997
998
void common_batch_clear(struct llama_batch & batch);
999
1000
void common_batch_add(
1001
                 struct llama_batch & batch,
1002
                        llama_token   id,
1003
                          llama_pos   pos,
1004
    const std::vector<llama_seq_id> & seq_ids,
1005
                               bool   logits);
1006
1007
// decodes a single batch of tokens for a prompt and manages session tokens
1008
//
1009
// Note: We save state before the last token so that we can replay it to ensure
1010
// compatibility with all memory types. Recurrent/hybrid models cannot remove
1011
// tokens from memory, so this approach works across all model architectures.
1012
bool common_prompt_batch_decode(
1013
              struct llama_context * ctx,
1014
    const std::vector<llama_token> & all_tokens,
1015
                               int   n_new,
1016
                               int & n_past,
1017
                               int   n_batch,
1018
                  std::string_view   state_path,
1019
                              bool   save_state);
1020
1021
// replays the last token after loading state to regenerate logits
1022
// used after loading session state to ensure the sampling context has valid logits
1023
bool common_replay_last_token(struct llama_context * ctx, llama_token last_token, int32_t pos);
1024
1025
//
1026
// Vocab utils
1027
//
1028
1029
// tokenizes a string into a vector of tokens
1030
// should work similar to Python's `tokenizer.encode`
1031
std::vector<llama_token> common_tokenize(
1032
  const struct llama_context * ctx,
1033
           const std::string & text,
1034
                        bool   add_special,
1035
                        bool   parse_special = false);
1036
1037
std::vector<llama_token> common_tokenize(
1038
    const struct llama_vocab * vocab,
1039
           const std::string & text,
1040
                        bool   add_special,
1041
                        bool   parse_special = false);
1042
1043
// tokenizes a token into a piece, optionally renders special/control tokens
1044
// should work similar to Python's `tokenizer.id_to_piece`
1045
std::string common_token_to_piece(
1046
        const struct llama_context * ctx,
1047
                       llama_token   token,
1048
                       bool          special = true);
1049
1050
std::string common_token_to_piece(
1051
          const struct llama_vocab * vocab,
1052
                       llama_token   token,
1053
                       bool          special = true);
1054
1055
// detokenizes a vector of tokens into a string
1056
// should work similar to Python's `tokenizer.decode`
1057
// optionally renders special/control tokens
1058
std::string common_detokenize(
1059
            const struct llama_context * ctx,
1060
        const std::vector<llama_token> & tokens,
1061
                                  bool   special = true);
1062
1063
std::string common_detokenize(
1064
              const struct llama_vocab * vocab,
1065
        const std::vector<llama_token> & tokens,
1066
                                  bool   special = true);
1067
1068
//
1069
// Embedding utils
1070
//
1071
1072
// TODO: replace embd_norm with an enum
1073
void common_embd_normalize(const float * inp, float * out, int n, int embd_norm);
1074
1075
float common_embd_similarity_cos(const float * embd1, const float * embd2, int n);
1076
1077
//
1078
// Control vector utils
1079
//
1080
1081
struct common_control_vector_data {
1082
    int n_embd;
1083
1084
    // stores data for layers [1, n_layer] where n_layer = data.size() / n_embd
1085
    std::vector<float> data;
1086
};
1087
1088
struct common_control_vector_load_info {
1089
    float strength;
1090
1091
    std::string fname;
1092
};
1093
1094
// Load control vectors, scale each by strength, and add them together.
1095
// On error, returns {-1, empty}
1096
common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos);
1097
1098
//
1099
// Split utils
1100
//
1101
1102
namespace {
1103
1104
const char * const LLM_KV_SPLIT_NO            = "split.no";
1105
const char * const LLM_KV_SPLIT_COUNT         = "split.count";
1106
const char * const LLM_KV_SPLIT_TENSORS_COUNT = "split.tensors.count";
1107
1108
}
1109
1110
//
1111
// MoE utils
1112
//
1113
1114
const char * const LLM_FFN_EXPS_REGEX = "\\.ffn_(up|down|gate|gate_up)_(ch|)exps";
1115
1116
0
inline std::string llm_ffn_exps_block_regex(int idx) {
1117
0
    return string_format("blk\\.%d%s", idx, LLM_FFN_EXPS_REGEX);
1118
0
}
1119
1120
0
inline llama_model_tensor_buft_override llm_ffn_exps_cpu_override() {
1121
0
    return { LLM_FFN_EXPS_REGEX, ggml_backend_cpu_buffer_type() };
1122
0
}
1123
1124
//
1125
// training utils
1126
//
1127
1128
ggml_opt_dataset_t common_opt_dataset_init(struct llama_context * ctx, const std::vector<llama_token> & tokens, int64_t stride);
1129
1130
// "adamw" or "sgd" (case insensitive)
1131
enum ggml_opt_optimizer_type common_opt_get_optimizer(const char *);
1132
1133
//
1134
// prompt utils
1135
//
1136
1137
struct common_prompt_checkpoint {
1138
    int64_t n_tokens;
1139
1140
    // (optional) id of the task that created the checkpoint
1141
    int id_task = -1;
1142
1143
    llama_pos pos_min;
1144
    llama_pos pos_max;
1145
1146
    std::vector<uint8_t> data_tgt;
1147
    std::vector<uint8_t> data_dft;
1148
1149
    // (optional) speculative-decoding implementation state stashed with the checkpoint
1150
    // (e.g. eagle3's deferred-boundary g_embd row)
1151
    std::vector<uint8_t> data_spec;
1152
1153
    size_t size() const;
1154
1155
    bool empty() const;
1156
    void clear();
1157
1158
    void update_pos(
1159
            int64_t n_tokens,
1160
            llama_pos pos_min,
1161
            llama_pos pos_max);
1162
1163
    void update_tgt(
1164
            llama_context * ctx,
1165
            llama_seq_id seq_id,
1166
            llama_state_seq_flags flags);
1167
1168
    void update_dft(
1169
            llama_context * ctx,
1170
            llama_seq_id seq_id,
1171
            llama_state_seq_flags flags);
1172
1173
    void load_tgt(
1174
            llama_context * ctx,
1175
            llama_seq_id seq_id,
1176
            llama_state_seq_flags flags) const;
1177
1178
    void load_dft(
1179
            llama_context * ctx,
1180
            llama_seq_id seq_id,
1181
            llama_state_seq_flags flags) const;
1182
1183
    void clear_tgt();
1184
    void clear_dft();
1185
};