llama.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. /**
  2. * llama.cpp - git 5bf2a2771886ee86137e01dbc7492f78fb392066
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023 Georgi Gerganov
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #ifndef LLAMA_H
  27. #define LLAMA_H
  28. #include "ggml.h"
  29. #ifdef GGML_USE_CUBLAS
  30. #include "ggml-cuda.h"
  31. #define LLAMA_MAX_DEVICES GGML_CUDA_MAX_DEVICES
  32. #else
  33. #define LLAMA_MAX_DEVICES 1
  34. #endif // GGML_USE_CUBLAS
  35. #include <stddef.h>
  36. #include <stdint.h>
  37. #include <stdbool.h>
  38. #ifdef LLAMA_SHARED
  39. # if defined(_WIN32) && !defined(__MINGW32__)
  40. # ifdef LLAMA_BUILD
  41. # define LLAMA_API __declspec(dllexport)
  42. # else
  43. # define LLAMA_API __declspec(dllimport)
  44. # endif
  45. # else
  46. # define LLAMA_API __attribute__ ((visibility ("default")))
  47. # endif
  48. #else
  49. # define LLAMA_API
  50. #endif
  51. #ifdef __GNUC__
  52. # define DEPRECATED(func, hint) func __attribute__((deprecated(hint)))
  53. #elif defined(_MSC_VER)
  54. # define DEPRECATED(func, hint) __declspec(deprecated(hint)) func
  55. #else
  56. # define DEPRECATED(func, hint) func
  57. #endif
  58. #define LLAMA_FILE_MAGIC_GGJT 0x67676a74u // 'ggjt'
  59. #define LLAMA_FILE_MAGIC_GGLA 0x67676c61u // 'ggla'
  60. #define LLAMA_FILE_MAGIC_GGMF 0x67676d66u // 'ggmf'
  61. #define LLAMA_FILE_MAGIC_GGML 0x67676d6cu // 'ggml'
  62. #define LLAMA_FILE_MAGIC_GGSN 0x6767736eu // 'ggsn'
  63. #define LLAMA_FILE_VERSION 3
  64. #define LLAMA_FILE_MAGIC LLAMA_FILE_MAGIC_GGJT
  65. #define LLAMA_FILE_MAGIC_UNVERSIONED LLAMA_FILE_MAGIC_GGML
  66. #define LLAMA_SESSION_MAGIC LLAMA_FILE_MAGIC_GGSN
  67. #define LLAMA_SESSION_VERSION 1
  68. #define LLAMA_DEFAULT_SEED 0xFFFFFFFF
  69. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL)
  70. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  71. #define LLAMA_SUPPORTS_GPU_OFFLOAD
  72. #endif
  73. #ifdef __cplusplus
  74. extern "C" {
  75. #endif
  76. //
  77. // C interface
  78. //
  79. // TODO: show sample usage
  80. //
  81. struct llama_model;
  82. struct llama_context;
  83. typedef int llama_token;
  84. typedef struct llama_token_data {
  85. llama_token id; // token id
  86. float logit; // log-odds of the token
  87. float p; // probability of the token
  88. } llama_token_data;
  89. typedef struct llama_token_data_array {
  90. llama_token_data * data;
  91. size_t size;
  92. bool sorted;
  93. } llama_token_data_array;
  94. typedef void (*llama_progress_callback)(float progress, void *ctx);
  95. struct llama_context_params {
  96. uint32_t seed; // RNG seed, -1 for random
  97. int32_t n_ctx; // text context
  98. int32_t n_batch; // prompt processing batch size
  99. int32_t n_gpu_layers; // number of layers to store in VRAM
  100. int32_t main_gpu; // the GPU that is used for scratch and small tensors
  101. float tensor_split[LLAMA_MAX_DEVICES]; // how to split layers across multiple GPUs
  102. // called with a progress value between 0 and 1, pass NULL to disable
  103. llama_progress_callback progress_callback;
  104. // context pointer passed to the progress callback
  105. void * progress_callback_user_data;
  106. // Keep the booleans together to avoid misalignment during copy-by-value.
  107. bool low_vram; // if true, reduce VRAM usage at the cost of performance
  108. bool f16_kv; // use fp16 for KV cache
  109. bool logits_all; // the llama_eval() call computes all logits, not just the last one
  110. bool vocab_only; // only load the vocabulary, no weights
  111. bool use_mmap; // use mmap if possible
  112. bool use_mlock; // force system to keep model in RAM
  113. bool embedding; // embedding mode only
  114. };
  115. // model file types
  116. enum llama_ftype {
  117. LLAMA_FTYPE_ALL_F32 = 0,
  118. LLAMA_FTYPE_MOSTLY_F16 = 1, // except 1d tensors
  119. LLAMA_FTYPE_MOSTLY_Q4_0 = 2, // except 1d tensors
  120. LLAMA_FTYPE_MOSTLY_Q4_1 = 3, // except 1d tensors
  121. LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16 = 4, // tok_embeddings.weight and output.weight are F16
  122. // LLAMA_FTYPE_MOSTLY_Q4_2 = 5, // support has been removed
  123. // LLAMA_FTYPE_MOSTLY_Q4_3 = 6, // support has been removed
  124. LLAMA_FTYPE_MOSTLY_Q8_0 = 7, // except 1d tensors
  125. LLAMA_FTYPE_MOSTLY_Q5_0 = 8, // except 1d tensors
  126. LLAMA_FTYPE_MOSTLY_Q5_1 = 9, // except 1d tensors
  127. LLAMA_FTYPE_MOSTLY_Q2_K = 10,// except 1d tensors
  128. LLAMA_FTYPE_MOSTLY_Q3_K_S = 11,// except 1d tensors
  129. LLAMA_FTYPE_MOSTLY_Q3_K_M = 12,// except 1d tensors
  130. LLAMA_FTYPE_MOSTLY_Q3_K_L = 13,// except 1d tensors
  131. LLAMA_FTYPE_MOSTLY_Q4_K_S = 14,// except 1d tensors
  132. LLAMA_FTYPE_MOSTLY_Q4_K_M = 15,// except 1d tensors
  133. LLAMA_FTYPE_MOSTLY_Q5_K_S = 16,// except 1d tensors
  134. LLAMA_FTYPE_MOSTLY_Q5_K_M = 17,// except 1d tensors
  135. LLAMA_FTYPE_MOSTLY_Q6_K = 18,// except 1d tensors
  136. };
  137. // model quantization parameters
  138. typedef struct llama_model_quantize_params {
  139. int nthread; // number of threads to use for quantizing, if <=0 will use std::thread::hardware_concurrency()
  140. enum llama_ftype ftype; // quantize to this llama_ftype
  141. bool allow_requantize; // allow quantizing non-f32/f16 tensors
  142. bool quantize_output_tensor; // quantize output.weight
  143. } llama_model_quantize_params;
  144. // performance timing information
  145. struct llama_timings {
  146. double t_start_ms;
  147. double t_end_ms;
  148. double t_load_ms;
  149. double t_sample_ms;
  150. double t_p_eval_ms;
  151. double t_eval_ms;
  152. int32_t n_sample;
  153. int32_t n_p_eval;
  154. int32_t n_eval;
  155. };
  156. LLAMA_API struct llama_context_params llama_context_default_params();
  157. LLAMA_API struct llama_model_quantize_params llama_model_quantize_default_params();
  158. LLAMA_API bool llama_mmap_supported();
  159. LLAMA_API bool llama_mlock_supported();
  160. // TODO: not great API - very likely to change
  161. // Initialize the llama + ggml backend
  162. // If numa is true, use NUMA optimizations
  163. // Call once at the start of the program
  164. LLAMA_API void llama_backend_init(bool numa);
  165. // Call once at the end of the program - currently only used for MPI
  166. LLAMA_API void llama_backend_free();
  167. LLAMA_API int64_t llama_time_us();
  168. LLAMA_API struct llama_model * llama_load_model_from_file(
  169. const char * path_model,
  170. struct llama_context_params params);
  171. LLAMA_API void llama_free_model(struct llama_model * model);
  172. LLAMA_API struct llama_context * llama_new_context_with_model(
  173. struct llama_model * model,
  174. struct llama_context_params params);
  175. // Various functions for loading a ggml llama model.
  176. // Allocate (almost) all memory needed for the model.
  177. // Return NULL on failure
  178. LLAMA_API DEPRECATED(struct llama_context * llama_init_from_file(
  179. const char * path_model,
  180. struct llama_context_params params),
  181. "please use llama_load_model_from_file combined with llama_new_context_with_model instead");
  182. // Frees all allocated memory
  183. LLAMA_API void llama_free(struct llama_context * ctx);
  184. // Returns 0 on success
  185. LLAMA_API int llama_model_quantize(
  186. const char * fname_inp,
  187. const char * fname_out,
  188. const llama_model_quantize_params * params);
  189. // Apply a LoRA adapter to a loaded model
  190. // path_base_model is the path to a higher quality model to use as a base for
  191. // the layers modified by the adapter. Can be NULL to use the current loaded model.
  192. // The model needs to be reloaded before applying a new adapter, otherwise the adapter
  193. // will be applied on top of the previous one
  194. // Returns 0 on success
  195. LLAMA_API DEPRECATED(int llama_apply_lora_from_file(
  196. struct llama_context * ctx,
  197. const char * path_lora,
  198. const char * path_base_model,
  199. int n_threads),
  200. "please use llama_model_apply_lora_from_file instead");
  201. LLAMA_API int llama_model_apply_lora_from_file(
  202. const struct llama_model * model,
  203. const char * path_lora,
  204. const char * path_base_model,
  205. int n_threads);
  206. // Returns the number of tokens in the KV cache
  207. LLAMA_API int llama_get_kv_cache_token_count(const struct llama_context * ctx);
  208. // Sets the current rng seed.
  209. LLAMA_API void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed);
  210. // Returns the maximum size in bytes of the state (rng, logits, embedding
  211. // and kv_cache) - will often be smaller after compacting tokens
  212. LLAMA_API size_t llama_get_state_size(const struct llama_context * ctx);
  213. // Copies the state to the specified destination address.
  214. // Destination needs to have allocated enough memory.
  215. // Returns the number of bytes copied
  216. LLAMA_API size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst);
  217. // Set the state reading from the specified address
  218. // Returns the number of bytes read
  219. LLAMA_API size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src);
  220. // Save/load session file
  221. LLAMA_API bool llama_load_session_file(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out);
  222. LLAMA_API bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count);
  223. // Run the llama inference to obtain the logits and probabilities for the next token.
  224. // tokens + n_tokens is the provided batch of new tokens to process
  225. // n_past is the number of tokens to use from previous eval calls
  226. // Returns 0 on success
  227. LLAMA_API int llama_eval(
  228. struct llama_context * ctx,
  229. const llama_token * tokens,
  230. int n_tokens,
  231. int n_past,
  232. int n_threads);
  233. // Same as llama_eval, but use float matrix input directly.
  234. LLAMA_API int llama_eval_embd(
  235. struct llama_context * ctx,
  236. const float * embd,
  237. int n_tokens,
  238. int n_past,
  239. int n_threads);
  240. // Export a static computation graph for context of 511 and batch size of 1
  241. // NOTE: since this functionality is mostly for debugging and demonstration purposes, we hardcode these
  242. // parameters here to keep things simple
  243. // IMPORTANT: do not use for anything else other than debugging and testing!
  244. LLAMA_API int llama_eval_export(struct llama_context * ctx, const char * fname);
  245. // Convert the provided text into tokens.
  246. // The tokens pointer must be large enough to hold the resulting tokens.
  247. // Returns the number of tokens on success, no more than n_max_tokens
  248. // Returns a negative number on failure - the number of tokens that would have been returned
  249. // TODO: not sure if correct
  250. LLAMA_API int llama_tokenize(
  251. struct llama_context * ctx,
  252. const char * text,
  253. llama_token * tokens,
  254. int n_max_tokens,
  255. bool add_bos);
  256. LLAMA_API int llama_n_vocab(const struct llama_context * ctx);
  257. LLAMA_API int llama_n_ctx (const struct llama_context * ctx);
  258. LLAMA_API int llama_n_embd (const struct llama_context * ctx);
  259. // Get the vocabulary as output parameters.
  260. // Returns number of results.
  261. LLAMA_API int llama_get_vocab(
  262. const struct llama_context * ctx,
  263. const char * * strings,
  264. float * scores,
  265. int capacity);
  266. // Token logits obtained from the last call to llama_eval()
  267. // The logits for the last token are stored in the last row
  268. // Can be mutated in order to change the probabilities of the next token
  269. // Rows: n_tokens
  270. // Cols: n_vocab
  271. LLAMA_API float * llama_get_logits(struct llama_context * ctx);
  272. // Get the embeddings for the input
  273. // shape: [n_embd] (1-dimensional)
  274. LLAMA_API float * llama_get_embeddings(struct llama_context * ctx);
  275. // Token Id -> String. Uses the vocabulary in the provided context
  276. LLAMA_API const char * llama_token_to_str(const struct llama_context * ctx, llama_token token);
  277. // Special tokens
  278. LLAMA_API llama_token llama_token_bos(); // beginning-of-sentence
  279. LLAMA_API llama_token llama_token_eos(); // end-of-sentence
  280. LLAMA_API llama_token llama_token_nl(); // next-line
  281. // Sampling functions
  282. /// @details Repetition penalty described in CTRL academic paper https://arxiv.org/abs/1909.05858, with negative logit fix.
  283. LLAMA_API void llama_sample_repetition_penalty(struct llama_context * ctx, llama_token_data_array * candidates, const llama_token * last_tokens, size_t last_tokens_size, float penalty);
  284. /// @details Frequency and presence penalties described in OpenAI API https://platform.openai.com/docs/api-reference/parameter-details.
  285. LLAMA_API void llama_sample_frequency_and_presence_penalties(struct llama_context * ctx, llama_token_data_array * candidates, const llama_token * last_tokens, size_t last_tokens_size, float alpha_frequency, float alpha_presence);
  286. /// @details Apply classifier-free guidance to the logits as described in academic paper "Stay on topic with Classifier-Free Guidance" https://arxiv.org/abs/2306.17806
  287. /// @param candidates A vector of `llama_token_data` containing the candidate tokens, the logits must be directly extracted from the original generation context without being sorted.
  288. /// @params guidance_ctx A separate context from the same model. Other than a negative prompt at the beginning, it should have all generated and user input tokens copied from the main context.
  289. /// @params scale Guidance strength. 1.0f means no guidance. Higher values mean stronger guidance.
  290. /// @params smooth_factor Smooth factor between guidance logits and original logits. 1.0f means only use guidance logits. 0.0f means only original logits.
  291. LLAMA_API void llama_sample_classifier_free_guidance(
  292. struct llama_context * ctx,
  293. llama_token_data_array * candidates,
  294. struct llama_context * guidance_ctx,
  295. float scale,
  296. float smooth_factor);
  297. /// @details Sorts candidate tokens by their logits in descending order and calculate probabilities based on logits.
  298. LLAMA_API void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates);
  299. /// @details Top-K sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
  300. LLAMA_API void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep);
  301. /// @details Nucleus sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
  302. LLAMA_API void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep);
  303. /// @details Tail Free Sampling described in https://www.trentonbricken.com/Tail-Free-Sampling/.
  304. LLAMA_API void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep);
  305. /// @details Locally Typical Sampling implementation described in the paper https://arxiv.org/abs/2202.00666.
  306. LLAMA_API void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep);
  307. LLAMA_API void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates, float temp);
  308. /// @details Mirostat 1.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
  309. /// @param candidates A vector of `llama_token_data` containing the candidate tokens, their probabilities (p), and log-odds (logit) for the current position in the generated text.
  310. /// @param tau The target cross-entropy (or surprise) value you want to achieve for the generated text. A higher value corresponds to more surprising or less predictable text, while a lower value corresponds to less surprising or more predictable text.
  311. /// @param eta The learning rate used to update `mu` based on the error between the target and observed surprisal of the sampled word. A larger learning rate will cause `mu` to be updated more quickly, while a smaller learning rate will result in slower updates.
  312. /// @param m The number of tokens considered in the estimation of `s_hat`. This is an arbitrary value that is used to calculate `s_hat`, which in turn helps to calculate the value of `k`. In the paper, they use `m = 100`, but you can experiment with different values to see how it affects the performance of the algorithm.
  313. /// @param mu Maximum cross-entropy. This value is initialized to be twice the target cross-entropy (`2 * tau`) and is updated in the algorithm based on the error between the target and observed surprisal.
  314. LLAMA_API llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu);
  315. /// @details Mirostat 2.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
  316. /// @param candidates A vector of `llama_token_data` containing the candidate tokens, their probabilities (p), and log-odds (logit) for the current position in the generated text.
  317. /// @param tau The target cross-entropy (or surprise) value you want to achieve for the generated text. A higher value corresponds to more surprising or less predictable text, while a lower value corresponds to less surprising or more predictable text.
  318. /// @param eta The learning rate used to update `mu` based on the error between the target and observed surprisal of the sampled word. A larger learning rate will cause `mu` to be updated more quickly, while a smaller learning rate will result in slower updates.
  319. /// @param mu Maximum cross-entropy. This value is initialized to be twice the target cross-entropy (`2 * tau`) and is updated in the algorithm based on the error between the target and observed surprisal.
  320. LLAMA_API llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu);
  321. /// @details Selects the token with the highest probability.
  322. LLAMA_API llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates);
  323. /// @details Randomly selects a token from the candidates based on their probabilities.
  324. LLAMA_API llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates);
  325. // Performance information
  326. LLAMA_API struct llama_timings llama_get_timings(struct llama_context * ctx);
  327. LLAMA_API void llama_print_timings(struct llama_context * ctx);
  328. LLAMA_API void llama_reset_timings(struct llama_context * ctx);
  329. // Print system information
  330. LLAMA_API const char * llama_print_system_info(void);
  331. #ifdef __cplusplus
  332. }
  333. #endif
  334. // Internal API to be implemented by llama.cpp and used by tests/benchmarks only
  335. #ifdef LLAMA_API_INTERNAL
  336. #include <vector>
  337. #include <string>
  338. struct ggml_tensor;
  339. const std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx);
  340. #endif
  341. #endif // LLAMA_H