llama.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. #ifndef LLAMA_H
  2. #define LLAMA_H
  3. #include <stddef.h>
  4. #include <stdint.h>
  5. #include <stdbool.h>
  6. #ifdef LLAMA_SHARED
  7. # if defined(_WIN32) && !defined(__MINGW32__)
  8. # ifdef LLAMA_BUILD
  9. # define LLAMA_API __declspec(dllexport)
  10. # else
  11. # define LLAMA_API __declspec(dllimport)
  12. # endif
  13. # else
  14. # define LLAMA_API __attribute__ ((visibility ("default")))
  15. # endif
  16. #else
  17. # define LLAMA_API
  18. #endif
  19. #define LLAMA_FILE_VERSION 1
  20. #define LLAMA_FILE_MAGIC 0x67676a74 // 'ggjt' in hex
  21. #define LLAMA_FILE_MAGIC_UNVERSIONED 0x67676d6c // pre-versioned files
  22. #ifdef __cplusplus
  23. extern "C" {
  24. #endif
  25. //
  26. // C interface
  27. //
  28. // TODO: show sample usage
  29. //
  30. struct llama_context;
  31. typedef int llama_token;
  32. typedef struct llama_token_data {
  33. llama_token id; // token id
  34. float logit; // log-odds of the token
  35. float p; // probability of the token
  36. } llama_token_data;
  37. typedef struct llama_token_data_array {
  38. llama_token_data * data;
  39. size_t size;
  40. bool sorted;
  41. } llama_token_data_array;
  42. typedef void (*llama_progress_callback)(float progress, void *ctx);
  43. struct llama_context_params {
  44. int n_ctx; // text context
  45. int n_parts; // -1 for default
  46. int seed; // RNG seed, 0 for random
  47. bool f16_kv; // use fp16 for KV cache
  48. bool logits_all; // the llama_eval() call computes all logits, not just the last one
  49. bool vocab_only; // only load the vocabulary, no weights
  50. bool use_mmap; // use mmap if possible
  51. bool use_mlock; // force system to keep model in RAM
  52. bool embedding; // embedding mode only
  53. // called with a progress value between 0 and 1, pass NULL to disable
  54. llama_progress_callback progress_callback;
  55. // context pointer passed to the progress callback
  56. void * progress_callback_user_data;
  57. };
  58. // model file types
  59. enum llama_ftype {
  60. LLAMA_FTYPE_ALL_F32 = 0,
  61. LLAMA_FTYPE_MOSTLY_F16 = 1, // except 1d tensors
  62. LLAMA_FTYPE_MOSTLY_Q4_0 = 2, // except 1d tensors
  63. LLAMA_FTYPE_MOSTLY_Q4_1 = 3, // except 1d tensors
  64. LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16 = 4, // tok_embeddings.weight and output.weight are F16
  65. LLAMA_FTYPE_MOSTLY_Q4_2 = 5, // except 1d tensors
  66. // LLAMA_FTYPE_MOSTLY_Q4_3 (6) support has been removed
  67. LLAMA_FTYPE_MOSTLY_Q8_0 = 7, // except 1d tensors
  68. LLAMA_FTYPE_MOSTLY_Q5_0 = 8, // except 1d tensors
  69. LLAMA_FTYPE_MOSTLY_Q5_1 = 9, // except 1d tensors
  70. };
  71. LLAMA_API struct llama_context_params llama_context_default_params();
  72. LLAMA_API bool llama_mmap_supported();
  73. LLAMA_API bool llama_mlock_supported();
  74. // Various functions for loading a ggml llama model.
  75. // Allocate (almost) all memory needed for the model.
  76. // Return NULL on failure
  77. LLAMA_API struct llama_context * llama_init_from_file(
  78. const char * path_model,
  79. struct llama_context_params params);
  80. // Frees all allocated memory
  81. LLAMA_API void llama_free(struct llama_context * ctx);
  82. // TODO: not great API - very likely to change
  83. // Returns 0 on success
  84. // nthread - how many threads to use. If <=0, will use std::thread::hardware_concurrency(), else the number given
  85. LLAMA_API int llama_model_quantize(
  86. const char * fname_inp,
  87. const char * fname_out,
  88. enum llama_ftype ftype,
  89. int nthread);
  90. // Apply a LoRA adapter to a loaded model
  91. // path_base_model is the path to a higher quality model to use as a base for
  92. // the layers modified by the adapter. Can be NULL to use the current loaded model.
  93. // The model needs to be reloaded before applying a new adapter, otherwise the adapter
  94. // will be applied on top of the previous one
  95. // Returns 0 on success
  96. LLAMA_API int llama_apply_lora_from_file(
  97. struct llama_context * ctx,
  98. const char * path_lora,
  99. const char * path_base_model,
  100. int n_threads);
  101. // Returns the number of tokens in the KV cache
  102. LLAMA_API int llama_get_kv_cache_token_count(struct llama_context * ctx);
  103. // Sets the current rng seed.
  104. LLAMA_API void llama_set_rng_seed(struct llama_context * ctx, int seed);
  105. // Returns the size in bytes of the state (rng, logits, embedding and kv_cache)
  106. LLAMA_API size_t llama_get_state_size(struct llama_context * ctx);
  107. // Copies the state to the specified destination address.
  108. // Destination needs to have allocated enough memory.
  109. // Returns the number of bytes copied
  110. LLAMA_API size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dest);
  111. // Set the state reading from the specified address
  112. // Returns the number of bytes read
  113. LLAMA_API size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src);
  114. // Save/load session file
  115. LLAMA_API size_t 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);
  116. LLAMA_API size_t llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count);
  117. // Run the llama inference to obtain the logits and probabilities for the next token.
  118. // tokens + n_tokens is the provided batch of new tokens to process
  119. // n_past is the number of tokens to use from previous eval calls
  120. // Returns 0 on success
  121. LLAMA_API int llama_eval(
  122. struct llama_context * ctx,
  123. const llama_token * tokens,
  124. int n_tokens,
  125. int n_past,
  126. int n_threads);
  127. // Convert the provided text into tokens.
  128. // The tokens pointer must be large enough to hold the resulting tokens.
  129. // Returns the number of tokens on success, no more than n_max_tokens
  130. // Returns a negative number on failure - the number of tokens that would have been returned
  131. // TODO: not sure if correct
  132. LLAMA_API int llama_tokenize(
  133. struct llama_context * ctx,
  134. const char * text,
  135. llama_token * tokens,
  136. int n_max_tokens,
  137. bool add_bos);
  138. LLAMA_API int llama_n_vocab(struct llama_context * ctx);
  139. LLAMA_API int llama_n_ctx (struct llama_context * ctx);
  140. LLAMA_API int llama_n_embd (struct llama_context * ctx);
  141. // Token logits obtained from the last call to llama_eval()
  142. // The logits for the last token are stored in the last row
  143. // Can be mutated in order to change the probabilities of the next token
  144. // Rows: n_tokens
  145. // Cols: n_vocab
  146. LLAMA_API float * llama_get_logits(struct llama_context * ctx);
  147. // Get the embeddings for the input
  148. // shape: [n_embd] (1-dimensional)
  149. LLAMA_API float * llama_get_embeddings(struct llama_context * ctx);
  150. // Token Id -> String. Uses the vocabulary in the provided context
  151. LLAMA_API const char * llama_token_to_str(struct llama_context * ctx, llama_token token);
  152. // Special tokens
  153. LLAMA_API llama_token llama_token_bos();
  154. LLAMA_API llama_token llama_token_eos();
  155. LLAMA_API llama_token llama_token_nl();
  156. // Sampling functions
  157. /// @details Repetition penalty described in CTRL academic paper https://arxiv.org/abs/1909.05858, with negative logit fix.
  158. LLAMA_API void llama_sample_repetition_penalty(struct llama_context * ctx, llama_token_data_array * candidates, llama_token * last_tokens, size_t last_tokens_size, float penalty);
  159. /// @details Frequency and presence penalties described in OpenAI API https://platform.openai.com/docs/api-reference/parameter-details.
  160. LLAMA_API void llama_sample_frequency_and_presence_penalties(struct llama_context * ctx, llama_token_data_array * candidates, llama_token * last_tokens, size_t last_tokens_size, float alpha_frequency, float alpha_presence);
  161. /// @details Sorts candidate tokens by their logits in descending order and calculate probabilities based on logits.
  162. LLAMA_API void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates);
  163. /// @details Top-K sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
  164. LLAMA_API void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep = 1);
  165. /// @details Nucleus sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
  166. LLAMA_API void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep = 1);
  167. /// @details Tail Free Sampling described in https://www.trentonbricken.com/Tail-Free-Sampling/.
  168. LLAMA_API void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep = 1);
  169. /// @details Locally Typical Sampling implementation described in the paper https://arxiv.org/abs/2202.00666.
  170. LLAMA_API void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep = 1);
  171. LLAMA_API void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates, float temp);
  172. /// @details Mirostat 1.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
  173. /// @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.
  174. /// @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.
  175. /// @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.
  176. /// @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.
  177. /// @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.
  178. 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);
  179. /// @details Mirostat 2.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
  180. /// @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.
  181. /// @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.
  182. /// @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.
  183. /// @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.
  184. LLAMA_API llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu);
  185. /// @details Selects the token with the highest probability.
  186. LLAMA_API llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates);
  187. /// @details Randomly selects a token from the candidates based on their probabilities.
  188. LLAMA_API llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates);
  189. // Performance information
  190. LLAMA_API void llama_print_timings(struct llama_context * ctx);
  191. LLAMA_API void llama_reset_timings(struct llama_context * ctx);
  192. // Print system information
  193. LLAMA_API const char * llama_print_system_info(void);
  194. #ifdef __cplusplus
  195. }
  196. #endif
  197. // Internal API to be implemented by llama.cpp and used by tests/benchmarks only
  198. #ifdef LLAMA_API_INTERNAL
  199. #include <vector>
  200. #include <string>
  201. struct ggml_tensor;
  202. std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx);
  203. #endif
  204. #endif // LLAMA_H