common.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. // Various helper functions and utilities
  2. #pragma once
  3. #include "llama.h"
  4. #include "build-info.h"
  5. #define LOG_NO_FILE_LINE_FUNCTION
  6. #include "log.h"
  7. #include <string>
  8. #include <vector>
  9. #include <random>
  10. #include <thread>
  11. #include <unordered_map>
  12. #include <tuple>
  13. #ifdef _WIN32
  14. #define DIRECTORY_SEPARATOR '\\'
  15. #else
  16. #define DIRECTORY_SEPARATOR '/'
  17. #endif // _WIN32
  18. #define die(msg) do { fputs("error: " msg "\n", stderr); exit(1); } while (0)
  19. #define die_fmt(fmt, ...) do { fprintf(stderr, "error: " fmt "\n", __VA_ARGS__); exit(1); } while (0)
  20. #define print_build_info() do { \
  21. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT); \
  22. fprintf(stderr, "%s: built with %s for %s\n", __func__, BUILD_COMPILER, BUILD_TARGET); \
  23. } while(0)
  24. //
  25. // CLI argument parsing
  26. //
  27. int32_t get_num_physical_cores();
  28. struct gpt_params {
  29. uint32_t seed = -1; // RNG seed
  30. int32_t n_threads = get_num_physical_cores();
  31. int32_t n_predict = -1; // new tokens to predict
  32. int32_t n_ctx = 512; // context size
  33. int32_t n_batch = 512; // batch size for prompt processing (must be >=32 to use BLAS)
  34. int32_t n_keep = 0; // number of tokens to keep from initial prompt
  35. int32_t n_draft = 16; // number of tokens to draft during speculative decoding
  36. int32_t n_chunks = -1; // max number of chunks to process (-1 = unlimited)
  37. int32_t n_gpu_layers = -1; // number of layers to store in VRAM (-1 - use default)
  38. int32_t n_gpu_layers_draft = -1; // number of layers to store in VRAM for the draft model (-1 - use default)
  39. int32_t main_gpu = 0; // the GPU that is used for scratch and small tensors
  40. float tensor_split[LLAMA_MAX_DEVICES] = {0}; // how split tensors should be distributed across GPUs
  41. int32_t n_probs = 0; // if greater than 0, output the probabilities of top n_probs tokens.
  42. int32_t n_beams = 0; // if non-zero then use beam search of given width.
  43. float rope_freq_base = 10000.0f; // RoPE base frequency
  44. float rope_freq_scale = 1.0f; // RoPE frequency scaling factor
  45. // sampling parameters
  46. int32_t top_k = 40; // <= 0 to use vocab size
  47. float top_p = 0.95f; // 1.0 = disabled
  48. float tfs_z = 1.00f; // 1.0 = disabled
  49. float typical_p = 1.00f; // 1.0 = disabled
  50. float temp = 0.80f; // 1.0 = disabled
  51. float repeat_penalty = 1.10f; // 1.0 = disabled
  52. int32_t repeat_last_n = 64; // last n tokens to penalize (0 = disable penalty, -1 = context size)
  53. float frequency_penalty = 0.00f; // 0.0 = disabled
  54. float presence_penalty = 0.00f; // 0.0 = disabled
  55. int32_t mirostat = 0; // 0 = disabled, 1 = mirostat, 2 = mirostat 2.0
  56. float mirostat_tau = 5.00f; // target entropy
  57. float mirostat_eta = 0.10f; // learning rate
  58. std::unordered_map<llama_token, float> logit_bias; // logit bias for specific tokens
  59. // Classifier-Free Guidance
  60. // https://arxiv.org/abs/2306.17806
  61. std::string cfg_negative_prompt; // string to help guidance
  62. float cfg_scale = 1.f; // How strong is guidance
  63. std::string model = "models/7B/ggml-model-f16.gguf"; // model path
  64. std::string model_draft = ""; // draft model for speculative decoding
  65. std::string model_alias = "unknown"; // model alias
  66. std::string prompt = "";
  67. std::string path_prompt_cache = ""; // path to file for saving/loading prompt eval state
  68. std::string input_prefix = ""; // string to prefix user inputs with
  69. std::string input_suffix = ""; // string to suffix user inputs with
  70. std::string grammar = ""; // optional BNF-like grammar to constrain sampling
  71. std::vector<std::string> antiprompt; // string upon seeing which more user input is prompted
  72. std::string logdir = ""; // directory in which to save YAML log files
  73. std::string lora_adapter = ""; // lora adapter path
  74. std::string lora_base = ""; // base model path for the lora adapter
  75. int ppl_stride = 0; // stride for perplexity calculations. If left at 0, the pre-existing approach will be used.
  76. int ppl_output_type = 0; // = 0 -> ppl output is as usual, = 1 -> ppl output is num_tokens, ppl, one per line
  77. // (which is more convenient to use for plotting)
  78. //
  79. bool hellaswag = false; // compute HellaSwag score over random tasks from datafile supplied in prompt
  80. size_t hellaswag_tasks = 400; // number of tasks to use when computing the HellaSwag score
  81. bool low_vram = false; // if true, reduce VRAM usage at the cost of performance
  82. bool mul_mat_q = true; // if true, use mul_mat_q kernels instead of cuBLAS
  83. bool memory_f16 = true; // use f16 instead of f32 for memory kv
  84. bool random_prompt = false; // do not randomize prompt if none provided
  85. bool use_color = false; // use color to distinguish generations and inputs
  86. bool interactive = false; // interactive mode
  87. bool prompt_cache_all = false; // save user input and generations to prompt cache
  88. bool prompt_cache_ro = false; // open the prompt cache read-only and do not update it
  89. bool embedding = false; // get only sentence embedding
  90. bool escape = false; // escape "\n", "\r", "\t", "\'", "\"", and "\\"
  91. bool interactive_first = false; // wait for user input immediately
  92. bool multiline_input = false; // reverse the usage of `\`
  93. bool simple_io = false; // improves compatibility with subprocesses and limited consoles
  94. bool input_prefix_bos = false; // prefix BOS to user inputs, preceding input_prefix
  95. bool ignore_eos = false; // ignore generated EOS tokens
  96. bool instruct = false; // instruction mode (used for Alpaca models)
  97. bool penalize_nl = true; // consider newlines as a repeatable token
  98. bool perplexity = false; // compute perplexity over the prompt
  99. bool use_mmap = true; // use mmap for faster loads
  100. bool use_mlock = false; // use mlock to keep model in memory
  101. bool numa = false; // attempt optimizations that help on some NUMA systems
  102. bool export_cgraph = false; // export the computation graph
  103. bool verbose_prompt = false; // print prompt tokens before generation
  104. };
  105. bool gpt_params_parse(int argc, char ** argv, gpt_params & params);
  106. void gpt_print_usage(int argc, char ** argv, const gpt_params & params);
  107. std::string gpt_random_prompt(std::mt19937 & rng);
  108. //
  109. // Model utils
  110. //
  111. std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_params(gpt_params & params);
  112. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params);
  113. //
  114. // Vocab utils
  115. //
  116. // tokenizes a string into a vector of tokens
  117. // should work similar to Python's `tokenizer.encode`
  118. std::vector<llama_token> llama_tokenize(
  119. struct llama_context * ctx,
  120. const std::string & text,
  121. bool add_bos);
  122. // tokenizes a token into a piece
  123. // should work similar to Python's `tokenizer.id_to_piece`
  124. std::string llama_token_to_piece(
  125. const struct llama_context * ctx,
  126. llama_token token);
  127. // TODO: these should be moved in llama.h C-style API under single `llama_detokenize` function
  128. // that takes into account the tokenizer type and decides how to handle the leading space
  129. //
  130. // detokenizes a vector of tokens into a string
  131. // should work similar to Python's `tokenizer.decode`
  132. // removes the leading space from the first non-BOS token
  133. std::string llama_detokenize_spm(
  134. llama_context * ctx,
  135. const std::vector<llama_token> & tokens);
  136. // detokenizes a vector of tokens into a string
  137. // should work similar to Python's `tokenizer.decode`
  138. std::string llama_detokenize_bpe(
  139. llama_context * ctx,
  140. const std::vector<llama_token> & tokens);
  141. //
  142. // Sampling utils
  143. //
  144. // this is a common sampling function used across the examples for convenience
  145. // it can serve as a starting point for implementing your own sampling function
  146. //
  147. // required:
  148. // - ctx: context to use for sampling
  149. // - params: sampling parameters
  150. //
  151. // optional:
  152. // - ctx_guidance: context to use for classifier-free guidance, ignore if NULL
  153. // - grammar: grammar to use for sampling, ignore if NULL
  154. // - last_tokens: needed for repetition penalty, ignore if empty
  155. // - idx: sample from llama_get_logits(ctx) + idx * n_vocab
  156. //
  157. // returns:
  158. // - token: sampled token
  159. // - candidates: vector of candidate tokens
  160. //
  161. llama_token llama_sample_token(
  162. struct llama_context * ctx,
  163. struct llama_context * ctx_guidance,
  164. struct llama_grammar * grammar,
  165. const struct gpt_params & params,
  166. const std::vector<llama_token> & last_tokens,
  167. std::vector<llama_token_data> & candidates,
  168. int idx = 0);
  169. //
  170. // YAML utils
  171. //
  172. bool create_directory_with_parents(const std::string & path);
  173. void dump_vector_float_yaml(FILE * stream, const char * prop_name, const std::vector<float> & data);
  174. void dump_vector_int_yaml(FILE * stream, const char * prop_name, const std::vector<int> & data);
  175. void dump_string_yaml_multiline(FILE * stream, const char * prop_name, const char * data);
  176. std::string get_sortable_timestamp();
  177. void dump_non_result_info_yaml(
  178. FILE * stream, const gpt_params & params, const llama_context * lctx,
  179. const std::string & timestamp, const std::vector<int> & prompt_tokens, const char * model_desc);