2023-03-10 20:40:58 +02:00
// Various helper functions and utilities
#pragma once
2026-04-17 11:11:46 +03:00
#include "llama-cpp.h"
2025-11-20 13:40:10 +02:00
#include "ggml-opt.h"
2026-03-19 16:58:21 +01:00
#include "ggml.h"
2025-11-20 13:40:10 +02:00
2025-02-02 09:25:38 +00:00
#include <set>
2025-08-14 03:03:57 -07:00
#include <sstream>
2023-03-10 20:40:58 +02:00
#include <string>
2025-05-14 19:50:57 +01:00
#include <string_view>
2023-03-10 20:40:58 +02:00
#include <vector>
2025-06-29 20:02:53 +02:00
#include <map>
2026-05-16 20:06:23 +08:00
#include <algorithm>
2023-03-10 20:40:58 +02:00
2025-12-04 07:04:02 +01:00
#if defined(_WIN32) && !defined(_WIN32_WINNT)
#define _WIN32_WINNT 0x0A00
#endif
2023-08-28 17:59:39 +02:00
#ifdef _WIN32
#define DIRECTORY_SEPARATOR '\\'
#else
#define DIRECTORY_SEPARATOR '/'
#endif // _WIN32
2023-09-15 14:02:01 -04:00
#define die(msg) do { fputs("error: " msg "\n", stderr); exit(1); } while (0)
#define die_fmt(fmt, ...) do { fprintf(stderr, "error: " fmt "\n", __VA_ARGS__); exit(1); } while (0)
2023-09-07 13:22:29 -04:00
2025-11-20 13:40:10 +02:00
struct common_time_meas {
common_time_meas ( int64_t & t_acc , bool disable = false );
~ common_time_meas ();
const int64_t t_start_us ;
int64_t & t_acc ;
};
2025-01-12 11:32:42 +02:00
struct common_adapter_lora_info {
2024-08-06 17:33:39 +02:00
std :: string path ;
float scale ;
2025-08-28 15:49:50 +02:00
std :: string task_name ;
std :: string prompt_prefix ;
2025-01-12 11:32:42 +02:00
struct llama_adapter_lora * ptr ;
2024-08-06 17:33:39 +02:00
};
2024-11-25 09:58:41 +02:00
using llama_tokens = std :: vector < llama_token > ;
2024-10-10 22:57:42 +02:00
struct common_control_vector_load_info ;
2024-03-15 13:43:02 -07:00
2024-05-22 20:04:20 +03:00
//
// CPU utils
//
2026-04-28 09:07:33 +03:00
struct common_cpu_params {
2024-09-09 23:36:09 +02:00
int n_threads = - 1 ;
bool cpumask [ GGML_MAX_N_THREADS ] = { false }; // CPU affinity mask.
bool mask_valid = false ; // Default: any CPU
enum ggml_sched_priority priority = GGML_SCHED_PRIO_NORMAL ; // Scheduling prio : (0 - normal, 1 - medium, 2 - high, 3 - realtime)
bool strict_cpu = false ; // Use strict CPU placement
uint32_t poll = 50 ; // Polling (busywait) level (0 - no polling, 100 - mostly polling)
};
2026-04-28 09:07:33 +03:00
int32_t common_cpu_get_num_physical_cores ();
int32_t common_cpu_get_num_math ();
2024-03-15 13:43:02 -07:00
2023-03-10 20:40:58 +02:00
//
2024-09-09 23:36:09 +02:00
// Common params
2023-03-10 20:40:58 +02:00
//
2024-09-07 20:43:51 +02:00
enum llama_example {
2026-01-12 13:47:58 +01:00
LLAMA_EXAMPLE_BATCHED ,
2026-01-07 10:42:19 +01:00
LLAMA_EXAMPLE_DEBUG ,
2024-09-07 20:43:51 +02:00
LLAMA_EXAMPLE_COMMON ,
LLAMA_EXAMPLE_SPECULATIVE ,
2025-12-10 15:28:59 +01:00
LLAMA_EXAMPLE_COMPLETION ,
LLAMA_EXAMPLE_CLI ,
2024-09-07 20:43:51 +02:00
LLAMA_EXAMPLE_EMBEDDING ,
LLAMA_EXAMPLE_PERPLEXITY ,
LLAMA_EXAMPLE_RETRIEVAL ,
LLAMA_EXAMPLE_PASSKEY ,
LLAMA_EXAMPLE_IMATRIX ,
LLAMA_EXAMPLE_BENCH ,
LLAMA_EXAMPLE_SERVER ,
LLAMA_EXAMPLE_CVECTOR_GENERATOR ,
LLAMA_EXAMPLE_EXPORT_LORA ,
2025-05-22 20:42:48 +02:00
LLAMA_EXAMPLE_MTMD ,
2024-09-09 23:36:09 +02:00
LLAMA_EXAMPLE_LOOKUP ,
LLAMA_EXAMPLE_PARALLEL ,
2024-12-18 19:27:21 +02:00
LLAMA_EXAMPLE_TTS ,
2025-07-16 20:03:51 +08:00
LLAMA_EXAMPLE_DIFFUSION ,
2025-08-14 03:03:57 -07:00
LLAMA_EXAMPLE_FINETUNE ,
2025-12-15 09:24:59 +01:00
LLAMA_EXAMPLE_FIT_PARAMS ,
2026-03-08 12:30:21 +01:00
LLAMA_EXAMPLE_RESULTS ,
2026-03-12 13:26:00 +01:00
LLAMA_EXAMPLE_EXPORT_GRAPH_OPS ,
2024-09-07 20:43:51 +02:00
LLAMA_EXAMPLE_COUNT ,
};
2024-10-10 22:57:42 +02:00
enum common_sampler_type {
COMMON_SAMPLER_TYPE_NONE = 0 ,
2024-10-25 10:07:34 -06:00
COMMON_SAMPLER_TYPE_DRY = 1 ,
COMMON_SAMPLER_TYPE_TOP_K = 2 ,
COMMON_SAMPLER_TYPE_TOP_P = 3 ,
COMMON_SAMPLER_TYPE_MIN_P = 4 ,
2024-10-29 10:42:05 +02:00
//COMMON_SAMPLER_TYPE_TFS_Z = 5,
2024-10-25 10:07:34 -06:00
COMMON_SAMPLER_TYPE_TYPICAL_P = 6 ,
COMMON_SAMPLER_TYPE_TEMPERATURE = 7 ,
COMMON_SAMPLER_TYPE_XTC = 8 ,
COMMON_SAMPLER_TYPE_INFILL = 9 ,
2024-12-16 12:31:14 +02:00
COMMON_SAMPLER_TYPE_PENALTIES = 10 ,
2025-05-05 17:12:19 -03:00
COMMON_SAMPLER_TYPE_TOP_N_SIGMA = 11 ,
2026-01-15 11:16:29 -06:00
COMMON_SAMPLER_TYPE_ADAPTIVE_P = 12 ,
2024-09-09 23:36:09 +02:00
};
2024-06-25 13:59:54 +02:00
// dimensionality reduction methods, used by cvector-generator
enum dimre_method {
DIMRE_METHOD_PCA ,
DIMRE_METHOD_MEAN ,
};
2025-01-13 20:18:12 +01:00
enum common_conversation_mode {
COMMON_CONVERSATION_MODE_DISABLED = 0 ,
COMMON_CONVERSATION_MODE_ENABLED = 1 ,
COMMON_CONVERSATION_MODE_AUTO = 2 ,
};
2025-03-05 13:05:13 +00:00
enum common_grammar_trigger_type {
COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN ,
COMMON_GRAMMAR_TRIGGER_TYPE_WORD ,
COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN ,
2025-05-25 01:48:08 +01:00
COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL ,
2025-03-05 13:05:13 +00:00
};
2025-01-30 19:13:58 +00:00
struct common_grammar_trigger {
2025-03-05 13:05:13 +00:00
common_grammar_trigger_type type ;
std :: string value ;
llama_token token = LLAMA_TOKEN_NULL ;
2025-01-30 19:13:58 +00:00
};
2025-11-25 09:56:07 +08:00
enum common_params_sampling_config : uint64_t {
COMMON_PARAMS_SAMPLING_CONFIG_SAMPLERS = 1 << 0 ,
COMMON_PARAMS_SAMPLING_CONFIG_TOP_K = 1 << 1 ,
COMMON_PARAMS_SAMPLING_CONFIG_TOP_P = 1 << 2 ,
COMMON_PARAMS_SAMPLING_CONFIG_MIN_P = 1 << 3 ,
COMMON_PARAMS_SAMPLING_CONFIG_XTC_PROBABILITY = 1 << 4 ,
COMMON_PARAMS_SAMPLING_CONFIG_XTC_THRESHOLD = 1 << 5 ,
COMMON_PARAMS_SAMPLING_CONFIG_TEMP = 1 << 6 ,
COMMON_PARAMS_SAMPLING_CONFIG_PENALTY_LAST_N = 1 << 7 ,
COMMON_PARAMS_SAMPLING_CONFIG_PENALTY_REPEAT = 1 << 8 ,
COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT = 1 << 9 ,
COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT_TAU = 1 << 10 ,
COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT_ETA = 1 << 11 ,
};
2026-01-28 18:42:42 +01:00
enum common_speculative_type {
COMMON_SPECULATIVE_TYPE_NONE , // no speculative decoding
2026-05-13 09:15:39 +03:00
COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE , // standalone draft model speculative decoding
COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3 , // Eagle3 speculative decoding
2026-05-16 20:06:23 +08:00
COMMON_SPECULATIVE_TYPE_DRAFT_MTP , // Multi-token prediction
2026-05-13 09:15:39 +03:00
COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE , // simple self-speculative decoding based on n-grams
2026-01-28 18:42:42 +01:00
COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K , // self-speculative decoding with n-gram keys only
COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V , // self-speculative decoding with n-gram keys and 4 m-gram values
2026-01-30 18:21:48 +02:00
COMMON_SPECULATIVE_TYPE_NGRAM_MOD ,
2026-01-28 18:42:42 +01:00
COMMON_SPECULATIVE_TYPE_NGRAM_CACHE , // self-speculative decoding with 3-level n-gram cache
COMMON_SPECULATIVE_TYPE_COUNT // number of types, unknown type
};
2025-11-25 09:56:07 +08:00
2026-03-19 16:58:21 +01:00
// Grammar type enumeration
enum common_grammar_type {
COMMON_GRAMMAR_TYPE_NONE , // no grammar set
COMMON_GRAMMAR_TYPE_USER , // user-provided GBNF (--grammar / "grammar" API field)
COMMON_GRAMMAR_TYPE_OUTPUT_FORMAT , // auto-generated from JSON schema (--json-schema / "json_schema" API field)
COMMON_GRAMMAR_TYPE_TOOL_CALLS , // auto-generated by chat template parser for function calling
};
// Grammar variant struct with type and grammar string
struct common_grammar {
common_grammar_type type = COMMON_GRAMMAR_TYPE_NONE ;
std :: string grammar ;
// Default constructor - no grammar
common_grammar () = default ;
// Constructor with type and grammar string
common_grammar ( common_grammar_type t , std :: string g ) : type ( t ), grammar ( std :: move ( g )) {
GGML_ASSERT ( type != COMMON_GRAMMAR_TYPE_NONE || ! grammar . empty ());
}
// Check if a grammar is set
bool empty () const { return type == COMMON_GRAMMAR_TYPE_NONE || grammar . empty (); }
};
// Returns the raw grammar string, or empty string if no grammar is set.
inline const std :: string & common_grammar_value ( const common_grammar & g ) {
return g . grammar ;
}
// Returns true when the generation_prompt should be prefilled into the grammar sampler.
// Only output-format and tool-call grammars need prefill; user-supplied grammars must not be prefilled.
inline bool common_grammar_needs_prefill ( const common_grammar & g ) {
return g . type == COMMON_GRAMMAR_TYPE_OUTPUT_FORMAT
|| g . type == COMMON_GRAMMAR_TYPE_TOOL_CALLS ;
}
2024-11-25 09:58:41 +02:00
// sampling parameters
struct common_params_sampling {
2024-09-09 23:36:09 +02:00
uint32_t seed = LLAMA_DEFAULT_SEED ; // the seed used to initialize llama_sampler
2026-01-15 11:16:29 -06:00
int32_t n_prev = 64 ; // number of previous tokens to remember
int32_t n_probs = 0 ; // if greater than 0, output the probabilities of top n_probs tokens.
int32_t min_keep = 0 ; // 0 = disabled, otherwise samplers should return at least min_keep tokens
int32_t top_k = 40 ; // <= 0 to use vocab size
float top_p = 0.95f ; // 1.0 = disabled
float min_p = 0.05f ; // 0.0 = disabled
float xtc_probability = 0.00f ; // 0.0 = disabled
float xtc_threshold = 0.10f ; // > 0.5 disables XTC
float typ_p = 1.00f ; // typical_p, 1.0 = disabled
float temp = 0.80f ; // <= 0.0 to sample greedily, 0.0 to not output probabilities
float dynatemp_range = 0.00f ; // 0.0 = disabled
float dynatemp_exponent = 1.00f ; // controls how entropy maps to temperature in dynamic temperature sampler
int32_t penalty_last_n = 64 ; // last n tokens to penalize (0 = disable penalty, -1 = context size)
float penalty_repeat = 1.00f ; // 1.0 = disabled
float penalty_freq = 0.00f ; // 0.0 = disabled
float penalty_present = 0.00f ; // 0.0 = disabled
float dry_multiplier = 0.0f ; // 0.0 = disabled; DRY repetition penalty for tokens extending repetition:
float dry_base = 1.75f ; // 0.0 = disabled; multiplier * base ^ (length of sequence before token - allowed length)
int32_t dry_allowed_length = 2 ; // tokens extending repetitions beyond this receive penalty
int32_t dry_penalty_last_n = - 1 ; // how many tokens to scan for repetitions (0 = disable penalty, -1 = context size)
float adaptive_target = - 1.0f ; // select tokens near this probability (valid range 0.0 to 1.0; negative = disabled)
float adaptive_decay = 0.90f ; // EMA decay for adaptation; history ≈ 1/(1-decay) tokens (0.0 - 0.99)
int32_t mirostat = 0 ; // 0 = disabled, 1 = mirostat, 2 = mirostat 2.0
float top_n_sigma = - 1.00f ; // -1.0 = disabled
float mirostat_tau = 5.00f ; // target entropy
float mirostat_eta = 0.10f ; // learning rate
2024-10-25 10:07:34 -06:00
bool ignore_eos = false ;
2026-01-15 11:16:29 -06:00
bool no_perf = false ; // disable performance metrics
2024-12-02 21:45:54 +08:00
bool timing_per_token = false ;
2024-10-25 10:07:34 -06:00
2025-11-25 09:56:07 +08:00
uint64_t user_sampling_config = 0 ; // bitfield to track user-specified samplers
2024-10-25 10:07:34 -06:00
std :: vector < std :: string > dry_sequence_breakers = { " \n " , ":" , " \" " , "*" }; // default sequence breakers for DRY
2024-09-09 23:36:09 +02:00
2024-10-10 22:57:42 +02:00
std :: vector < enum common_sampler_type > samplers = {
2024-12-16 12:31:14 +02:00
COMMON_SAMPLER_TYPE_PENALTIES ,
2024-10-25 10:07:34 -06:00
COMMON_SAMPLER_TYPE_DRY ,
2025-05-05 17:12:19 -03:00
COMMON_SAMPLER_TYPE_TOP_N_SIGMA ,
2024-10-10 22:57:42 +02:00
COMMON_SAMPLER_TYPE_TOP_K ,
COMMON_SAMPLER_TYPE_TYPICAL_P ,
COMMON_SAMPLER_TYPE_TOP_P ,
COMMON_SAMPLER_TYPE_MIN_P ,
2024-10-15 15:54:55 +05:00
COMMON_SAMPLER_TYPE_XTC ,
2024-10-15 16:35:33 +03:00
COMMON_SAMPLER_TYPE_TEMPERATURE ,
2024-09-09 23:36:09 +02:00
};
2026-03-19 16:58:21 +01:00
common_grammar grammar ; // optional grammar constraint (user / output-format / tool-calls)
2025-01-30 19:13:58 +00:00
bool grammar_lazy = false ;
2025-03-05 13:05:13 +00:00
std :: vector < common_grammar_trigger > grammar_triggers ; // optional triggers (for lazy grammars)
2025-02-02 09:25:38 +00:00
std :: set < llama_token > preserved_tokens ;
2024-09-09 23:36:09 +02:00
2025-07-16 14:04:12 +03:00
std :: vector < llama_logit_bias > logit_bias ; // logit biases to apply
std :: vector < llama_logit_bias > logit_bias_eog ; // pre-calculated logit biases for EOG tokens
2024-09-09 23:36:09 +02:00
2026-03-19 16:58:21 +01:00
// The assistant generation prompt already prefilled into the prompt.
// Fed to the grammar sampler (to advance past pre-existing tokens) and used
// to determine the reasoning budget sampler's initial state.
// Only applied when the grammar is of output-format or tool-calls type.
std :: string generation_prompt ;
2026-03-11 10:26:12 +01:00
// reasoning budget sampler parameters
// these are populated by the server/CLI based on chat template params
int32_t reasoning_budget_tokens = - 1 ; // -1 = disabled, >= 0 = token budget
std :: vector < llama_token > reasoning_budget_start ; // start tag token sequence
std :: vector < llama_token > reasoning_budget_end ; // end tag token sequence
std :: vector < llama_token > reasoning_budget_forced ; // forced sequence (message + end tag)
2026-04-22 01:40:19 -07:00
std :: string reasoning_budget_message ; // message injected before end tag when budget exhausted
2026-06-02 07:26:20 +02:00
bool reasoning_control = false ; // create the budget sampler on demand so reasoning can be ended at runtime
2026-03-11 10:26:12 +01:00
2026-01-04 21:22:16 +01:00
bool backend_sampling = false ;
2025-12-14 10:11:13 +02:00
bool has_logit_bias () const {
return ! logit_bias . empty ();
}
2024-09-09 23:36:09 +02:00
// print the parameters into a string
std :: string print () const ;
2024-08-29 19:20:53 -04:00
};
2025-04-01 23:44:05 +02:00
struct common_params_model {
2025-09-12 16:31:50 +01:00
std :: string path = "" ; // model local path // NOLINT
std :: string url = "" ; // model url to download // NOLINT
std :: string hf_repo = "" ; // HF repo // NOLINT
std :: string hf_file = "" ; // HF file // NOLINT
std :: string docker_repo = "" ; // Docker repo // NOLINT
2025-12-01 19:41:04 +01:00
std :: string name = "" ; // in format <user>/<model>[:<tag>] (tag is optional) // NOLINT
2025-04-01 23:44:05 +02:00
};
2026-04-28 09:07:33 +03:00
// draft-model-based speculative decoding parameters
struct common_params_speculative_draft {
2026-05-19 15:32:58 +03:00
int32_t n_max = 3 ; // maximum number of tokens to draft during speculative decoding
int32_t n_min = 0 ; // minimum number of draft tokens to use for speculative decoding
2024-12-18 19:27:21 +02:00
2026-05-19 15:32:58 +03:00
float p_split = 0.1f ; // speculative decoding split probability
float p_min = 0.0f ; // minimum speculative decoding probability (greedy)
2026-01-28 18:42:42 +01:00
2026-05-20 22:34:45 +05:30
bool backend_sampling = true ; // offload draft sampling to the backend (default: on)
2026-04-28 09:07:33 +03:00
common_params_model mparams ;
2026-01-28 18:42:42 +01:00
2026-05-11 19:09:43 +03:00
llama_context * ctx_tgt = nullptr ;
llama_context * ctx_dft = nullptr ;
2026-01-28 18:42:42 +01:00
int32_t n_gpu_layers = - 1 ; // number of layers to store in VRAM for the draft model (-1 - use default)
2024-11-25 09:58:41 +02:00
2025-06-19 16:01:03 +03:00
ggml_type cache_type_k = GGML_TYPE_F16 ; // KV cache data type for the K
ggml_type cache_type_v = GGML_TYPE_F16 ; // KV cache data type for the V
2026-04-28 09:07:33 +03:00
common_cpu_params cpuparams ;
common_cpu_params cpuparams_batch ;
2024-11-25 09:58:41 +02:00
2026-01-28 18:42:42 +01:00
std :: vector < ggml_backend_dev_t > devices ; // devices to use for offloading
std :: vector < llama_model_tensor_buft_override > tensor_buft_overrides ;
2026-04-28 09:07:33 +03:00
};
struct common_params_speculative_ngram_mod {
int32_t n_match = 24 ;
int32_t n_max = 64 ;
int32_t n_min = 48 ;
};
struct common_params_speculative_ngram_map {
uint16_t size_n = 12 ; // ngram size for lookup
uint16_t size_m = 48 ; // mgram size for speculative tokens
uint16_t min_hits = 1 ; // minimum hits at ngram/mgram lookup for mgram to be proposed
};
struct common_params_speculative_ngram_cache {
std :: string lookup_cache_static ; // path of static ngram cache file for lookup decoding
std :: string lookup_cache_dynamic ; // path of dynamic ngram cache file for lookup decoding
};
struct common_params_speculative {
2026-05-11 19:09:43 +03:00
std :: vector < enum common_speculative_type > types = { COMMON_SPECULATIVE_TYPE_NONE };
2026-04-28 09:07:33 +03:00
2026-05-13 09:15:39 +03:00
// used by Simple, MTP, Eagle3, etc. - all methods that require some kind of draft model
2026-04-28 09:07:33 +03:00
common_params_speculative_draft draft ;
common_params_speculative_ngram_mod ngram_mod ;
common_params_speculative_ngram_map ngram_simple ;
common_params_speculative_ngram_map ngram_map_k ;
common_params_speculative_ngram_map ngram_map_k4v ;
common_params_speculative_ngram_cache ngram_cache ;
2026-01-28 18:42:42 +01:00
bool has_dft () const {
2026-04-28 09:07:33 +03:00
return ! draft . mparams . path . empty () || ! draft . mparams . hf_repo . empty ();
2026-01-28 18:42:42 +01:00
}
2026-05-16 20:06:23 +08:00
uint32_t need_n_rs_seq () const {
bool needs_rs_seq = std :: any_of ( types . begin (), types . end (), [ & ]( auto t ) {
2026-06-19 12:08:50 +02:00
return t == COMMON_SPECULATIVE_TYPE_DRAFT_MTP || t == COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3 ;
2026-05-16 20:06:23 +08:00
});
return needs_rs_seq ? draft . n_max : 0u ;
}
2024-11-25 09:58:41 +02:00
};
2024-12-18 19:27:21 +02:00
struct common_params_vocoder {
2025-04-01 23:44:05 +02:00
struct common_params_model model ;
2025-01-18 18:20:57 +08:00
2026-04-28 09:07:33 +03:00
std :: string speaker_file ; // speaker file path
2025-03-03 21:09:29 +08:00
2026-04-28 09:07:33 +03:00
bool use_guide_tokens = false ; // enable guide tokens to improve TTS accuracy
2024-12-18 19:27:21 +02:00
};
2025-07-16 20:03:51 +08:00
struct common_params_diffusion {
2025-07-31 19:49:09 +08:00
int32_t steps = 128 ;
bool visual_mode = false ;
float eps = 0 ; // epsilon for timesteps
2025-08-01 01:22:58 +08:00
int32_t block_length = 0 ; // block length for generation
2025-07-31 19:49:09 +08:00
int32_t algorithm = 4 ; // default algorithm: low-confidence
float alg_temp = 0.0f ; // algorithm temperature
float cfg_scale = 0 ; // classifier-free guidance scale
bool add_gumbel_noise = false ; // add gumbel noise to the logits if temp > 0.0
2025-07-16 20:03:51 +08:00
};
2025-08-19 10:29:36 +02:00
// reasoning API response format (not to be confused as chat template's reasoning format)
2026-01-20 18:23:25 +01:00
// only used by server
2025-02-13 10:05:16 +00:00
enum common_reasoning_format {
COMMON_REASONING_FORMAT_NONE ,
2025-08-19 10:29:36 +02:00
COMMON_REASONING_FORMAT_AUTO , // Same as deepseek, using `message.reasoning_content`
2025-06-02 10:15:44 -07:00
COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY , // Extract thinking tag contents and return as `message.reasoning_content`, or leave inline in <think> tags in stream mode
COMMON_REASONING_FORMAT_DEEPSEEK , // Extract thinking tag contents and return as `message.reasoning_content`, including in streaming deltas.
2025-08-19 10:29:36 +02:00
// do not extend this enum unless you absolutely have to
// in most cases, use COMMON_REASONING_FORMAT_AUTO
// see: https://github.com/ggml-org/llama.cpp/pull/15408
2025-02-13 10:05:16 +00:00
};
2025-08-14 03:03:57 -07:00
struct lr_opt {
float lr0 = 1e-5 ; // learning rate at first epoch
float lr_min = - 1 ;
float decay_epochs = - 1 ; // if >0, the learning rate starts at lr0 and decays to lr_min after this many epochs
float scale_epoch = 0 ;
float wd = 0 ;
unsigned epochs = 2 ;
unsigned epoch ; // set by optimizer outer (epochs) loop
// learning rate decay - constant LR per epoch only for now
float get_lr ( float e ) const ;
float get_lr () const { return get_lr ( epoch ); }
// must call after arg parse, before get_lr
void init ();
};
struct ggml_opt_optimizer_params common_opt_lr_pars ( void * userdata );
2024-10-10 22:57:42 +02:00
struct common_params {
2025-12-15 09:24:59 +01:00
int32_t n_predict = - 1 ; // max. number of new tokens to predict, -1 == no limit
int32_t n_ctx = 0 ; // context size, 0 == context the model was trained with
2024-06-06 16:30:58 +03:00
int32_t n_batch = 2048 ; // logical batch size for prompt processing (must be >=32 to use BLAS)
int32_t n_ubatch = 512 ; // physical batch size for prompt processing (must be >=32 to use BLAS)
int32_t n_keep = 0 ; // number of tokens to keep from initial prompt
int32_t n_chunks = - 1 ; // max number of chunks to process (-1 = unlimited)
int32_t n_parallel = 1 ; // number of parallel sequences to decode
int32_t n_sequences = 1 ; // number of sequences to decode
2026-06-01 23:01:38 +08:00
int32_t n_outputs_max = 0 ; // max outputs in a batch (0 = n_batch)
2024-06-06 16:30:58 +03:00
int32_t grp_attn_n = 1 ; // group-attention factor
int32_t grp_attn_w = 512 ; // group-attention width
int32_t n_print = - 1 ; // print token count every n tokens (-1 = disabled)
float rope_freq_base = 0.0f ; // RoPE base frequency
float rope_freq_scale = 0.0f ; // RoPE frequency scaling factor
2024-01-31 17:30:17 +02:00
float yarn_ext_factor = - 1.0f ; // YaRN extrapolation mix factor
2025-09-14 23:00:59 +02:00
float yarn_attn_factor = - 1.0f ; // YaRN magnitude scaling factor
float yarn_beta_fast = - 1.0f ; // YaRN low correction dim
float yarn_beta_slow = - 1.0f ; // YaRN high correction dim
2024-06-06 16:30:58 +03:00
int32_t yarn_orig_ctx = 0 ; // YaRN original context length
2024-03-03 04:40:27 -06:00
2024-11-25 19:30:06 +01:00
// offload params
2024-12-16 12:31:14 +02:00
std :: vector < ggml_backend_dev_t > devices ; // devices to use for offloading
2026-04-21 09:54:36 +03:00
int32_t n_gpu_layers = - 1 ; // number of layers to store in VRAM, -1 is auto, <= -2 is all
int32_t main_gpu = 0 ; // the GPU that is used for scratch and small tensors
float tensor_split [ 128 ] = { 0 }; // how split tensors should be distributed across GPUs
bool fit_params = true ; // whether to fit unset model/context parameters to free device memory
bool fit_params_print = false ; // print the estimated required memory to run the model
int32_t fit_params_min_ctx = 4096 ; // minimum context size to set when trying to reduce memory use
2026-01-08 10:07:58 +01:00
// margin per device in bytes for fitting parameters to free memory:
std :: vector < size_t > fit_params_target = std :: vector < size_t > ( llama_max_devices (), 1024 * 1024 * 1024 );
2024-12-16 12:31:14 +02:00
enum llama_split_mode split_mode = LLAMA_SPLIT_MODE_LAYER ; // how to split the model across GPUs
2024-11-25 19:30:06 +01:00
2026-04-28 09:07:33 +03:00
common_cpu_params cpuparams ;
common_cpu_params cpuparams_batch ;
2024-08-29 19:20:53 -04:00
2024-04-11 14:51:07 +02:00
ggml_backend_sched_eval_callback cb_eval = nullptr ;
void * cb_eval_user_data = nullptr ;
2024-03-03 04:40:27 -06:00
ggml_numa_strategy numa = GGML_NUMA_STRATEGY_DISABLED ;
2024-04-24 08:10:07 -05:00
enum llama_rope_scaling_type rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED ;
enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_UNSPECIFIED ; // pooling type for embeddings
2024-07-05 02:05:56 -05:00
enum llama_attention_type attention_type = LLAMA_ATTENTION_TYPE_UNSPECIFIED ; // attention type for embeddings
2025-08-30 16:32:10 +02:00
enum llama_flash_attn_type flash_attn_type = LLAMA_FLASH_ATTN_TYPE_AUTO ; // whether to use Flash Attention
2023-03-17 21:46:46 +02:00
2024-12-18 19:27:21 +02:00
struct common_params_sampling sampling ;
2024-11-25 09:58:41 +02:00
struct common_params_speculative speculative ;
2024-12-18 19:27:21 +02:00
struct common_params_vocoder vocoder ;
2025-07-16 20:03:51 +08:00
struct common_params_diffusion diffusion ;
2023-07-12 00:18:43 +08:00
2025-04-01 23:44:05 +02:00
struct common_params_model model ;
2026-02-27 07:05:23 +01:00
std :: set < std :: string > model_alias ; // model aliases // NOLINT
std :: set < std :: string > model_tags ; // model tags (informational, not used for routing) // NOLINT
2026-05-29 16:30:55 +02:00
std :: string hf_token = "" ; // HF token (aka bearer token) // NOLINT
2024-09-09 23:36:09 +02:00
std :: string prompt = "" ; // NOLINT
2025-03-01 13:56:45 +01:00
std :: string system_prompt = "" ; // NOLINT
2024-09-09 23:36:09 +02:00
std :: string prompt_file = "" ; // store the external prompt file name // NOLINT
std :: string path_prompt_cache = "" ; // path to file for saving/loading prompt eval state // NOLINT
std :: string input_prefix = "" ; // string to prefix user inputs with // NOLINT
std :: string input_suffix = "" ; // string to suffix user inputs with // NOLINT
std :: string logits_file = "" ; // file for saving *all* logits // NOLINT
2026-06-09 12:09:07 +02:00
std :: string path_prompts_log_dir = "" ; // directory with logged prompts // NOLINT
2023-03-21 17:32:14 +02:00
2026-01-07 10:42:19 +01:00
// llama-debug specific options
std :: string logits_output_dir = "data" ; // directory for saving logits output files // NOLINT
bool save_logits = false ; // whether to save logits to files // NOLINT
std :: vector < std :: string > tensor_filter ; // filter tensor names for debug output (regex) // NOLINT
2024-06-06 16:30:58 +03:00
std :: vector < std :: string > in_files ; // all input files
2024-06-04 21:23:39 +03:00
std :: vector < std :: string > antiprompt ; // strings upon which more user input is prompted (a.k.a. reverse prompts)
2023-12-05 10:19:18 -07:00
std :: vector < llama_model_kv_override > kv_overrides ;
2025-04-02 14:52:01 +02:00
std :: vector < llama_model_tensor_buft_override > tensor_buft_overrides ;
2023-12-05 10:19:18 -07:00
2025-01-12 11:32:42 +02:00
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)
std :: vector < common_adapter_lora_info > lora_adapters ; // lora adapter path with user defined scale
2023-04-17 17:28:55 +02:00
2024-10-10 22:57:42 +02:00
std :: vector < common_control_vector_load_info > control_vectors ; // control vector with user defined scale
2024-03-15 13:43:02 -07:00
2025-12-01 14:38:13 +01:00
int32_t verbosity = 3 ; // LOG_LEVEL_INFO
2024-03-15 13:43:02 -07:00
int32_t control_vector_layer_start = - 1 ; // layer range for control vector
int32_t control_vector_layer_end = - 1 ; // layer range for control vector
2025-05-26 14:34:27 -07:00
bool offline = false ;
2026-05-29 16:30:55 +02:00
bool skip_download = false ; // skip model file downloading
2024-03-15 13:43:02 -07:00
2024-06-06 16:30:58 +03:00
int32_t ppl_stride = 0 ; // stride for perplexity calculations. If left at 0, the pre-existing approach will be used.
int32_t ppl_output_type = 0 ; // = 0 -> ppl output is as usual, = 1 -> ppl output is num_tokens, ppl, one per line
// (which is more convenient to use for plotting)
//
bool hellaswag = false ; // compute HellaSwag score over random tasks from datafile supplied in prompt
size_t hellaswag_tasks = 400 ; // number of tasks to use when computing the HellaSwag score
2023-07-28 20:25:36 +02:00
2024-06-06 16:30:58 +03:00
bool winogrande = false ; // compute Winogrande score over random tasks from datafile supplied in prompt
size_t winogrande_tasks = 0 ; // number of tasks to use when computing the Winogrande score. If 0, all tasks will be computed
2024-01-18 13:46:27 +02:00
2024-06-06 16:30:58 +03:00
bool multiple_choice = false ; // compute TruthfulQA score over random tasks from datafile supplied in prompt
size_t multiple_choice_tasks = 0 ; // number of tasks to use when computing the TruthfulQA score. If 0, all tasks will be computed
2024-01-21 14:42:44 +02:00
2024-06-06 16:30:58 +03:00
bool kl_divergence = false ; // compute KL divergence
2024-01-22 16:10:14 +02:00
2026-03-08 12:30:21 +01:00
bool check = false ; // check rather than generate results for llama-results
2024-06-04 21:23:39 +03:00
bool usage = false ; // print usage
2025-02-13 14:46:59 +01:00
bool completion = false ; // print source-able completion script
2023-03-21 17:32:14 +02:00
bool use_color = false ; // use color to distinguish generations and inputs
2024-05-27 00:10:17 +10:00
bool special = false ; // enable special token output
2024-06-04 21:23:39 +03:00
bool interactive = false ; // interactive mode
bool interactive_first = false ; // wait for user input immediately
2023-05-10 11:37:14 -04:00
bool prompt_cache_all = false ; // save user input and generations to prompt cache
2023-06-07 04:10:17 +02:00
bool prompt_cache_ro = false ; // open the prompt cache read-only and do not update it
2023-03-24 08:05:13 -07:00
2024-06-04 21:23:39 +03:00
bool escape = true ; // escape "\n", "\r", "\t", "\'", "\"", and "\\"
2023-05-08 19:45:48 -07:00
bool multiline_input = false ; // reverse the usage of `\`
2023-08-04 08:20:12 -07:00
bool simple_io = false ; // improves compatibility with subprocesses and limited consoles
2024-03-22 13:08:28 +02:00
bool cont_batching = true ; // insert new sequences for decoding on-the-fly
2024-09-13 09:53:38 +03:00
bool no_perf = false ; // disable performance metrics
2025-12-10 15:28:59 +01:00
bool show_timings = true ; // show timing information on CLI
2025-10-09 18:54:51 +03:00
bool ctx_shift = false ; // context shift on infinite text generation
2025-05-20 08:05:46 +03:00
bool swa_full = false ; // use full-size SWA cache (https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)
2025-07-16 16:35:42 +03:00
bool kv_unified = false ; // enable unified KV cache
2023-03-24 08:05:13 -07:00
2023-07-25 07:19:11 -05:00
bool input_prefix_bos = false ; // prefix BOS to user inputs, preceding input_prefix
2026-01-08 07:35:30 +01:00
bool use_mmap = true ; // enable mmap to use filesystem cache
2026-01-28 09:11:13 +02:00
bool use_direct_io = false ; // read from disk without buffering
2023-03-24 08:19:05 -07:00
bool use_mlock = false ; // use mlock to keep model in memory
2023-03-25 17:16:50 +02:00
bool verbose_prompt = false ; // print prompt tokens before generation
2024-01-14 00:09:08 +08:00
bool display_prompt = true ; // print prompt before generation
2023-12-07 13:03:17 +02:00
bool no_kv_offload = false ; // disable KV offloading
2024-04-11 14:51:07 +02:00
bool warmup = true ; // warmup run
2024-04-26 18:39:58 +02:00
bool check_tensors = false ; // validate tensor data
2025-05-11 20:18:39 +08:00
bool no_op_offload = false ; // globally disable offload host tensor operations to device
2025-07-31 09:11:34 -07:00
bool no_extra_bufts = false ; // disable extra buffer types (used for weight repacking)
2025-10-06 12:55:53 -05:00
bool no_host = false ; // bypass host buffer allowing extra buffers to be used
2023-12-07 13:03:17 +02:00
2025-03-04 17:19:39 +01:00
bool single_turn = false ; // single turn chat conversation
2024-12-12 22:53:05 +01:00
ggml_type cache_type_k = GGML_TYPE_F16 ; // KV cache data type for the K
ggml_type cache_type_v = GGML_TYPE_F16 ; // KV cache data type for the V
2023-10-12 18:23:18 +03:00
2025-01-13 20:18:12 +01:00
common_conversation_mode conversation_mode = COMMON_CONVERSATION_MODE_AUTO ;
2025-05-05 16:02:55 +02:00
// multimodal models (see tools/mtmd)
2025-04-01 23:44:05 +02:00
struct common_params_model mmproj ;
2025-04-24 14:04:14 +02:00
bool mmproj_use_gpu = true ; // use GPU for multimodal model
2025-04-24 12:14:13 +02:00
bool no_mmproj = false ; // explicitly disable multimodal model
2026-06-08 13:40:12 +02:00
std :: vector < std :: string > image ; // path to image file(s) ; TODO: change the name to "media"
2025-11-03 11:11:18 +01:00
int image_min_tokens = - 1 ;
int image_max_tokens = - 1 ;
2026-06-13 00:10:29 +02:00
int mtmd_batch_max_tokens = 1024 ;
2024-06-04 21:23:39 +03:00
2025-08-14 03:03:57 -07:00
// finetune
struct lr_opt lr ;
enum ggml_opt_optimizer_type optimizer = GGML_OPT_OPTIMIZER_TYPE_ADAMW ;
float val_split = 0.05f ; // fraction of the data used for the validation set
2024-06-24 13:30:24 +08:00
// embedding
bool embedding = false ; // get only sentence embedding
2024-10-22 09:40:02 +02:00
int32_t embd_normalize = 2 ; // normalisation for embeddings (-1=none, 0=max absolute int16, 1=taxicab, 2=euclidean, >2=p-norm)
2024-06-24 13:30:24 +08:00
std :: string embd_out = "" ; // empty = default, "array" = [[],[]...], "json" = openai style, "json+" = same "json" + cosine similarity matrix
2024-10-22 09:40:02 +02:00
std :: string embd_sep = " \n " ; // separator of embeddings
2025-06-20 14:04:09 +02:00
std :: string cls_sep = " \t " ; // separator of classification sequences
2024-06-24 13:30:24 +08:00
2024-06-04 21:23:39 +03:00
// server params
2026-03-06 11:39:26 +01:00
int32_t port = 8080 ; // server listens on this network port
2026-03-28 01:12:43 +01:00
bool reuse_port = false ; // allow multiple sockets to bind to the same port
2026-05-29 10:23:17 +02:00
int32_t timeout_read = 3600 ; // http read timeout in seconds
2026-03-06 11:39:26 +01:00
int32_t timeout_write = timeout_read ; // http write timeout in seconds
2026-06-02 14:14:55 +02:00
int32_t sse_ping_interval = 30 ; // SSE ping interval in seconds
2026-03-06 11:39:26 +01:00
int32_t n_threads_http = - 1 ; // number of threads to process HTTP requests (TODO: support threadpool)
int32_t n_cache_reuse = 0 ; // min chunk size to reuse from the cache via KV shifting
bool cache_prompt = true ; // whether to enable prompt caching
2026-04-20 08:30:24 +03:00
bool cache_idle_slots = true ; // save and clear idle slots upon starting a new task
2026-04-03 20:02:27 +03:00
int32_t n_ctx_checkpoints = 32 ; // max number of context checkpoints per slot
2026-05-25 07:56:18 +02:00
int32_t checkpoint_min_step = 256 ; // minimum spacing between context checkpoints
2026-03-06 11:39:26 +01:00
int32_t cache_ram_mib = 8192 ; // -1 = no limit, 0 - disable, 1 = 1 MiB, etc.
2024-06-04 21:23:39 +03:00
std :: string hostname = "127.0.0.1" ;
2024-09-09 23:36:09 +02:00
std :: string public_path = "" ; // NOLINT
2025-07-08 11:47:33 +03:00
std :: string api_prefix = "" ; // NOLINT
2024-09-09 23:36:09 +02:00
std :: string chat_template = "" ; // NOLINT
2025-12-10 22:19:42 +01:00
bool use_jinja = true ; // NOLINT
2024-06-30 20:27:13 +02:00
bool enable_chat_template = true ;
2026-03-17 16:16:43 +01:00
bool force_pure_content_parser = false ;
2025-10-08 22:18:41 +02:00
common_reasoning_format reasoning_format = COMMON_REASONING_FORMAT_DEEPSEEK ;
2026-03-11 10:26:12 +01:00
int enable_reasoning = - 1 ; // -1 = auto, 0 = disable, 1 = enable
2025-12-21 02:24:42 +01:00
bool prefill_assistant = true ; // if true, any trailing assistant message will be prefilled into the response
int sleep_idle_seconds = - 1 ; // if >0, server will sleep after this many seconds of idle time
2024-06-04 21:23:39 +03:00
std :: vector < std :: string > api_keys ;
2024-09-09 23:36:09 +02:00
std :: string ssl_file_key = "" ; // NOLINT
std :: string ssl_file_cert = "" ; // NOLINT
2024-06-04 21:23:39 +03:00
2025-06-29 20:02:53 +02:00
std :: map < std :: string , std :: string > default_template_kwargs ;
2026-05-16 02:02:40 +02:00
// UI configs
2026-05-23 17:08:22 -04:00
bool ui = true ;
2026-05-16 02:02:40 +02:00
bool ui_mcp_proxy = false ;
std :: string ui_config_json ;
2024-10-08 13:27:04 +02:00
// "advanced" endpoints are disabled by default for better security
2025-08-31 20:11:58 +03:00
bool endpoint_slots = true ;
2024-10-08 13:27:04 +02:00
bool endpoint_props = false ; // only control POST requests, not GET
2024-06-04 21:23:39 +03:00
bool endpoint_metrics = false ;
2026-03-27 10:07:11 +01:00
// enable built-in tools
std :: vector < std :: string > server_tools ;
2025-12-01 19:41:04 +01:00
// router server configs
2026-06-18 12:45:23 +02:00
std :: string models_dir = "" ; // directory containing models for the router server
std :: string models_preset = "" ; // directory containing model presets for the router server
int models_max = 4 ; // maximum number of models to load simultaneously
bool models_autoload = true ; // automatically load models when requested via the router server
std :: string models_preset_hf = "" ; // show a warning about remote presets on router loaded (if not empty)
2025-12-01 19:41:04 +01:00
2024-06-04 21:23:39 +03:00
bool log_json = false ;
std :: string slot_save_path ;
2025-12-02 22:49:20 +01:00
std :: string media_path ; // path to directory for loading media files
2024-06-08 07:50:31 +00:00
2025-09-12 17:02:55 +03:00
float slot_prompt_similarity = 0.1f ;
2024-06-04 21:23:39 +03:00
// batched-bench params
2025-11-10 12:59:29 +02:00
bool is_pp_shared = false ;
bool is_tg_separate = false ;
2024-06-04 21:23:39 +03:00
std :: vector < int32_t > n_pp ;
std :: vector < int32_t > n_tg ;
std :: vector < int32_t > n_pl ;
// retrieval params
std :: vector < std :: string > context_files ; // context files to embed
int32_t chunk_size = 64 ; // chunk size for context embedding
std :: string chunk_separator = " \n " ; // chunk separator for context embedding
// passkey params
int32_t n_junk = 250 ; // number of times to repeat the junk text
int32_t i_pos = - 1 ; // position of the passkey in the junk text
2024-06-06 16:30:58 +03:00
// imatrix params
int32_t n_out_freq = 10 ; // output the imatrix every n_out_freq iterations
int32_t n_save_freq = 0 ; // save the imatrix every n_save_freq iterations
int32_t i_chunk = 0 ; // start processing from this chunk
2025-08-04 17:26:52 -04:00
int8_t imat_dat = 0 ; // whether the legacy imatrix.dat format should be output (gguf <= 0 < dat)
2024-06-06 16:30:58 +03:00
2025-07-22 13:33:37 +01:00
bool process_output = false ; // collect data for the output tensor
bool compute_ppl = true ; // whether to compute perplexity
bool show_statistics = false ; // show imatrix statistics per tensor
bool parse_special = false ; // whether to parse special tokens during imatrix tokenization
2024-06-15 18:53:40 +02:00
// cvector-generator params
2024-06-25 13:59:54 +02:00
int n_pca_batch = 100 ;
2024-06-15 18:53:40 +02:00
int n_pca_iterations = 1000 ;
2024-06-25 13:59:54 +02:00
dimre_method cvector_dimre_method = DIMRE_METHOD_PCA ;
2025-05-02 20:27:13 +02:00
std :: string cvector_positive_file = "tools/cvector-generator/positive.txt" ;
std :: string cvector_negative_file = "tools/cvector-generator/negative.txt" ;
2024-06-28 12:53:43 +02:00
bool spm_infill = false ; // suffix/prefix/middle pattern for infill
2024-07-23 23:48:37 +02:00
2024-09-06 18:59:58 +03:00
// batched-bench params
bool batched_bench_output_jsonl = false ;
2025-03-10 12:34:13 +01:00
// common params
std :: string out_file ; // output filename for all example programs
2025-05-19 21:17:36 +02:00
// optional callback for model loading progress and cancellation:
// called with a progress value between 0.0 and 1.0.
// return false from callback to abort model loading or true to continue
llama_progress_callback load_progress_callback = NULL ;
void * load_progress_callback_user_data = NULL ;
2026-04-02 18:19:20 +02:00
bool no_alloc = false ; // Don't allocate model buffers
2023-03-10 20:40:58 +02:00
};
2024-09-15 20:46:12 +03:00
// call once at the start of a program if it uses libcommon
// initializes the logging system and prints info about the build
2024-10-10 22:57:42 +02:00
void common_init ();
2024-09-15 20:46:12 +03:00
2026-05-16 21:21:06 +02:00
void common_params_print_info ( const common_params & params , bool print_devices = true );
2024-10-10 22:57:42 +02:00
std :: string common_params_get_system_info ( const common_params & params );
2024-04-08 20:43:30 +08:00
2024-10-12 08:21:51 +03:00
bool parse_cpu_range ( const std :: string & range , bool ( & boolmask )[ GGML_MAX_N_THREADS ]);
bool parse_cpu_mask ( const std :: string & mask , bool ( & boolmask )[ GGML_MAX_N_THREADS ]);
2026-04-28 09:07:33 +03:00
void postprocess_cpu_params ( common_cpu_params & cpuparams , const common_cpu_params * role_model = nullptr );
2024-08-29 19:20:53 -04:00
bool set_process_priority ( enum ggml_sched_priority prio );
2023-12-05 15:05:51 +05:00
//
2024-02-11 13:43:31 +00:00
// String utils
2023-12-05 15:05:51 +05:00
//
2024-10-12 08:21:51 +03:00
#ifdef __GNUC__
2025-02-12 10:06:53 -04:00
# if defined(__MINGW32__) && !defined(__clang__)
# define LLAMA_COMMON_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
# else
# define LLAMA_COMMON_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
# endif
2024-10-12 08:21:51 +03:00
#else
2025-02-12 10:06:53 -04:00
# define LLAMA_COMMON_ATTRIBUTE_FORMAT(...)
2024-10-12 08:21:51 +03:00
#endif
LLAMA_COMMON_ATTRIBUTE_FORMAT ( 1 , 2 )
std :: string string_format ( const char * fmt , ...);
2024-04-29 16:58:41 +03:00
std :: string string_strip ( const std :: string & str );
2024-05-22 20:04:20 +03:00
std :: string string_get_sortable_timestamp ();
2026-05-25 07:56:18 +02:00
std :: string string_lcs ( std :: string_view a , std :: string_view b );
2024-06-04 21:23:39 +03:00
2025-01-22 09:51:44 +00:00
std :: string string_join ( const std :: vector < std :: string > & values , const std :: string & separator );
std :: vector < std :: string > string_split ( const std :: string & str , const std :: string & delimiter );
std :: string string_repeat ( const std :: string & str , size_t n );
2024-08-09 18:23:52 +03:00
void string_replace_all ( std :: string & s , const std :: string & search , const std :: string & replace );
2025-03-05 13:05:13 +00:00
std :: string regex_escape ( const std :: string & s );
2024-06-04 21:23:39 +03:00
template < class T >
static std :: vector < T > string_split ( const std :: string & str , char delim ) {
2024-10-25 17:57:54 +02:00
static_assert ( ! std :: is_same < T , std :: string >:: value , "Please use the specialized version for std::string" );
2024-06-04 21:23:39 +03:00
std :: vector < T > values ;
std :: istringstream str_stream ( str );
std :: string token ;
while ( std :: getline ( str_stream , token , delim )) {
T value ;
std :: istringstream token_stream ( token );
token_stream >> value ;
values . push_back ( value );
}
return values ;
}
2024-05-22 20:04:20 +03:00
2024-10-25 17:57:54 +02:00
template <>
2026-02-18 08:03:01 +01:00
inline std :: vector < std :: string > string_split < std :: string > ( const std :: string & str , char delim )
2024-10-25 17:57:54 +02:00
{
std :: vector < std :: string > parts ;
size_t begin_pos = 0 ;
2026-02-18 08:03:01 +01:00
size_t delim_pos = str . find ( delim );
while ( delim_pos != std :: string :: npos ) {
std :: string part = str . substr ( begin_pos , delim_pos - begin_pos );
2024-10-25 17:57:54 +02:00
parts . emplace_back ( part );
2026-02-18 08:03:01 +01:00
begin_pos = delim_pos + 1 ;
delim_pos = str . find ( delim , begin_pos );
2024-10-25 17:57:54 +02:00
}
2026-02-18 08:03:01 +01:00
parts . emplace_back ( str . substr ( begin_pos ));
2024-10-25 17:57:54 +02:00
return parts ;
}
2026-02-18 08:03:01 +01:00
// remove when moving to c++20
inline bool string_starts_with ( std :: string_view str , std :: string_view prefix ) {
return str . size () >= prefix . size () &&
str . compare ( 0 , prefix . size (), prefix ) == 0 ;
2024-12-13 18:34:25 +00:00
}
2026-04-23 15:03:28 +02:00
// remove when moving to c++20
inline bool string_starts_with ( std :: string_view str , char prefix ) {
return ! str . empty () && str . front () == prefix ;
}
2026-02-18 08:03:01 +01:00
// remove when moving to c++20
inline bool string_ends_with ( std :: string_view str , std :: string_view suffix ) {
return str . size () >= suffix . size () &&
str . compare ( str . size () - suffix . size (), suffix . size (), suffix ) == 0 ;
}
inline bool string_remove_suffix ( std :: string & str , std :: string_view suffix ) {
if ( string_ends_with ( str , suffix )) {
str . resize ( str . size () - suffix . size ());
return true ;
}
return false ;
}
inline size_t string_find_partial_stop ( std :: string_view str , std :: string_view stop ) {
if ( ! str . empty () && ! stop . empty ()) {
const size_t max_len = std :: min ( str . size (), stop . size ());
const char last_char = str . back ();
for ( size_t len = max_len ; len > 0 ; -- len ) {
if ( stop [ len - 1 ] == last_char ) {
if ( string_ends_with ( str , stop . substr ( 0 , len ))) {
return str . size () - len ;
}
}
}
}
return std :: string :: npos ;
}
2025-01-13 13:56:23 +01:00
2024-05-22 20:04:20 +03:00
bool string_parse_kv_override ( const char * data , std :: vector < llama_model_kv_override > & overrides );
void string_process_escapes ( std :: string & input );
2024-09-15 20:46:12 +03:00
std :: string string_from ( bool value );
std :: string string_from ( const std :: vector < int > & values );
std :: string string_from ( const struct llama_context * ctx , const std :: vector < llama_token > & tokens );
std :: string string_from ( const struct llama_context * ctx , const struct llama_batch & batch );
2026-03-28 02:33:04 +01:00
bool glob_match ( const std :: string & pattern , const std :: string & str );
2024-05-22 20:04:20 +03:00
//
// Filesystem utils
//
2025-12-02 22:49:20 +01:00
bool fs_validate_filename ( const std :: string & filename , bool allow_subdirs = false );
2024-05-22 20:04:20 +03:00
bool fs_create_directory_with_parents ( const std :: string & path );
2025-12-02 22:49:20 +01:00
bool fs_is_directory ( const std :: string & path );
2024-05-22 20:04:20 +03:00
std :: string fs_get_cache_directory ();
2024-06-08 20:21:08 +01:00
std :: string fs_get_cache_file ( const std :: string & filename );
2023-12-05 15:05:51 +05:00
2025-11-08 21:54:14 +01:00
struct common_file_info {
std :: string path ;
std :: string name ;
size_t size = 0 ; // in bytes
2025-12-01 19:41:04 +01:00
bool is_dir = false ;
2025-11-08 21:54:14 +01:00
};
2025-12-01 19:41:04 +01:00
std :: vector < common_file_info > fs_list ( const std :: string & path , bool include_directories );
2025-11-08 21:54:14 +01:00
2025-12-07 03:43:50 +01:00
//
// TTY utils
//
// Auto-detect if colors can be enabled based on terminal and environment
bool tty_can_use_colors ();
2023-05-02 22:39:51 +02:00
//
// Model utils
//
2025-12-14 10:11:13 +02:00
struct common_sampler ;
2025-01-03 10:18:53 +02:00
2025-12-14 10:11:13 +02:00
// note: defines the model, context, samplers, ets. lifetimes
struct common_init_result {
2026-05-19 09:46:34 +03:00
common_init_result ( common_params & params , bool model_only = false );
2025-12-14 10:11:13 +02:00
~ common_init_result ();
llama_model * model ();
llama_context * context ();
2026-01-04 21:22:16 +01:00
2025-12-14 10:11:13 +02:00
common_sampler * sampler ( llama_seq_id seq_id );
2026-01-04 21:22:16 +01:00
void reset_samplers ();
2025-12-14 10:11:13 +02:00
std :: vector < llama_adapter_lora_ptr > & lora ();
private :
struct impl ;
std :: unique_ptr < impl > pimpl ;
2024-08-06 00:14:10 +08:00
};
2025-12-14 10:11:13 +02:00
using common_init_result_ptr = std :: unique_ptr < common_init_result > ;
2026-05-19 09:46:34 +03:00
common_init_result_ptr common_init_from_params ( common_params & params , bool model_only = false );
2023-10-18 16:21:57 +03:00
2024-11-25 19:30:06 +01:00
struct llama_model_params common_model_params_to_llama ( common_params & params );
2024-10-10 22:57:42 +02:00
struct llama_context_params common_context_params_to_llama ( const common_params & params );
2026-04-28 09:07:33 +03:00
struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params ( const common_cpu_params & params );
2023-08-21 23:07:43 +03:00
2024-08-06 17:33:39 +02:00
// clear LoRA adapters from context, then apply new list of adapters
2025-01-12 11:32:42 +02:00
void common_set_adapter_lora ( struct llama_context * ctx , std :: vector < common_adapter_lora_info > & lora );
2024-08-06 17:33:39 +02:00
2026-04-20 08:42:37 +03:00
// model endpoint from env
std :: string common_get_model_endpoint ();
//
// Context utils
//
enum common_context_seq_rm_type {
2026-05-16 20:06:23 +08:00
COMMON_CONTEXT_SEQ_RM_TYPE_NO = 0 , // seq_rm not supported (e.g. no memory module)
COMMON_CONTEXT_SEQ_RM_TYPE_PART = 1 , // can seq_rm partial sequences
COMMON_CONTEXT_SEQ_RM_TYPE_FULL = 2 , // can seq_rm full sequences only
COMMON_CONTEXT_SEQ_RM_TYPE_RS = 3 , // can seq_rm partial sequences, bounded by n_rs_seq
2026-04-20 08:42:37 +03:00
};
// check if the llama_context can remove sequences
// note: clears the memory of the context
common_context_seq_rm_type common_context_can_seq_rm ( llama_context * ctx );
2026-05-16 20:06:23 +08:00
// aborts execution on failure
void common_context_seq_rm ( llama_context * ctx , llama_seq_id seq_id , llama_pos p0 , llama_pos p1 );
void common_context_seq_add ( llama_context * ctx , llama_seq_id seq_id , llama_pos p0 , llama_pos p1 , llama_pos delta );
void common_context_seq_cp ( llama_context * ctx , llama_seq_id seq_id_src , llama_seq_id seq_id_dst , llama_pos p0 , llama_pos p1 );
2025-04-11 20:01:56 +08:00
2024-11-25 09:58:41 +02:00
//
2023-10-18 16:21:57 +03:00
// Batch utils
2024-11-25 09:58:41 +02:00
//
2023-10-18 16:21:57 +03:00
2024-10-10 22:57:42 +02:00
void common_batch_clear ( struct llama_batch & batch );
2023-10-18 16:21:57 +03:00
2024-10-10 22:57:42 +02:00
void common_batch_add (
2023-10-18 16:21:57 +03:00
struct llama_batch & batch ,
llama_token id ,
llama_pos pos ,
const std :: vector < llama_seq_id > & seq_ids ,
bool logits );
2026-02-23 07:04:30 +01:00
// decodes a single batch of tokens for a prompt and manages session tokens
//
// Note: We save state before the last token so that we can replay it to ensure
// compatibility with all memory types. Recurrent/hybrid models cannot remove
// tokens from memory, so this approach works across all model architectures.
bool common_prompt_batch_decode (
struct llama_context * ctx ,
2026-06-02 15:44:15 +02:00
const std :: vector < llama_token > & all_tokens ,
int n_new ,
2026-02-23 07:04:30 +01:00
int & n_past ,
int n_batch ,
std :: string_view state_path ,
bool save_state );
// replays the last token after loading state to regenerate logits
// used after loading session state to ensure the sampling context has valid logits
bool common_replay_last_token ( struct llama_context * ctx , llama_token last_token , int32_t pos );
2023-08-21 23:07:43 +03:00
//
// Vocab utils
//
2023-08-27 14:19:19 +03:00
// tokenizes a string into a vector of tokens
// should work similar to Python's `tokenizer.encode`
2024-10-10 22:57:42 +02:00
std :: vector < llama_token > common_tokenize (
2023-09-28 21:42:38 +02:00
const struct llama_context * ctx ,
const std :: string & text ,
2024-04-09 13:44:08 -04:00
bool add_special ,
bool parse_special = false );
2023-09-28 21:42:38 +02:00
2024-10-10 22:57:42 +02:00
std :: vector < llama_token > common_tokenize (
2025-01-12 11:32:42 +02:00
const struct llama_vocab * vocab ,
2023-08-21 23:07:43 +03:00
const std :: string & text ,
2024-04-09 13:44:08 -04:00
bool add_special ,
bool parse_special = false );
2023-08-21 23:07:43 +03:00
2024-04-24 05:15:29 -05:00
// tokenizes a token into a piece, optionally renders special/control tokens
2023-08-27 14:19:19 +03:00
// should work similar to Python's `tokenizer.id_to_piece`
2024-10-10 22:57:42 +02:00
std :: string common_token_to_piece (
2023-08-21 23:07:43 +03:00
const struct llama_context * ctx ,
2024-04-24 05:15:29 -05:00
llama_token token ,
bool special = true );
2023-08-27 14:19:19 +03:00
2025-01-12 11:32:42 +02:00
std :: string common_token_to_piece (
const struct llama_vocab * vocab ,
llama_token token ,
bool special = true );
2023-08-27 14:19:19 +03:00
// detokenizes a vector of tokens into a string
// should work similar to Python's `tokenizer.decode`
2024-07-05 19:01:35 +02:00
// optionally renders special/control tokens
2024-10-10 22:57:42 +02:00
std :: string common_detokenize (
2025-01-12 11:32:42 +02:00
const struct llama_context * ctx ,
const std :: vector < llama_token > & tokens ,
bool special = true );
std :: string common_detokenize (
const struct llama_vocab * vocab ,
2024-07-05 19:01:35 +02:00
const std :: vector < llama_token > & tokens ,
bool special = true );
2023-08-28 17:59:39 +02:00
2024-03-09 21:27:58 +09:00
//
// Embedding utils
//
2026-03-05 08:50:21 +01:00
// TODO: replace embd_norm with an enum
2024-12-18 13:01:41 +02:00
void common_embd_normalize ( const float * inp , float * out , int n , int embd_norm );
2024-03-09 21:27:58 +09:00
2024-10-10 22:57:42 +02:00
float common_embd_similarity_cos ( const float * embd1 , const float * embd2 , int n );
2024-03-15 13:43:02 -07:00
//
// Control vector utils
//
2024-10-10 22:57:42 +02:00
struct common_control_vector_data {
2024-03-15 13:43:02 -07:00
int n_embd ;
// stores data for layers [1, n_layer] where n_layer = data.size() / n_embd
std :: vector < float > data ;
};
2024-10-10 22:57:42 +02:00
struct common_control_vector_load_info {
2024-03-15 13:43:02 -07:00
float strength ;
std :: string fname ;
};
// Load control vectors, scale each by strength, and add them together.
// On error, returns {-1, empty}
2024-10-10 22:57:42 +02:00
common_control_vector_data common_control_vector_load ( const std :: vector < common_control_vector_load_info > & load_infos );
2024-03-23 18:07:00 +01:00
//
// Split utils
//
2024-05-22 20:04:20 +03:00
2025-01-03 10:18:53 +02:00
namespace {
const char * const LLM_KV_SPLIT_NO = "split.no" ;
const char * const LLM_KV_SPLIT_COUNT = "split.count" ;
const char * const LLM_KV_SPLIT_TENSORS_COUNT = "split.tensors.count" ;
}
2025-05-12 14:44:49 +02:00
2025-09-16 16:17:08 +02:00
//
// MoE utils
//
2026-03-11 18:13:28 -05:00
const char * const LLM_FFN_EXPS_REGEX = " \\ .ffn_(up|down|gate|gate_up)_(ch|)exps" ;
2025-09-16 16:17:08 +02:00
2026-02-16 18:52:24 +03:00
inline std :: string llm_ffn_exps_block_regex ( int idx ) {
2025-09-16 16:17:08 +02:00
return string_format ( "blk \\ .%d%s" , idx , LLM_FFN_EXPS_REGEX );
}
2026-02-16 18:52:24 +03:00
inline llama_model_tensor_buft_override llm_ffn_exps_cpu_override () {
2025-09-16 16:17:08 +02:00
return { LLM_FFN_EXPS_REGEX , ggml_backend_cpu_buffer_type () };
}
2025-05-12 14:44:49 +02:00
//
// training utils
//
ggml_opt_dataset_t common_opt_dataset_init ( struct llama_context * ctx , const std :: vector < llama_token > & tokens , int64_t stride );
2025-08-14 03:03:57 -07:00
// "adamw" or "sgd" (case insensitive)
enum ggml_opt_optimizer_type common_opt_get_optimizer ( const char * );
2026-05-11 19:09:43 +03:00
//
// prompt utils
//
struct common_prompt_checkpoint {
int64_t n_tokens ;
llama_pos pos_min ;
llama_pos pos_max ;
std :: vector < uint8_t > data_tgt ;
std :: vector < uint8_t > data_dft ;
2026-06-19 12:08:50 +02:00
// (optional) speculative-decoding implementation state stashed with the checkpoint
// (e.g. eagle3's deferred-boundary g_embd row)
std :: vector < uint8_t > data_spec ;
2026-05-11 19:09:43 +03:00
size_t size () const ;
bool empty () const ;
void clear ();
void update_pos (
int64_t n_tokens ,
llama_pos pos_min ,
llama_pos pos_max );
void update_tgt (
llama_context * ctx ,
llama_seq_id seq_id ,
llama_state_seq_flags flags );
void update_dft (
llama_context * ctx ,
llama_seq_id seq_id ,
llama_state_seq_flags flags );
void load_tgt (
llama_context * ctx ,
llama_seq_id seq_id ,
llama_state_seq_flags flags ) const ;
void load_dft (
llama_context * ctx ,
llama_seq_id seq_id ,
llama_state_seq_flags flags ) const ;
2026-05-16 20:06:23 +08:00
void clear_tgt ();
void clear_dft ();
2026-05-11 19:09:43 +03:00
};