common.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. // Various helper functions and utilities
  2. #pragma once
  3. #include "llama.h"
  4. #include "sampling.h"
  5. #define LOG_NO_FILE_LINE_FUNCTION
  6. #include "log.h"
  7. #include <cmath>
  8. #include <string>
  9. #include <vector>
  10. #include <random>
  11. #include <thread>
  12. #include <unordered_map>
  13. #include <tuple>
  14. #ifdef _WIN32
  15. #define DIRECTORY_SEPARATOR '\\'
  16. #else
  17. #define DIRECTORY_SEPARATOR '/'
  18. #endif // _WIN32
  19. #define die(msg) do { fputs("error: " msg "\n", stderr); exit(1); } while (0)
  20. #define die_fmt(fmt, ...) do { fprintf(stderr, "error: " fmt "\n", __VA_ARGS__); exit(1); } while (0)
  21. #define print_build_info() do { \
  22. fprintf(stderr, "%s: build = %d (%s)\n", __func__, LLAMA_BUILD_NUMBER, LLAMA_COMMIT); \
  23. fprintf(stderr, "%s: built with %s for %s\n", __func__, LLAMA_COMPILER, LLAMA_BUILD_TARGET); \
  24. } while(0)
  25. #define DEFAULT_MODEL_PATH "models/7B/ggml-model-f16.gguf"
  26. struct llama_lora_adapter_info {
  27. std::string path;
  28. float scale;
  29. };
  30. struct llama_lora_adapter_container : llama_lora_adapter_info {
  31. struct llama_lora_adapter * adapter;
  32. };
  33. // build info
  34. extern int LLAMA_BUILD_NUMBER;
  35. extern char const * LLAMA_COMMIT;
  36. extern char const * LLAMA_COMPILER;
  37. extern char const * LLAMA_BUILD_TARGET;
  38. struct llama_control_vector_load_info;
  39. //
  40. // CPU utils
  41. //
  42. int32_t cpu_get_num_physical_cores();
  43. int32_t cpu_get_num_math();
  44. //
  45. // CLI argument parsing
  46. //
  47. // dimensionality reduction methods, used by cvector-generator
  48. enum dimre_method {
  49. DIMRE_METHOD_PCA,
  50. DIMRE_METHOD_MEAN,
  51. };
  52. struct gpt_params {
  53. uint32_t seed = LLAMA_DEFAULT_SEED; // RNG seed
  54. int32_t n_threads = cpu_get_num_math();
  55. int32_t n_threads_draft = -1;
  56. int32_t n_threads_batch = -1; // number of threads to use for batch processing (-1 = use n_threads)
  57. int32_t n_threads_batch_draft = -1;
  58. int32_t n_predict = -1; // new tokens to predict
  59. int32_t n_ctx = 0; // context size
  60. int32_t n_batch = 2048; // logical batch size for prompt processing (must be >=32 to use BLAS)
  61. int32_t n_ubatch = 512; // physical batch size for prompt processing (must be >=32 to use BLAS)
  62. int32_t n_keep = 0; // number of tokens to keep from initial prompt
  63. int32_t n_draft = 5; // number of tokens to draft during speculative decoding
  64. int32_t n_chunks = -1; // max number of chunks to process (-1 = unlimited)
  65. int32_t n_parallel = 1; // number of parallel sequences to decode
  66. int32_t n_sequences = 1; // number of sequences to decode
  67. float p_split = 0.1f; // speculative decoding split probability
  68. int32_t n_gpu_layers = -1; // number of layers to store in VRAM (-1 - use default)
  69. int32_t n_gpu_layers_draft = -1; // number of layers to store in VRAM for the draft model (-1 - use default)
  70. int32_t main_gpu = 0; // the GPU that is used for scratch and small tensors
  71. float tensor_split[128] = {0}; // how split tensors should be distributed across GPUs
  72. int32_t grp_attn_n = 1; // group-attention factor
  73. int32_t grp_attn_w = 512; // group-attention width
  74. int32_t n_print = -1; // print token count every n tokens (-1 = disabled)
  75. float rope_freq_base = 0.0f; // RoPE base frequency
  76. float rope_freq_scale = 0.0f; // RoPE frequency scaling factor
  77. float yarn_ext_factor = -1.0f; // YaRN extrapolation mix factor
  78. float yarn_attn_factor = 1.0f; // YaRN magnitude scaling factor
  79. float yarn_beta_fast = 32.0f; // YaRN low correction dim
  80. float yarn_beta_slow = 1.0f; // YaRN high correction dim
  81. int32_t yarn_orig_ctx = 0; // YaRN original context length
  82. float defrag_thold = -1.0f; // KV cache defragmentation threshold
  83. ggml_backend_sched_eval_callback cb_eval = nullptr;
  84. void * cb_eval_user_data = nullptr;
  85. ggml_numa_strategy numa = GGML_NUMA_STRATEGY_DISABLED;
  86. enum llama_split_mode split_mode = LLAMA_SPLIT_MODE_LAYER; // how to split the model across GPUs
  87. enum llama_rope_scaling_type rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  88. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_UNSPECIFIED; // pooling type for embeddings
  89. enum llama_attention_type attention_type = LLAMA_ATTENTION_TYPE_UNSPECIFIED; // attention type for embeddings
  90. // // sampling parameters
  91. struct llama_sampling_params sparams;
  92. std::string model = ""; // model path
  93. std::string model_draft = ""; // draft model for speculative decoding
  94. std::string model_alias = "unknown"; // model alias
  95. std::string model_url = ""; // model url to download
  96. std::string hf_token = ""; // HF token
  97. std::string hf_repo = ""; // HF repo
  98. std::string hf_file = ""; // HF file
  99. std::string prompt = "";
  100. std::string prompt_file = ""; // store the external prompt file name
  101. std::string path_prompt_cache = ""; // path to file for saving/loading prompt eval state
  102. std::string input_prefix = ""; // string to prefix user inputs with
  103. std::string input_suffix = ""; // string to suffix user inputs with
  104. std::string logdir = ""; // directory in which to save YAML log files
  105. std::string lookup_cache_static = ""; // path of static ngram cache file for lookup decoding
  106. std::string lookup_cache_dynamic = ""; // path of dynamic ngram cache file for lookup decoding
  107. std::string logits_file = ""; // file for saving *all* logits
  108. std::string rpc_servers = ""; // comma separated list of RPC servers
  109. std::vector<std::string> in_files; // all input files
  110. std::vector<std::string> antiprompt; // strings upon which more user input is prompted (a.k.a. reverse prompts)
  111. std::vector<llama_model_kv_override> kv_overrides;
  112. 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_lora_adapter_apply)
  113. std::vector<llama_lora_adapter_info> lora_adapters; // lora adapter path with user defined scale
  114. std::vector<llama_control_vector_load_info> control_vectors; // control vector with user defined scale
  115. int32_t verbosity = 0;
  116. int32_t control_vector_layer_start = -1; // layer range for control vector
  117. int32_t control_vector_layer_end = -1; // layer range for control vector
  118. int32_t ppl_stride = 0; // stride for perplexity calculations. If left at 0, the pre-existing approach will be used.
  119. int32_t ppl_output_type = 0; // = 0 -> ppl output is as usual, = 1 -> ppl output is num_tokens, ppl, one per line
  120. // (which is more convenient to use for plotting)
  121. //
  122. bool hellaswag = false; // compute HellaSwag score over random tasks from datafile supplied in prompt
  123. size_t hellaswag_tasks = 400; // number of tasks to use when computing the HellaSwag score
  124. bool winogrande = false; // compute Winogrande score over random tasks from datafile supplied in prompt
  125. size_t winogrande_tasks = 0; // number of tasks to use when computing the Winogrande score. If 0, all tasks will be computed
  126. bool multiple_choice = false; // compute TruthfulQA score over random tasks from datafile supplied in prompt
  127. size_t multiple_choice_tasks = 0; // number of tasks to use when computing the TruthfulQA score. If 0, all tasks will be computed
  128. bool kl_divergence = false; // compute KL divergence
  129. bool usage = false; // print usage
  130. bool use_color = false; // use color to distinguish generations and inputs
  131. bool special = false; // enable special token output
  132. bool interactive = false; // interactive mode
  133. bool interactive_first = false; // wait for user input immediately
  134. bool conversation = false; // conversation mode (does not print special tokens and suffix/prefix)
  135. bool prompt_cache_all = false; // save user input and generations to prompt cache
  136. bool prompt_cache_ro = false; // open the prompt cache read-only and do not update it
  137. bool escape = true; // escape "\n", "\r", "\t", "\'", "\"", and "\\"
  138. bool multiline_input = false; // reverse the usage of `\`
  139. bool simple_io = false; // improves compatibility with subprocesses and limited consoles
  140. bool cont_batching = true; // insert new sequences for decoding on-the-fly
  141. bool flash_attn = false; // flash attention
  142. bool input_prefix_bos = false; // prefix BOS to user inputs, preceding input_prefix
  143. bool ignore_eos = false; // ignore generated EOS tokens
  144. bool logits_all = false; // return logits for all tokens in the batch
  145. bool use_mmap = true; // use mmap for faster loads
  146. bool use_mlock = false; // use mlock to keep model in memory
  147. bool verbose_prompt = false; // print prompt tokens before generation
  148. bool display_prompt = true; // print prompt before generation
  149. bool infill = false; // use infill mode
  150. bool dump_kv_cache = false; // dump the KV cache contents for debugging purposes
  151. bool no_kv_offload = false; // disable KV offloading
  152. bool warmup = true; // warmup run
  153. bool check_tensors = false; // validate tensor data
  154. std::string cache_type_k = "f16"; // KV cache data type for the K
  155. std::string cache_type_v = "f16"; // KV cache data type for the V
  156. // multimodal models (see examples/llava)
  157. std::string mmproj = ""; // path to multimodal projector
  158. std::vector<std::string> image; // path to image file(s)
  159. // embedding
  160. bool embedding = false; // get only sentence embedding
  161. int32_t embd_normalize = 2; // normalisation for embendings (-1=none, 0=max absolute int16, 1=taxicab, 2=euclidean, >2=p-norm)
  162. std::string embd_out = ""; // empty = default, "array" = [[],[]...], "json" = openai style, "json+" = same "json" + cosine similarity matrix
  163. std::string embd_sep = "\n"; // separator of embendings
  164. // server params
  165. int32_t port = 8080; // server listens on this network port
  166. int32_t timeout_read = 600; // http read timeout in seconds
  167. int32_t timeout_write = timeout_read; // http write timeout in seconds
  168. int32_t n_threads_http = -1; // number of threads to process HTTP requests
  169. std::string hostname = "127.0.0.1";
  170. std::string public_path = "";
  171. std::string chat_template = "";
  172. std::string system_prompt = "";
  173. bool enable_chat_template = true;
  174. std::vector<std::string> api_keys;
  175. std::string ssl_file_key = "";
  176. std::string ssl_file_cert = "";
  177. bool endpoint_slots = true;
  178. bool endpoint_metrics = false;
  179. bool log_json = false;
  180. std::string slot_save_path;
  181. float slot_prompt_similarity = 0.5f;
  182. // batched-bench params
  183. bool is_pp_shared = false;
  184. std::vector<int32_t> n_pp;
  185. std::vector<int32_t> n_tg;
  186. std::vector<int32_t> n_pl;
  187. // retrieval params
  188. std::vector<std::string> context_files; // context files to embed
  189. int32_t chunk_size = 64; // chunk size for context embedding
  190. std::string chunk_separator = "\n"; // chunk separator for context embedding
  191. // passkey params
  192. int32_t n_junk = 250; // number of times to repeat the junk text
  193. int32_t i_pos = -1; // position of the passkey in the junk text
  194. // imatrix params
  195. std::string out_file = "imatrix.dat"; // save the resulting imatrix to this file
  196. int32_t n_out_freq = 10; // output the imatrix every n_out_freq iterations
  197. int32_t n_save_freq = 0; // save the imatrix every n_save_freq iterations
  198. int32_t i_chunk = 0; // start processing from this chunk
  199. bool process_output = false; // collect data for the output tensor
  200. bool compute_ppl = true; // whether to compute perplexity
  201. // cvector-generator params
  202. int n_pca_batch = 100;
  203. int n_pca_iterations = 1000;
  204. dimre_method cvector_dimre_method = DIMRE_METHOD_PCA;
  205. std::string cvector_outfile = "control_vector.gguf";
  206. std::string cvector_positive_file = "examples/cvector-generator/positive.txt";
  207. std::string cvector_negative_file = "examples/cvector-generator/negative.txt";
  208. bool spm_infill = false; // suffix/prefix/middle pattern for infill
  209. std::string lora_outfile = "ggml-lora-merged-f16.gguf";
  210. };
  211. void gpt_params_handle_hf_token(gpt_params & params);
  212. void gpt_params_handle_model_default(gpt_params & params);
  213. bool gpt_params_parse_ex (int argc, char ** argv, gpt_params & params);
  214. bool gpt_params_parse (int argc, char ** argv, gpt_params & params);
  215. bool gpt_params_find_arg (int argc, char ** argv, const std::string & arg, gpt_params & params, int & i, bool & invalid_param);
  216. void gpt_params_print_usage(int argc, char ** argv, const gpt_params & params);
  217. std::string gpt_params_get_system_info(const gpt_params & params);
  218. //
  219. // String utils
  220. //
  221. std::vector<std::string> string_split(std::string input, char separator);
  222. std::string string_strip(const std::string & str);
  223. std::string string_get_sortable_timestamp();
  224. void string_replace_all(std::string & s, const std::string & search, const std::string & replace);
  225. template<class T>
  226. static std::vector<T> string_split(const std::string & str, char delim) {
  227. std::vector<T> values;
  228. std::istringstream str_stream(str);
  229. std::string token;
  230. while (std::getline(str_stream, token, delim)) {
  231. T value;
  232. std::istringstream token_stream(token);
  233. token_stream >> value;
  234. values.push_back(value);
  235. }
  236. return values;
  237. }
  238. bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides);
  239. void string_process_escapes(std::string & input);
  240. //
  241. // Filesystem utils
  242. //
  243. bool fs_validate_filename(const std::string & filename);
  244. bool fs_create_directory_with_parents(const std::string & path);
  245. std::string fs_get_cache_directory();
  246. std::string fs_get_cache_file(const std::string & filename);
  247. //
  248. // Model utils
  249. //
  250. struct llama_init_result {
  251. struct llama_model * model = nullptr;
  252. struct llama_context * context = nullptr;
  253. std::vector<llama_lora_adapter_container> lora_adapters;
  254. };
  255. struct llama_init_result llama_init_from_gpt_params(gpt_params & params);
  256. struct llama_model_params llama_model_params_from_gpt_params (const gpt_params & params);
  257. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params);
  258. 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);
  259. 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);
  260. // clear LoRA adapters from context, then apply new list of adapters
  261. void llama_lora_adapters_apply(struct llama_context * ctx, std::vector<llama_lora_adapter_container> & lora_adapters);
  262. // Batch utils
  263. void llama_batch_clear(struct llama_batch & batch);
  264. void llama_batch_add(
  265. struct llama_batch & batch,
  266. llama_token id,
  267. llama_pos pos,
  268. const std::vector<llama_seq_id> & seq_ids,
  269. bool logits);
  270. //
  271. // Vocab utils
  272. //
  273. // tokenizes a string into a vector of tokens
  274. // should work similar to Python's `tokenizer.encode`
  275. std::vector<llama_token> llama_tokenize(
  276. const struct llama_context * ctx,
  277. const std::string & text,
  278. bool add_special,
  279. bool parse_special = false);
  280. std::vector<llama_token> llama_tokenize(
  281. const struct llama_model * model,
  282. const std::string & text,
  283. bool add_special,
  284. bool parse_special = false);
  285. // tokenizes a token into a piece, optionally renders special/control tokens
  286. // should work similar to Python's `tokenizer.id_to_piece`
  287. std::string llama_token_to_piece(
  288. const struct llama_context * ctx,
  289. llama_token token,
  290. bool special = true);
  291. // detokenizes a vector of tokens into a string
  292. // should work similar to Python's `tokenizer.decode`
  293. // optionally renders special/control tokens
  294. std::string llama_detokenize(
  295. llama_context * ctx,
  296. const std::vector<llama_token> & tokens,
  297. bool special = true);
  298. // Uses the value from the model metadata if possible, otherwise
  299. // defaults to true when model type is SPM, otherwise false.
  300. bool llama_should_add_bos_token(const llama_model * model);
  301. //
  302. // Chat template utils
  303. //
  304. // same with llama_chat_message, but uses std::string
  305. struct llama_chat_msg {
  306. std::string role;
  307. std::string content;
  308. };
  309. // Check if the template supplied via "--chat-template" is supported or not. Returns true if it's valid
  310. bool llama_chat_verify_template(const std::string & tmpl);
  311. // CPP wrapper for llama_chat_apply_template
  312. // If the built-in template is not supported, we default to chatml
  313. // If the custom "tmpl" is not supported, we throw an error
  314. std::string llama_chat_apply_template(const struct llama_model * model,
  315. const std::string & tmpl,
  316. const std::vector<llama_chat_msg> & chat,
  317. bool add_ass);
  318. // Format single message, while taking into account the position of that message in chat history
  319. std::string llama_chat_format_single(const struct llama_model * model,
  320. const std::string & tmpl,
  321. const std::vector<llama_chat_msg> & past_msg,
  322. const llama_chat_msg & new_msg,
  323. bool add_ass);
  324. // Returns an example of formatted chat
  325. std::string llama_chat_format_example(const struct llama_model * model,
  326. const std::string & tmpl);
  327. //
  328. // KV cache utils
  329. //
  330. // Dump the KV cache view with the number of sequences per cell.
  331. void llama_kv_cache_dump_view(const llama_kv_cache_view & view, int row_size = 80);
  332. // Dump the KV cache view showing individual sequences in each cell (long output).
  333. void llama_kv_cache_dump_view_seqs(const llama_kv_cache_view & view, int row_size = 40);
  334. //
  335. // Embedding utils
  336. //
  337. void llama_embd_normalize(const float * inp, float * out, int n, int embd_norm = 2);
  338. float llama_embd_similarity_cos(const float * embd1, const float * embd2, int n);
  339. //
  340. // Control vector utils
  341. //
  342. struct llama_control_vector_data {
  343. int n_embd;
  344. // stores data for layers [1, n_layer] where n_layer = data.size() / n_embd
  345. std::vector<float> data;
  346. };
  347. struct llama_control_vector_load_info {
  348. float strength;
  349. std::string fname;
  350. };
  351. // Load control vectors, scale each by strength, and add them together.
  352. // On error, returns {-1, empty}
  353. llama_control_vector_data llama_control_vector_load(const std::vector<llama_control_vector_load_info> & load_infos);
  354. //
  355. // Split utils
  356. //
  357. static const char * const LLM_KV_SPLIT_NO = "split.no";
  358. static const char * const LLM_KV_SPLIT_COUNT = "split.count";
  359. static const char * const LLM_KV_SPLIT_TENSORS_COUNT = "split.tensors.count";
  360. //
  361. // YAML utils
  362. //
  363. void yaml_dump_vector_float (FILE * stream, const char * prop_name, const std::vector<float> & data);
  364. void yaml_dump_vector_int (FILE * stream, const char * prop_name, const std::vector<int> & data);
  365. void yaml_dump_string_multiline(FILE * stream, const char * prop_name, const char * data);
  366. void yaml_dump_non_result_info(
  367. FILE * stream, const gpt_params & params, const llama_context * lctx,
  368. const std::string & timestamp, const std::vector<int> & prompt_tokens, const char * model_desc);