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