#pragma once
#include "llama.h"
#include "sampling.h"
#define LOG_NO_FILE_LINE_FUNCTION
#include "log.h"
#include <set>
#include <cmath>
#include <string>
#include <sstream>
#include <string_view>
#include <vector>
#include <random>
#include <thread>
#include <unordered_map>
#include <tuple>
#include <map>
#include <sstream>
#include <variant>
#ifdef _WIN32
#define DIRECTORY_SEPARATOR '\\'
#else
#define DIRECTORY_SEPARATOR '/'
#endif
#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)
#define print_build_info() do { \
fprintf(stderr, "%s: build = %d (%s)\n", __func__, LLAMA_BUILD_NUMBER, LLAMA_COMMIT); \
fprintf(stderr, "%s: built with %s for %s\n", __func__, LLAMA_COMPILER, LLAMA_BUILD_TARGET); \
} while(0)
#define DEFAULT_MODEL_PATH "models/7B/ggml-model-f16.gguf"
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;
};
struct llama_lora_adapter_info {
std::string path;
float scale;
};
struct llama_lora_adapter_container : llama_lora_adapter_info {
struct llama_lora_adapter * adapter;
};
using llama_tokens = std::vector<llama_token>;
extern int LLAMA_BUILD_NUMBER;
extern char const * LLAMA_COMMIT;
extern char const * LLAMA_COMPILER;
extern char const * LLAMA_BUILD_TARGET;
struct llama_control_vector_load_info;
int32_t cpu_get_num_physical_cores();
int32_t cpu_get_num_math();
enum llama_example {
LLAMA_EXAMPLE_COMMON,
LLAMA_EXAMPLE_SPECULATIVE,
LLAMA_EXAMPLE_MAIN,
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,
LLAMA_EXAMPLE_MTMD,
LLAMA_EXAMPLE_LOOKUP,
LLAMA_EXAMPLE_PARALLEL,
LLAMA_EXAMPLE_TTS,
LLAMA_EXAMPLE_DIFFUSION,
LLAMA_EXAMPLE_FINETUNE,
LLAMA_EXAMPLE_COUNT,
};
enum dimre_method {
DIMRE_METHOD_PCA,
DIMRE_METHOD_MEAN,
};
enum common_reasoning_format {
COMMON_REASONING_FORMAT_NONE,
COMMON_REASONING_FORMAT_AUTO,
COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY, COMMON_REASONING_FORMAT_DEEPSEEK, };
enum common_webui {
COMMON_WEBUI_NONE,
COMMON_WEBUI_AUTO,
COMMON_WEBUI_LLAMACPP,
};
enum common_checkpoint_eviction {
COMMON_CHECKPOINT_EVICTION_AUTO,
COMMON_CHECKPOINT_EVICTION_FIFO,
COMMON_CHECKPOINT_EVICTION_VARIANCE
};
common_webui common_webui_from_name(const std::string& format);
common_checkpoint_eviction common_checkpoint_eviction_from_name(const std::string & format);
struct thinking_tokens {
bool exclude = true;
std::string begin = "<think>";
std::string end = "</think>";
};
thinking_tokens thinking_tokens_from_string(const std::string& format);
enum common_speculative_type {
COMMON_SPECULATIVE_TYPE_NONE, COMMON_SPECULATIVE_TYPE_DRAFT, COMMON_SPECULATIVE_TYPE_DFLASH, COMMON_SPECULATIVE_TYPE_MTP, COMMON_SPECULATIVE_TYPE_EAGLE3, COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE, COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K, COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V, COMMON_SPECULATIVE_TYPE_NGRAM_MOD,
COMMON_SPECULATIVE_TYPE_NGRAM_CACHE, COMMON_SPECULATIVE_TYPE_SUFFIX, COMMON_SPECULATIVE_TYPE_COUNT };
std::string common_speculative_type_name_str();
enum common_speculative_type common_speculative_type_from_name(const std::string & name);
std::string common_speculative_type_to_str(enum common_speculative_type type);
bool common_speculative_type_is_self_spec(enum common_speculative_type type);
struct common_speculative_stage_params {
common_speculative_type type = COMMON_SPECULATIVE_TYPE_NONE;
int32_t n_max = -1;
int32_t n_min = -1;
float p_min = -1.0f;
int32_t mtp_heads = -1;
int32_t dflash_cross_ctx = -1;
uint16_t ngram_size_n = 0;
uint16_t ngram_size_m = 0;
uint16_t ngram_min_hits = 0;
int32_t suffix_min_match_len = -1;
int32_t suffix_max_depth = -1;
std::string suffix_corpus;
bool has_n_max_override() const { return n_max >= 0; }
bool has_n_min_override() const { return n_min >= 0; }
bool has_p_min_override() const { return p_min >= 0.0f; }
bool has_mtp_heads_override() const { return mtp_heads >= 0; }
bool has_dflash_cross_ctx_override() const { return dflash_cross_ctx >= 0; }
bool has_ngram_size_n_override() const { return ngram_size_n > 0; }
bool has_ngram_size_m_override() const { return ngram_size_m > 0; }
bool has_ngram_min_hits_override() const { return ngram_min_hits > 0; }
bool has_suffix_min_match_len_override() const { return suffix_min_match_len >= 0; }
bool has_suffix_max_depth_override() const { return suffix_max_depth >= 0; }
bool has_suffix_corpus_override() const { return !suffix_corpus.empty(); }
};
struct common_params_model {
std::string path = ""; std::string url = ""; std::string hf_repo = ""; std::string hf_file = ""; std::string docker_repo = ""; };
struct common_ngram_mod;
struct common_params_speculative {
common_speculative_type type = COMMON_SPECULATIVE_TYPE_NONE;
int recurrent_ckpt_mode = LLAMA_SPEC_CKPT_AUTO;
std::string devices;
std::string params;
int32_t n_threads = -1;
int32_t n_threads_batch = -1;
int32_t n_max = 16; int32_t n_min = 0; std::vector<common_speculative_stage_params> stages; int32_t mtp_heads = 1; int32_t dflash_cross_ctx = 512;
float p_split = 0.1f; float p_min = 0.75f;
uint16_t ngram_size_n = 12; uint16_t ngram_size_m = 48; uint16_t ngram_min_hits = 1;
std::shared_ptr<common_ngram_mod> ngram_mod;
int32_t suffix_min_match_len = 5; int32_t suffix_max_depth = 64; std::string suffix_corpus;
std::string lookup_cache_static; std::string lookup_cache_dynamic;
struct common_params_model mparams_dft;
llama_model * model_dft = nullptr;
llama_context_params cparams_dft;
int32_t n_ctx = 0; int32_t n_gpu_layers = -1;
std::string model = ""; std::vector<std::pair<std::string, std::string>> replacements; std::string cache_type_k = ""; std::string cache_type_v = "";
bool autotune = false;
bool has_dft() const {
return !model.empty() || !params.empty();
}
std::vector<common_speculative_stage_params> get_resolved_stages() const;
common_params_speculative with_stage_overrides(const common_speculative_stage_params & stage) const;
bool has_stage_chain() const;
bool has_stage_type(common_speculative_type stage_type) const;
void remove_stage_type(common_speculative_type stage_type);
bool has_composite_stage_chain() const;
bool needs_dft_model() const;
void clear_dft();
int32_t get_max_stage_n_max() const;
int32_t get_min_usable_stage_n_min() const;
};
bool common_speculative_validate_chain(const common_params_speculative & params, std::string * error = nullptr);
std::string common_speculative_stage_chain_to_str(const common_params_speculative & params);
struct gpt_params {
std::string devices;
uint32_t seed = LLAMA_DEFAULT_SEED;
int32_t n_threads = cpu_get_num_math();
int32_t n_threads_batch = -1; int32_t n_predict = -1; int32_t n_ctx = 0; int32_t n_batch = 2048; int32_t n_ubatch = 512; int32_t n_keep = 0; int32_t n_chunks = -1; int32_t n_parallel = 1; int32_t n_sequences = 1; float p_split = 0.1f; int32_t n_gpu_layers = -1; int32_t main_gpu = 0; int32_t max_gpu = 0; int32_t ncmoe = 0; int32_t fit_margin = 0; bool fit = false; int32_t worst_graph_tokens = 0; float tensor_split[128] = {0}; int32_t grp_attn_n = 1; int32_t grp_attn_w = 512; int32_t n_print = -1; float rope_freq_base = 0.0f; float rope_freq_scale = 0.0f; float yarn_ext_factor = -1.0f; float yarn_attn_factor = -1.0f; float yarn_beta_fast = -1.0f; float yarn_beta_slow = -1.0f; int32_t yarn_orig_ctx = 0; float defrag_thold = -1.0f; float ban_phrases_bias = -999.0f; int32_t max_extra_alloc_MiB = 256; int32_t nrep = 1;
ggml_backend_sched_eval_callback cb_eval = nullptr;
void * cb_eval_user_data = nullptr;
ggml_numa_strategy numa = GGML_NUMA_STRATEGY_DISABLED;
enum llama_split_mode split_mode = LLAMA_SPLIT_MODE_LAYER; enum llama_rope_scaling_type rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_UNSPECIFIED; enum llama_attention_type attention_type = LLAMA_ATTENTION_TYPE_UNSPECIFIED;
struct common_params_sampling sparams;
struct common_params_speculative speculative;
std::string model = ""; std::string model_alias = "unknown"; std::string model_url = ""; std::string hf_token = ""; std::string hf_repo = ""; std::string hf_file = ""; std::string prompt = "";
std::string prompt_file = ""; bool prompt_is_binary = false; std::string path_prompt_cache = ""; std::string input_prefix = ""; std::string input_suffix = ""; std::string logdir = ""; std::string lookup_cache_static = ""; std::string lookup_cache_dynamic = ""; std::string logits_file = ""; std::string rpc_servers = "";
std::string cuda_params = "";
std::vector<std::string> in_files; std::vector<std::string> antiprompt; std::vector<std::string> ban_phrases; int32_t banned_n = 1; size_t n_buffer = 0; bool can_ban_phrases = true;
std::vector<std::vector<std::tuple<
uint32_t ,uint32_t ,std::string ,float >>> allow_ruless;
std::vector<std::string> allow_pieces; std::vector<std::string> allow_kws; size_t allow_kw_delay;
std::vector<llama_model_kv_override> kv_overrides;
std::vector<llama_model_tensor_buft_override> tensor_buft_overrides;
std::vector<std::pair<int,int>> offload_policy;
std::vector<int> fit_margin_array;
bool lora_init_without_apply = false; std::vector<llama_lora_adapter_info> lora_adapters;
std::vector<llama_control_vector_load_info> control_vectors;
int32_t verbosity = 0;
int32_t control_vector_layer_start = -1; int32_t control_vector_layer_end = -1;
int32_t ppl_stride = 0; int32_t ppl_output_type = 0; bool hellaswag = false; size_t hellaswag_tasks = 400;
bool winogrande = false; size_t winogrande_tasks = 0;
bool multiple_choice = false; size_t multiple_choice_tasks = 0;
bool kl_divergence = false;
bool usage = false; bool use_color = false; bool special = false; bool interactive = false; bool interactive_first = false; bool conversation = false; bool prompt_cache_all = false; bool prompt_cache_ro = false; bool ctx_shift = true;
bool escape = true; bool multiline_input = false; bool simple_io = false; bool cont_batching = true; bool flash_attn = true; int mla_attn = 3; int attn_max_batch = 0; bool fused_moe_up_gate = true; bool fused_up_gate = true; bool fused_mmad = true; bool grouped_expert_routing = false; bool rope_cache = false; bool graph_reuse = true; bool dsa = false; bool fused_idx_topk = false; int dsa_top_k = -1; int min_experts = -1;
float thresh_experts = 0;
bool input_prefix_bos = false; bool ignore_eos = false; bool logits_all = false; bool use_mmap = true; bool use_mlock = false; bool verbose_prompt = false; bool display_prompt = true; bool infill = false; bool dump_kv_cache = false; bool no_kv_offload = false; bool warmup = true; bool batch_warmup = false; bool check_tensors = false; bool repack_tensors = false; bool use_thp = false; bool validate_quants = false; bool only_active_exps = true; bool merge_qkv = false; bool merge_up_gate_exps= false; bool defer_experts = false; bool prefetch_experts = false; int prefetch_experts_threads = 0; bool k_cache_hadamard = false; bool v_cache_hadamard = false; bool split_mode_graph_scheduling = false; bool scheduler_async = false; int fused_delta_net = 0; bool has_mtp = false;
std::string cache_type_k = "f16"; std::string cache_type_v = "f16"; std::string indexer_cache_type_k = "f16";
std::string reduce_type = "f16";
std::string graph_attn_precision = "f16";
std::string type_k_first = "f16";
std::string type_k_last = "f16";
std::string type_v_first = "f16";
std::string type_v_last = "f16";
int32_t n_k_first = -1;
int32_t n_k_last = -1;
int32_t n_v_first = -1;
int32_t n_v_last = -1;
std::string extra_output_type = "";
common_params_model mmproj;
bool mmproj_use_gpu = true; bool no_mmproj = false; std::vector<std::string> image; int image_min_tokens = -1;
int image_max_tokens = -1;
std::string mtmd_kq_type = "f32";
int32_t n_threads_mtmd = -1;
bool embedding = false; int32_t embd_normalize = 2; std::string embd_out = ""; std::string embd_sep = "\n";
int32_t port = 8080; int32_t timeout_read = 600; int32_t timeout_write = timeout_read; int32_t n_threads_http = -1; bool send_done = false;
std::string hostname = "127.0.0.1";
std::string public_path = "";
std::string chat_template = "";
bool use_jinja = false; bool use_peg = false;
std::string system_prompt = "";
bool enable_chat_template = true;
bool force_pure_content_parser = false;
bool parallel_tool_calls = false;
common_reasoning_format reasoning_format = COMMON_REASONING_FORMAT_DEEPSEEK;
int enable_reasoning = -1; int reasoning_budget = -1;
std::string reasoning_budget_message; std::map<std::string, std::string> default_template_kwargs;
thinking_tokens think_tokens;
bool prefill_assistant = true;
bool dry_run = false;
std::vector<std::string> api_keys;
std::string ssl_file_key = "";
std::string ssl_file_cert = "";
common_webui webui = COMMON_WEBUI_AUTO;
bool webui_mcp_proxy = false;
bool endpoint_slots = true;
bool endpoint_props = false; bool endpoint_metrics = false;
bool log_json = false;
std::string slot_save_path;
std::string sql_save_file;
std::string sqlite_zstd_ext_file;
float slot_prompt_similarity = 0.1f;
bool do_checkpoint = false; int32_t ctx_checkpoints_n = 32; int32_t ctx_checkpoints_interval = 512; int32_t ctx_checkpoints_tolerance = 5; common_checkpoint_eviction ctx_checkpoint_eviction = COMMON_CHECKPOINT_EVICTION_VARIANCE;
int32_t cache_ram_mib = 8192; int32_t cache_ram_n_min = 0; float cache_ram_similarity = 0.5f;
bool is_pp_shared = false;
std::vector<int32_t> n_pp;
std::vector<int32_t> n_tg;
std::vector<int32_t> n_pl;
std::vector<std::string> context_files;
int32_t chunk_size = 64;
std::string chunk_separator = "\n";
int32_t n_junk = 250; int32_t i_pos = -1;
std::string out_file = "imatrix.dat"; std::string out_file_draft = ""; std::string output_tensor_name = "output.weight";
int32_t n_out_freq = 10; int32_t n_save_freq = 0; int32_t i_chunk = 0;
bool process_output = false; bool compute_ppl = true;
int n_pca_batch = 100;
int n_pca_iterations = 1000;
dimre_method cvector_dimre_method = DIMRE_METHOD_PCA;
std::string cvector_outfile = "control_vector.gguf";
std::string cvector_positive_file = "examples/cvector-generator/positive.txt";
std::string cvector_negative_file = "examples/cvector-generator/negative.txt";
bool spm_infill = false;
std::string lora_outfile = "ggml-lora-merged-f16.gguf";
bool sweep_bench_output_jsonl = false;
bool minilog = false;
};
std::pair<int, char**> parse_command_line(const std::string& commandLine);
void free_command_line(int argc, char** argv);
void gpt_params_handle_hf_token(gpt_params & params);
void gpt_params_parse_from_env(gpt_params & params);
void gpt_params_handle_model_default(gpt_params & params);
bool gpt_params_parse_ex (int argc, char ** argv, gpt_params & params);
bool gpt_params_parse (int argc, char ** argv, gpt_params & params);
bool gpt_params_find_arg (int argc, char ** argv, const std::string & arg, gpt_params & params, int & i, bool & invalid_param);
void gpt_params_print_usage(int argc, char ** argv, const gpt_params & params);
std::string gpt_params_get_system_info(const gpt_params & params);
struct common_remote_params {
std::vector<std::string> headers;
long timeout = 0; long max_size = 0; };
std::pair<long, std::vector<char>> common_remote_get_content(const std::string& url, const common_remote_params& params);
std::string string_join(const std::vector<std::string>& values, const std::string& separator);
std::string string_strip(const std::string & str);
std::string string_get_sortable_timestamp();
std::string string_lower(const std::string & str);
std::string string_repeat(const std::string & str, size_t n);
static bool string_starts_with(const std::string& str,
const std::string& prefix) { return str.rfind(prefix, 0) == 0;
}
std::vector<std::string> string_split(const std::string& str, const std::string& delimiter);
std::vector<std::string> string_split(const std::string& str, char delim);
void string_replace_all(std::string & s, const std::string & search, const std::string & replace);
bool string_ends_with(const std::string_view& str, const std::string_view& suffix);
size_t string_find_partial_stop(const std::string_view& str, const std::string_view& stop);
std::string regex_escape(const std::string& s);
template<class T>
static std::vector<T> string_split(const std::string & str, char delim) {
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;
}
template<>
std::vector<std::string> string_split<std::string>(const std::string& input, char separator)
{
std::vector<std::string> parts;
size_t begin_pos = 0;
size_t separator_pos = input.find(separator);
while (separator_pos != std::string::npos) {
std::string part = input.substr(begin_pos, separator_pos - begin_pos);
parts.emplace_back(part);
begin_pos = separator_pos + 1;
separator_pos = input.find(separator, begin_pos);
}
parts.emplace_back(input.substr(begin_pos, separator_pos - begin_pos));
return parts;
}
bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides);
void string_process_escapes(std::string & input);
std::string string_unescape(const std::string& str);
std::vector<std::string> string_extract(const std::string& str, const char c, std::vector<size_t>& posi);
bool string_is_found(const std::string& window, const std::string& str, size_t& pos);
bool fs_validate_filename(const std::string & filename);
bool fs_create_directory_with_parents(const std::string & path);
std::string fs_get_cache_directory();
std::string fs_get_cache_file(const std::string & filename);
struct llama_init_result {
struct llama_model * model = nullptr;
struct llama_context * context = nullptr;
std::vector<llama_lora_adapter_container> lora_adapters;
};
struct llama_init_result llama_init_from_gpt_params(gpt_params & params);
struct llama_model_params common_model_params_to_llama (const gpt_params & params);
struct llama_context_params common_context_params_to_llama(const gpt_params & params);
struct llama_model * llama_load_model_from_url(const char * model_url, const char * path_model, const char * hf_token, const struct llama_model_params & params);
struct llama_model * llama_load_model_from_hf(const char * repo, const char * file, const char * path_model, const char * hf_token, const struct llama_model_params & params);
void llama_lora_adapters_apply(struct llama_context * ctx, std::vector<llama_lora_adapter_container> & lora_adapters);
void common_batch_clear(struct llama_batch & batch);
void common_batch_add(
struct llama_batch & batch,
llama_token id,
llama_pos pos,
const std::vector<llama_seq_id> & seq_ids,
bool logits);
std::vector<llama_token> common_tokenize(
const struct llama_context * ctx,
const std::string & text,
bool add_special,
bool parse_special = false);
std::vector<llama_token> common_tokenize(
const struct llama_model * model,
const std::string & text,
bool add_special,
bool parse_special = false);
std::vector<llama_token> common_tokenize(
const struct llama_vocab* vocab,
const std::string& text,
bool add_special,
bool parse_special = false);
std::vector<llama_token> llama_tokenize(
const struct llama_vocab * vocab,
const std::string & text,
bool add_special,
bool parse_special = false);
std::string common_token_to_piece(
const struct llama_context * ctx,
llama_token token,
bool special = true);
std::string llama_token_to_piece(
const struct llama_model* model,
llama_token token,
bool special = true);
std::string common_detokenize(
const llama_context * ctx,
const std::vector<llama_token> & tokens,
bool special = true);
std::string common_detokenize(
const struct llama_vocab * vocab,
const std::vector<llama_token> & tokens,
bool special = true);
std::string common_token_to_piece(
const struct llama_vocab * vocab,
llama_token token,
bool special = true);
bool llama_should_add_bos_token(const llama_model * model);
void llama_kv_cache_dump_view(const llama_kv_cache_view & view, int row_size = 80);
void llama_kv_cache_dump_view_seqs(const llama_kv_cache_view & view, int row_size = 40);
void common_embd_normalize(const float * inp, float * out, int n, int embd_norm = 2);
float common_embd_similarity_cos(const float * embd1, const float * embd2, int n);
struct llama_control_vector_data {
int n_embd;
std::vector<float> data;
};
struct llama_control_vector_load_info {
float strength;
std::string fname;
};
llama_control_vector_data llama_control_vector_load(const std::vector<llama_control_vector_load_info> & load_infos);
static const char * const LLM_KV_SPLIT_NO = "split.no";
static const char * const LLM_KV_SPLIT_COUNT = "split.count";
static const char * const LLM_KV_SPLIT_TENSORS_COUNT = "split.tensors.count";
void yaml_dump_vector_float (FILE * stream, const char * prop_name, const std::vector<float> & data);
void yaml_dump_vector_int (FILE * stream, const char * prop_name, const std::vector<int> & data);
void yaml_dump_string_multiline(FILE * stream, const char * prop_name, const char * data);
void yaml_dump_non_result_info(
FILE * stream, const gpt_params & params, const llama_context * lctx,
const std::string & timestamp, const std::vector<int> & prompt_tokens, const char * model_desc);
std::string string_format(const char* fmt, ...);
std::tuple<uint32_t, uint32_t, std::string, float> argparse_allowlist_unicode_rule(std::string argstr);
void argparse_expiring_logit_bias(const std::string& content, common_params_sampling& sparams);