llama.h 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. #ifndef LLAMA_H
  2. #define LLAMA_H
  3. #include "ggml.h"
  4. #include "ggml-backend.h"
  5. #include <stddef.h>
  6. #include <stdint.h>
  7. #include <stdio.h>
  8. #include <stdbool.h>
  9. #ifdef LLAMA_SHARED
  10. # if defined(_WIN32) && !defined(__MINGW32__)
  11. # ifdef LLAMA_BUILD
  12. # define LLAMA_API __declspec(dllexport)
  13. # else
  14. # define LLAMA_API __declspec(dllimport)
  15. # endif
  16. # else
  17. # define LLAMA_API __attribute__ ((visibility ("default")))
  18. # endif
  19. #else
  20. # define LLAMA_API
  21. #endif
  22. #ifdef __GNUC__
  23. # define DEPRECATED(func, hint) func __attribute__((deprecated(hint)))
  24. #elif defined(_MSC_VER)
  25. # define DEPRECATED(func, hint) __declspec(deprecated(hint)) func
  26. #else
  27. # define DEPRECATED(func, hint) func
  28. #endif
  29. #define LLAMA_DEFAULT_SEED 0xFFFFFFFF
  30. #define LLAMA_MAX_RNG_STATE (64*1024)
  31. #define LLAMA_FILE_MAGIC_GGLA 0x67676c61u // 'ggla'
  32. #define LLAMA_FILE_MAGIC_GGSN 0x6767736eu // 'ggsn'
  33. #define LLAMA_FILE_MAGIC_GGSQ 0x67677371u // 'ggsq'
  34. #define LLAMA_SESSION_MAGIC LLAMA_FILE_MAGIC_GGSN
  35. #define LLAMA_SESSION_VERSION 5
  36. #define LLAMA_STATE_SEQ_MAGIC LLAMA_FILE_MAGIC_GGSQ
  37. #define LLAMA_STATE_SEQ_VERSION 1
  38. #ifdef __cplusplus
  39. extern "C" {
  40. #endif
  41. //
  42. // C interface
  43. //
  44. // TODO: show sample usage
  45. //
  46. struct llama_model;
  47. struct llama_context;
  48. typedef int32_t llama_pos;
  49. typedef int32_t llama_token;
  50. typedef int32_t llama_seq_id;
  51. enum llama_vocab_type {
  52. LLAMA_VOCAB_TYPE_NONE = 0, // For models without vocab
  53. LLAMA_VOCAB_TYPE_SPM = 1, // LLaMA tokenizer based on byte-level BPE with byte fallback
  54. LLAMA_VOCAB_TYPE_BPE = 2, // GPT-2 tokenizer based on byte-level BPE
  55. LLAMA_VOCAB_TYPE_WPM = 3, // BERT tokenizer based on WordPiece
  56. };
  57. // note: these values should be synchronized with ggml_rope
  58. // TODO: maybe move this enum to ggml.h (ggml_rope_type)
  59. enum llama_rope_type {
  60. LLAMA_ROPE_TYPE_NONE = -1,
  61. LLAMA_ROPE_TYPE_NORM = 0,
  62. LLAMA_ROPE_TYPE_NEOX = 2,
  63. LLAMA_ROPE_TYPE_GLM = 4,
  64. };
  65. enum llama_token_type {
  66. LLAMA_TOKEN_TYPE_UNDEFINED = 0,
  67. LLAMA_TOKEN_TYPE_NORMAL = 1,
  68. LLAMA_TOKEN_TYPE_UNKNOWN = 2,
  69. LLAMA_TOKEN_TYPE_CONTROL = 3,
  70. LLAMA_TOKEN_TYPE_USER_DEFINED = 4,
  71. LLAMA_TOKEN_TYPE_UNUSED = 5,
  72. LLAMA_TOKEN_TYPE_BYTE = 6,
  73. };
  74. // model file types
  75. enum llama_ftype {
  76. LLAMA_FTYPE_ALL_F32 = 0,
  77. LLAMA_FTYPE_MOSTLY_F16 = 1, // except 1d tensors
  78. LLAMA_FTYPE_MOSTLY_Q4_0 = 2, // except 1d tensors
  79. LLAMA_FTYPE_MOSTLY_Q4_1 = 3, // except 1d tensors
  80. LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16 = 4, // tok_embeddings.weight and output.weight are F16
  81. // LLAMA_FTYPE_MOSTLY_Q4_2 = 5, // support has been removed
  82. // LLAMA_FTYPE_MOSTLY_Q4_3 = 6, // support has been removed
  83. LLAMA_FTYPE_MOSTLY_Q8_0 = 7, // except 1d tensors
  84. LLAMA_FTYPE_MOSTLY_Q5_0 = 8, // except 1d tensors
  85. LLAMA_FTYPE_MOSTLY_Q5_1 = 9, // except 1d tensors
  86. LLAMA_FTYPE_MOSTLY_Q2_K = 10, // except 1d tensors
  87. LLAMA_FTYPE_MOSTLY_Q3_K_S = 11, // except 1d tensors
  88. LLAMA_FTYPE_MOSTLY_Q3_K_M = 12, // except 1d tensors
  89. LLAMA_FTYPE_MOSTLY_Q3_K_L = 13, // except 1d tensors
  90. LLAMA_FTYPE_MOSTLY_Q4_K_S = 14, // except 1d tensors
  91. LLAMA_FTYPE_MOSTLY_Q4_K_M = 15, // except 1d tensors
  92. LLAMA_FTYPE_MOSTLY_Q5_K_S = 16, // except 1d tensors
  93. LLAMA_FTYPE_MOSTLY_Q5_K_M = 17, // except 1d tensors
  94. LLAMA_FTYPE_MOSTLY_Q6_K = 18, // except 1d tensors
  95. LLAMA_FTYPE_MOSTLY_IQ2_XXS = 19, // except 1d tensors
  96. LLAMA_FTYPE_MOSTLY_IQ2_XS = 20, // except 1d tensors
  97. LLAMA_FTYPE_MOSTLY_Q2_K_S = 21, // except 1d tensors
  98. LLAMA_FTYPE_MOSTLY_IQ3_XS = 22, // except 1d tensors
  99. LLAMA_FTYPE_MOSTLY_IQ3_XXS = 23, // except 1d tensors
  100. LLAMA_FTYPE_MOSTLY_IQ1_S = 24, // except 1d tensors
  101. LLAMA_FTYPE_MOSTLY_IQ4_NL = 25, // except 1d tensors
  102. LLAMA_FTYPE_MOSTLY_IQ3_S = 26, // except 1d tensors
  103. LLAMA_FTYPE_MOSTLY_IQ3_M = 27, // except 1d tensors
  104. LLAMA_FTYPE_MOSTLY_IQ2_S = 28, // except 1d tensors
  105. LLAMA_FTYPE_MOSTLY_IQ2_M = 29, // except 1d tensors
  106. LLAMA_FTYPE_MOSTLY_IQ4_XS = 30, // except 1d tensors
  107. LLAMA_FTYPE_MOSTLY_IQ1_M = 31, // except 1d tensors
  108. LLAMA_FTYPE_GUESSED = 1024, // not specified in the model file
  109. };
  110. enum llama_rope_scaling_type {
  111. LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED = -1,
  112. LLAMA_ROPE_SCALING_TYPE_NONE = 0,
  113. LLAMA_ROPE_SCALING_TYPE_LINEAR = 1,
  114. LLAMA_ROPE_SCALING_TYPE_YARN = 2,
  115. LLAMA_ROPE_SCALING_TYPE_MAX_VALUE = LLAMA_ROPE_SCALING_TYPE_YARN,
  116. };
  117. enum llama_pooling_type {
  118. LLAMA_POOLING_TYPE_UNSPECIFIED = -1,
  119. LLAMA_POOLING_TYPE_NONE = 0,
  120. LLAMA_POOLING_TYPE_MEAN = 1,
  121. LLAMA_POOLING_TYPE_CLS = 2,
  122. };
  123. enum llama_split_mode {
  124. LLAMA_SPLIT_MODE_NONE = 0, // single GPU
  125. LLAMA_SPLIT_MODE_LAYER = 1, // split layers and KV across GPUs
  126. LLAMA_SPLIT_MODE_ROW = 2, // split rows across GPUs
  127. };
  128. typedef struct llama_token_data {
  129. llama_token id; // token id
  130. float logit; // log-odds of the token
  131. float p; // probability of the token
  132. } llama_token_data;
  133. typedef struct llama_token_data_array {
  134. llama_token_data * data;
  135. size_t size;
  136. bool sorted;
  137. } llama_token_data_array;
  138. typedef bool (*llama_progress_callback)(float progress, void *ctx);
  139. // Input data for llama_decode
  140. // A llama_batch object can contain input about one or many sequences
  141. // The provided arrays (i.e. token, embd, pos, etc.) must have size of n_tokens
  142. //
  143. // - token : the token ids of the input (used when embd is NULL)
  144. // - embd : token embeddings (i.e. float vector of size n_embd) (used when token is NULL)
  145. // - pos : the positions of the respective token in the sequence
  146. // - seq_id : the sequence to which the respective token belongs
  147. // - logits : if zero, the logits (and/or the embeddings) for the respective token will not be output
  148. //
  149. typedef struct llama_batch {
  150. int32_t n_tokens;
  151. llama_token * token;
  152. float * embd;
  153. llama_pos * pos;
  154. int32_t * n_seq_id;
  155. llama_seq_id ** seq_id;
  156. int8_t * logits; // TODO: rename this to "output"
  157. // NOTE: helpers for smooth API transition - can be deprecated in the future
  158. // for future-proof code, use the above fields instead and ignore everything below
  159. //
  160. // pos[i] = all_pos_0 + i*all_pos_1
  161. //
  162. llama_pos all_pos_0; // used if pos == NULL
  163. llama_pos all_pos_1; // used if pos == NULL
  164. llama_seq_id all_seq_id; // used if seq_id == NULL
  165. } llama_batch;
  166. enum llama_model_kv_override_type {
  167. LLAMA_KV_OVERRIDE_TYPE_INT,
  168. LLAMA_KV_OVERRIDE_TYPE_FLOAT,
  169. LLAMA_KV_OVERRIDE_TYPE_BOOL,
  170. };
  171. struct llama_model_kv_override {
  172. char key[128];
  173. enum llama_model_kv_override_type tag;
  174. union {
  175. int64_t int_value;
  176. double float_value;
  177. bool bool_value;
  178. };
  179. };
  180. struct llama_model_params {
  181. int32_t n_gpu_layers; // number of layers to store in VRAM
  182. enum llama_split_mode split_mode; // how to split the model across multiple GPUs
  183. // main_gpu interpretation depends on split_mode:
  184. // LLAMA_SPLIT_NONE: the GPU that is used for the entire model
  185. // LLAMA_SPLIT_ROW: the GPU that is used for small tensors and intermediate results
  186. // LLAMA_SPLIT_LAYER: ignored
  187. int32_t main_gpu;
  188. // proportion of the model (layers or rows) to offload to each GPU, size: llama_max_devices()
  189. const float * tensor_split;
  190. // Called with a progress value between 0.0 and 1.0. Pass NULL to disable.
  191. // If the provided progress_callback returns true, model loading continues.
  192. // If it returns false, model loading is immediately aborted.
  193. llama_progress_callback progress_callback;
  194. // context pointer passed to the progress callback
  195. void * progress_callback_user_data;
  196. // override key-value pairs of the model meta data
  197. const struct llama_model_kv_override * kv_overrides;
  198. // Keep the booleans together to avoid misalignment during copy-by-value.
  199. bool vocab_only; // only load the vocabulary, no weights
  200. bool use_mmap; // use mmap if possible
  201. bool use_mlock; // force system to keep model in RAM
  202. };
  203. struct llama_context_params {
  204. uint32_t seed; // RNG seed, -1 for random
  205. uint32_t n_ctx; // text context, 0 = from model
  206. uint32_t n_batch; // logical maximum batch size that can be submitted to llama_decode
  207. uint32_t n_ubatch; // physical maximum batch size
  208. uint32_t n_seq_max; // max number of sequences (i.e. distinct states for recurrent models)
  209. uint32_t n_threads; // number of threads to use for generation
  210. uint32_t n_threads_batch; // number of threads to use for batch processing
  211. enum llama_rope_scaling_type rope_scaling_type; // RoPE scaling type, from `enum llama_rope_scaling_type`
  212. enum llama_pooling_type pooling_type; // whether to pool (sum) embedding results by sequence id
  213. // (ignored if no pooling layer)
  214. // ref: https://github.com/ggerganov/llama.cpp/pull/2054
  215. float rope_freq_base; // RoPE base frequency, 0 = from model
  216. float rope_freq_scale; // RoPE frequency scaling factor, 0 = from model
  217. float yarn_ext_factor; // YaRN extrapolation mix factor, negative = from model
  218. float yarn_attn_factor; // YaRN magnitude scaling factor
  219. float yarn_beta_fast; // YaRN low correction dim
  220. float yarn_beta_slow; // YaRN high correction dim
  221. uint32_t yarn_orig_ctx; // YaRN original context size
  222. float defrag_thold; // defragment the KV cache if holes/size > thold, < 0 disabled (default)
  223. ggml_backend_sched_eval_callback cb_eval;
  224. void * cb_eval_user_data;
  225. enum ggml_type type_k; // data type for K cache
  226. enum ggml_type type_v; // data type for V cache
  227. // Keep the booleans together to avoid misalignment during copy-by-value.
  228. bool logits_all; // the llama_decode() call computes all logits, not just the last one (DEPRECATED - set llama_batch.logits instead)
  229. bool embeddings; // if true, extract embeddings (together with logits)
  230. bool offload_kqv; // whether to offload the KQV ops (including the KV cache) to GPU
  231. // Abort callback
  232. // if it returns true, execution of llama_decode() will be aborted
  233. // currently works only with CPU execution
  234. ggml_abort_callback abort_callback;
  235. void * abort_callback_data;
  236. };
  237. // model quantization parameters
  238. typedef struct llama_model_quantize_params {
  239. int32_t nthread; // number of threads to use for quantizing, if <=0 will use std::thread::hardware_concurrency()
  240. enum llama_ftype ftype; // quantize to this llama_ftype
  241. enum ggml_type output_tensor_type; // output tensor type
  242. enum ggml_type token_embedding_type; // itoken embeddings tensor type
  243. bool allow_requantize; // allow quantizing non-f32/f16 tensors
  244. bool quantize_output_tensor; // quantize output.weight
  245. bool only_copy; // only copy tensors - ftype, allow_requantize and quantize_output_tensor are ignored
  246. bool pure; // quantize all tensors to the default type
  247. bool keep_split; // quantize to the same number of shards
  248. void * imatrix; // pointer to importance matrix data
  249. void * kv_overrides; // pointer to vector containing overrides
  250. } llama_model_quantize_params;
  251. // grammar types
  252. struct llama_grammar;
  253. // grammar element type
  254. enum llama_gretype {
  255. // end of rule definition
  256. LLAMA_GRETYPE_END = 0,
  257. // start of alternate definition for rule
  258. LLAMA_GRETYPE_ALT = 1,
  259. // non-terminal element: reference to rule
  260. LLAMA_GRETYPE_RULE_REF = 2,
  261. // terminal element: character (code point)
  262. LLAMA_GRETYPE_CHAR = 3,
  263. // inverse char(s) ([^a], [^a-b] [^abc])
  264. LLAMA_GRETYPE_CHAR_NOT = 4,
  265. // modifies a preceding LLAMA_GRETYPE_CHAR or LLAMA_GRETYPE_CHAR_ALT to
  266. // be an inclusive range ([a-z])
  267. LLAMA_GRETYPE_CHAR_RNG_UPPER = 5,
  268. // modifies a preceding LLAMA_GRETYPE_CHAR or
  269. // LLAMA_GRETYPE_CHAR_RNG_UPPER to add an alternate char to match ([ab], [a-zA])
  270. LLAMA_GRETYPE_CHAR_ALT = 6,
  271. };
  272. typedef struct llama_grammar_element {
  273. enum llama_gretype type;
  274. uint32_t value; // Unicode code point or rule ID
  275. } llama_grammar_element;
  276. // performance timing information
  277. struct llama_timings {
  278. double t_start_ms;
  279. double t_end_ms;
  280. double t_load_ms;
  281. double t_sample_ms;
  282. double t_p_eval_ms;
  283. double t_eval_ms;
  284. int32_t n_sample;
  285. int32_t n_p_eval;
  286. int32_t n_eval;
  287. };
  288. // used in chat template
  289. typedef struct llama_chat_message {
  290. const char * role;
  291. const char * content;
  292. } llama_chat_message;
  293. // Helpers for getting default parameters
  294. LLAMA_API struct llama_model_params llama_model_default_params(void);
  295. LLAMA_API struct llama_context_params llama_context_default_params(void);
  296. LLAMA_API struct llama_model_quantize_params llama_model_quantize_default_params(void);
  297. // Initialize the llama + ggml backend
  298. // If numa is true, use NUMA optimizations
  299. // Call once at the start of the program
  300. LLAMA_API void llama_backend_init(void);
  301. //optional:
  302. LLAMA_API void llama_numa_init(enum ggml_numa_strategy numa);
  303. // Call once at the end of the program - currently only used for MPI
  304. LLAMA_API void llama_backend_free(void);
  305. LLAMA_API struct llama_model * llama_load_model_from_file(
  306. const char * path_model,
  307. struct llama_model_params params);
  308. LLAMA_API void llama_free_model(struct llama_model * model);
  309. LLAMA_API struct llama_context * llama_new_context_with_model(
  310. struct llama_model * model,
  311. struct llama_context_params params);
  312. // Frees all allocated memory
  313. LLAMA_API void llama_free(struct llama_context * ctx);
  314. LLAMA_API int64_t llama_time_us(void);
  315. LLAMA_API size_t llama_max_devices(void);
  316. LLAMA_API bool llama_supports_mmap (void);
  317. LLAMA_API bool llama_supports_mlock (void);
  318. LLAMA_API bool llama_supports_gpu_offload(void);
  319. LLAMA_API const struct llama_model * llama_get_model(const struct llama_context * ctx);
  320. LLAMA_API uint32_t llama_n_ctx (const struct llama_context * ctx);
  321. LLAMA_API uint32_t llama_n_batch (const struct llama_context * ctx);
  322. LLAMA_API uint32_t llama_n_ubatch (const struct llama_context * ctx);
  323. LLAMA_API uint32_t llama_n_seq_max (const struct llama_context * ctx);
  324. LLAMA_API enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx);
  325. LLAMA_API enum llama_vocab_type llama_vocab_type (const struct llama_model * model);
  326. LLAMA_API enum llama_rope_type llama_rope_type (const struct llama_model * model);
  327. LLAMA_API int32_t llama_n_vocab (const struct llama_model * model);
  328. LLAMA_API int32_t llama_n_ctx_train(const struct llama_model * model);
  329. LLAMA_API int32_t llama_n_embd (const struct llama_model * model);
  330. LLAMA_API int32_t llama_n_layer (const struct llama_model * model);
  331. // Get the model's RoPE frequency scaling factor
  332. LLAMA_API float llama_rope_freq_scale_train(const struct llama_model * model);
  333. // Functions to access the model's GGUF metadata scalar values
  334. // - The functions return the length of the string on success, or -1 on failure
  335. // - The output string is always null-terminated and cleared on failure
  336. // - GGUF array values are not supported by these functions
  337. // Get metadata value as a string by key name
  338. LLAMA_API int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size);
  339. // Get the number of metadata key/value pairs
  340. LLAMA_API int32_t llama_model_meta_count(const struct llama_model * model);
  341. // Get metadata key name by index
  342. LLAMA_API int32_t llama_model_meta_key_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size);
  343. // Get metadata value as a string by index
  344. LLAMA_API int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size);
  345. // Get a string describing the model type
  346. LLAMA_API int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size);
  347. // Returns the total size of all the tensors in the model in bytes
  348. LLAMA_API uint64_t llama_model_size(const struct llama_model * model);
  349. // Returns the total number of parameters in the model
  350. LLAMA_API uint64_t llama_model_n_params(const struct llama_model * model);
  351. // Get a llama model tensor
  352. LLAMA_API struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name);
  353. // Returns 0 on success
  354. LLAMA_API uint32_t llama_model_quantize(
  355. const char * fname_inp,
  356. const char * fname_out,
  357. const llama_model_quantize_params * params);
  358. // Apply a LoRA adapter to a loaded model
  359. // path_base_model is the path to a higher quality model to use as a base for
  360. // the layers modified by the adapter. Can be NULL to use the current loaded model.
  361. // The model needs to be reloaded before applying a new adapter, otherwise the adapter
  362. // will be applied on top of the previous one
  363. // Returns 0 on success
  364. LLAMA_API int32_t llama_model_apply_lora_from_file(
  365. const struct llama_model * model,
  366. const char * path_lora,
  367. float scale,
  368. const char * path_base_model,
  369. int32_t n_threads);
  370. // Apply a loaded control vector to a llama_context, or if data is NULL, clear
  371. // the currently loaded vector.
  372. // n_embd should be the size of a single layer's control, and data should point
  373. // to an n_embd x n_layers buffer starting from layer 1.
  374. // il_start and il_end are the layer range the vector should apply to (both inclusive)
  375. // See llama_control_vector_load in common to load a control vector.
  376. LLAMA_API int32_t llama_control_vector_apply(
  377. struct llama_context * lctx,
  378. const float * data,
  379. size_t len,
  380. int32_t n_embd,
  381. int32_t il_start,
  382. int32_t il_end);
  383. //
  384. // KV cache
  385. //
  386. // Information associated with an individual cell in the KV cache view.
  387. struct llama_kv_cache_view_cell {
  388. // The position for this cell. Takes KV cache shifts into account.
  389. // May be negative if the cell is not populated.
  390. llama_pos pos;
  391. };
  392. // An updateable view of the KV cache.
  393. struct llama_kv_cache_view {
  394. // Number of KV cache cells. This will be the same as the context size.
  395. int32_t n_cells;
  396. // Maximum number of sequences that can exist in a cell. It's not an error
  397. // if there are more sequences in a cell than this value, however they will
  398. // not be visible in the view cells_sequences.
  399. int32_t n_seq_max;
  400. // Number of tokens in the cache. For example, if there are two populated
  401. // cells, the first with 1 sequence id in it and the second with 2 sequence
  402. // ids then you'll have 3 tokens.
  403. int32_t token_count;
  404. // Number of populated cache cells.
  405. int32_t used_cells;
  406. // Maximum contiguous empty slots in the cache.
  407. int32_t max_contiguous;
  408. // Index to the start of the max_contiguous slot range. Can be negative
  409. // when cache is full.
  410. int32_t max_contiguous_idx;
  411. // Information for an individual cell.
  412. struct llama_kv_cache_view_cell * cells;
  413. // The sequences for each cell. There will be n_seq_max items per cell.
  414. llama_seq_id * cells_sequences;
  415. };
  416. // Create an empty KV cache view. (use only for debugging purposes)
  417. LLAMA_API struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max);
  418. // Free a KV cache view. (use only for debugging purposes)
  419. LLAMA_API void llama_kv_cache_view_free(struct llama_kv_cache_view * view);
  420. // Update the KV cache view structure with the current state of the KV cache. (use only for debugging purposes)
  421. LLAMA_API void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view);
  422. // Returns the number of tokens in the KV cache (slow, use only for debug)
  423. // If a KV cell has multiple sequences assigned to it, it will be counted multiple times
  424. LLAMA_API int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx);
  425. // Returns the number of used KV cells (i.e. have at least one sequence assigned to them)
  426. LLAMA_API int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx);
  427. // Clear the KV cache
  428. LLAMA_API void llama_kv_cache_clear(
  429. struct llama_context * ctx);
  430. // Removes all tokens that belong to the specified sequence and have positions in [p0, p1)
  431. // Returns false if a partial sequence cannot be removed. Removing a whole sequence never fails
  432. // seq_id < 0 : match any sequence
  433. // p0 < 0 : [0, p1]
  434. // p1 < 0 : [p0, inf)
  435. LLAMA_API bool llama_kv_cache_seq_rm(
  436. struct llama_context * ctx,
  437. llama_seq_id seq_id,
  438. llama_pos p0,
  439. llama_pos p1);
  440. // Copy all tokens that belong to the specified sequence to another sequence
  441. // Note that this does not allocate extra KV cache memory - it simply assigns the tokens to the new sequence
  442. // p0 < 0 : [0, p1]
  443. // p1 < 0 : [p0, inf)
  444. LLAMA_API void llama_kv_cache_seq_cp(
  445. struct llama_context * ctx,
  446. llama_seq_id seq_id_src,
  447. llama_seq_id seq_id_dst,
  448. llama_pos p0,
  449. llama_pos p1);
  450. // Removes all tokens that do not belong to the specified sequence
  451. LLAMA_API void llama_kv_cache_seq_keep(
  452. struct llama_context * ctx,
  453. llama_seq_id seq_id);
  454. // Adds relative position "delta" to all tokens that belong to the specified sequence and have positions in [p0, p1)
  455. // If the KV cache is RoPEd, the KV data is updated accordingly:
  456. // - lazily on next llama_decode()
  457. // - explicitly with llama_kv_cache_update()
  458. // p0 < 0 : [0, p1]
  459. // p1 < 0 : [p0, inf)
  460. LLAMA_API void llama_kv_cache_seq_add(
  461. struct llama_context * ctx,
  462. llama_seq_id seq_id,
  463. llama_pos p0,
  464. llama_pos p1,
  465. llama_pos delta);
  466. // Integer division of the positions by factor of `d > 1`
  467. // If the KV cache is RoPEd, the KV data is updated accordingly:
  468. // - lazily on next llama_decode()
  469. // - explicitly with llama_kv_cache_update()
  470. // p0 < 0 : [0, p1]
  471. // p1 < 0 : [p0, inf)
  472. LLAMA_API void llama_kv_cache_seq_div(
  473. struct llama_context * ctx,
  474. llama_seq_id seq_id,
  475. llama_pos p0,
  476. llama_pos p1,
  477. int d);
  478. // Returns the largest position present in the KV cache for the specified sequence
  479. LLAMA_API llama_pos llama_kv_cache_seq_pos_max(
  480. struct llama_context * ctx,
  481. llama_seq_id seq_id);
  482. // Defragment the KV cache
  483. // This will be applied:
  484. // - lazily on next llama_decode()
  485. // - explicitly with llama_kv_cache_update()
  486. LLAMA_API void llama_kv_cache_defrag(struct llama_context * ctx);
  487. // Apply the KV cache updates (such as K-shifts, defragmentation, etc.)
  488. LLAMA_API void llama_kv_cache_update(struct llama_context * ctx);
  489. //
  490. // State / sessions
  491. //
  492. // Returns the maximum size in bytes of the state (rng, logits, embedding
  493. // and kv_cache) - will often be smaller after compacting tokens
  494. LLAMA_API size_t llama_state_get_size(const struct llama_context * ctx);
  495. LLAMA_API DEPRECATED(size_t llama_get_state_size(const struct llama_context * ctx),
  496. "use llama_state_get_size instead");
  497. // Copies the state to the specified destination address.
  498. // Destination needs to have allocated enough memory.
  499. // Returns the number of bytes copied
  500. LLAMA_API size_t llama_state_get_data(
  501. struct llama_context * ctx,
  502. uint8_t * dst);
  503. LLAMA_API DEPRECATED(size_t llama_copy_state_data(
  504. struct llama_context * ctx,
  505. uint8_t * dst),
  506. "use llama_state_get_data instead");
  507. // Set the state reading from the specified address
  508. // Returns the number of bytes read
  509. LLAMA_API size_t llama_state_set_data(
  510. struct llama_context * ctx,
  511. const uint8_t * src);
  512. LLAMA_API DEPRECATED(size_t llama_set_state_data(
  513. struct llama_context * ctx,
  514. const uint8_t * src),
  515. "use llama_state_set_data instead");
  516. // Save/load session file
  517. LLAMA_API bool llama_state_load_file(
  518. struct llama_context * ctx,
  519. const char * path_session,
  520. llama_token * tokens_out,
  521. size_t n_token_capacity,
  522. size_t * n_token_count_out);
  523. LLAMA_API DEPRECATED(bool llama_load_session_file(
  524. struct llama_context * ctx,
  525. const char * path_session,
  526. llama_token * tokens_out,
  527. size_t n_token_capacity,
  528. size_t * n_token_count_out),
  529. "use llama_state_load_file instead");
  530. LLAMA_API bool llama_state_save_file(
  531. struct llama_context * ctx,
  532. const char * path_session,
  533. const llama_token * tokens,
  534. size_t n_token_count);
  535. LLAMA_API DEPRECATED(bool llama_save_session_file(
  536. struct llama_context * ctx,
  537. const char * path_session,
  538. const llama_token * tokens,
  539. size_t n_token_count),
  540. "use llama_state_save_file instead");
  541. // Get the exact size needed to copy the KV cache of a single sequence
  542. LLAMA_API size_t llama_state_seq_get_size(
  543. struct llama_context * ctx,
  544. llama_seq_id seq_id);
  545. // Copy the KV cache of a single sequence into the specified buffer
  546. LLAMA_API size_t llama_state_seq_get_data(
  547. struct llama_context * ctx,
  548. uint8_t * dst,
  549. llama_seq_id seq_id);
  550. // Copy the sequence data (originally copied with `llama_state_seq_get_data`) into the specified sequence
  551. // Returns:
  552. // - Positive: Ok
  553. // - Zero: Failed to load
  554. LLAMA_API size_t llama_state_seq_set_data(
  555. struct llama_context * ctx,
  556. const uint8_t * src,
  557. llama_seq_id dest_seq_id);
  558. LLAMA_API size_t llama_state_seq_save_file(
  559. struct llama_context * ctx,
  560. const char * filepath,
  561. llama_seq_id seq_id,
  562. const llama_token * tokens,
  563. size_t n_token_count);
  564. LLAMA_API size_t llama_state_seq_load_file(
  565. struct llama_context * ctx,
  566. const char * filepath,
  567. llama_seq_id dest_seq_id,
  568. llama_token * tokens_out,
  569. size_t n_token_capacity,
  570. size_t * n_token_count_out);
  571. //
  572. // Decoding
  573. //
  574. // Return batch for single sequence of tokens starting at pos_0
  575. //
  576. // NOTE: this is a helper function to facilitate transition to the new batch API - avoid using it
  577. //
  578. LLAMA_API struct llama_batch llama_batch_get_one(
  579. llama_token * tokens,
  580. int32_t n_tokens,
  581. llama_pos pos_0,
  582. llama_seq_id seq_id);
  583. // Allocates a batch of tokens on the heap that can hold a maximum of n_tokens
  584. // Each token can be assigned up to n_seq_max sequence ids
  585. // The batch has to be freed with llama_batch_free()
  586. // If embd != 0, llama_batch.embd will be allocated with size of n_tokens * embd * sizeof(float)
  587. // Otherwise, llama_batch.token will be allocated to store n_tokens llama_token
  588. // The rest of the llama_batch members are allocated with size n_tokens
  589. // All members are left uninitialized
  590. LLAMA_API struct llama_batch llama_batch_init(
  591. int32_t n_tokens,
  592. int32_t embd,
  593. int32_t n_seq_max);
  594. // Frees a batch of tokens allocated with llama_batch_init()
  595. LLAMA_API void llama_batch_free(struct llama_batch batch);
  596. // Positive return values does not mean a fatal error, but rather a warning.
  597. // 0 - success
  598. // 1 - could not find a KV slot for the batch (try reducing the size of the batch or increase the context)
  599. // < 0 - error
  600. LLAMA_API int32_t llama_decode(
  601. struct llama_context * ctx,
  602. struct llama_batch batch);
  603. // Set the number of threads used for decoding
  604. // n_threads is the number of threads used for generation (single token)
  605. // n_threads_batch is the number of threads used for prompt and batch processing (multiple tokens)
  606. LLAMA_API void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch);
  607. // Set whether to use causal attention or not
  608. // If set to true, the model will only attend to the past tokens
  609. LLAMA_API void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn);
  610. // Set abort callback
  611. LLAMA_API void llama_set_abort_callback(struct llama_context * ctx, ggml_abort_callback abort_callback, void * abort_callback_data);
  612. // Wait until all computations are finished
  613. // This is automatically done when using one of the functions below to obtain the computation results
  614. // and is not necessary to call it explicitly in most cases
  615. LLAMA_API void llama_synchronize(struct llama_context * ctx);
  616. // Token logits obtained from the last call to llama_decode()
  617. // The logits for which llama_batch.logits[i] != 0 are stored contiguously
  618. // in the order they have appeared in the batch.
  619. // Rows: number of tokens for which llama_batch.logits[i] != 0
  620. // Cols: n_vocab
  621. LLAMA_API float * llama_get_logits(struct llama_context * ctx);
  622. // Logits for the ith token. For positive indices, Equivalent to:
  623. // llama_get_logits(ctx) + ctx->output_ids[i]*n_vocab
  624. // Negative indicies can be used to access logits in reverse order, -1 is the last logit.
  625. // returns NULL for invalid ids.
  626. LLAMA_API float * llama_get_logits_ith(struct llama_context * ctx, int32_t i);
  627. // Get all output token embeddings.
  628. // when pooling_type == LLAMA_POOLING_TYPE_NONE or when using a generative model,
  629. // the embeddings for which llama_batch.logits[i] != 0 are stored contiguously
  630. // in the order they have appeared in the batch.
  631. // shape: [n_outputs*n_embd]
  632. // Otherwise, returns NULL.
  633. LLAMA_API float * llama_get_embeddings(struct llama_context * ctx);
  634. // Get the embeddings for the ith token. For positive indices, Equivalent to:
  635. // llama_get_embeddings(ctx) + ctx->output_ids[i]*n_embd
  636. // Negative indicies can be used to access embeddings in reverse order, -1 is the last embedding.
  637. // shape: [n_embd] (1-dimensional)
  638. // returns NULL for invalid ids.
  639. LLAMA_API float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i);
  640. // Get the embeddings for a sequence id
  641. // Returns NULL if pooling_type is LLAMA_POOLING_TYPE_NONE
  642. // shape: [n_embd] (1-dimensional)
  643. LLAMA_API float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id);
  644. //
  645. // Vocab
  646. //
  647. LLAMA_API const char * llama_token_get_text(const struct llama_model * model, llama_token token);
  648. LLAMA_API float llama_token_get_score(const struct llama_model * model, llama_token token);
  649. LLAMA_API enum llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token);
  650. // Check if the token is supposed to end generation (end-of-generation, eg. EOS, EOT, etc.)
  651. LLAMA_API bool llama_token_is_eog(const struct llama_model * model, llama_token token);
  652. // Special tokens
  653. LLAMA_API llama_token llama_token_bos(const struct llama_model * model); // beginning-of-sentence
  654. LLAMA_API llama_token llama_token_eos(const struct llama_model * model); // end-of-sentence
  655. LLAMA_API llama_token llama_token_cls(const struct llama_model * model); // classification
  656. LLAMA_API llama_token llama_token_sep(const struct llama_model * model); // sentence separator
  657. LLAMA_API llama_token llama_token_nl (const struct llama_model * model); // next-line
  658. // Returns -1 if unknown, 1 for true or 0 for false.
  659. LLAMA_API int32_t llama_add_bos_token(const struct llama_model * model);
  660. // Returns -1 if unknown, 1 for true or 0 for false.
  661. LLAMA_API int32_t llama_add_eos_token(const struct llama_model * model);
  662. // Codellama infill tokens
  663. LLAMA_API llama_token llama_token_prefix(const struct llama_model * model); // Beginning of infill prefix
  664. LLAMA_API llama_token llama_token_middle(const struct llama_model * model); // Beginning of infill middle
  665. LLAMA_API llama_token llama_token_suffix(const struct llama_model * model); // Beginning of infill suffix
  666. LLAMA_API llama_token llama_token_eot (const struct llama_model * model); // End of infill middle
  667. //
  668. // Tokenization
  669. //
  670. /// @details Convert the provided text into tokens.
  671. /// @param tokens The tokens pointer must be large enough to hold the resulting tokens.
  672. /// @return Returns the number of tokens on success, no more than n_tokens_max
  673. /// @return Returns a negative number on failure - the number of tokens that would have been returned
  674. /// @param parse_special Allow tokenizing special and/or control tokens which otherwise are not exposed and treated
  675. /// as plaintext. Does not insert a leading space.
  676. LLAMA_API int32_t llama_tokenize(
  677. const struct llama_model * model,
  678. const char * text,
  679. int32_t text_len,
  680. llama_token * tokens,
  681. int32_t n_tokens_max,
  682. bool add_special,
  683. bool parse_special);
  684. // Token Id -> Piece.
  685. // Uses the vocabulary in the provided context.
  686. // Does not write null terminator to the buffer.
  687. // User code is responsible to remove the leading whitespace of the first non-BOS token when decoding multiple tokens.
  688. // @param special If true, special tokens are rendered in the output.
  689. LLAMA_API int32_t llama_token_to_piece(
  690. const struct llama_model * model,
  691. llama_token token,
  692. char * buf,
  693. int32_t length,
  694. bool special);
  695. /// Apply chat template. Inspired by hf apply_chat_template() on python.
  696. /// Both "model" and "custom_template" are optional, but at least one is required. "custom_template" has higher precedence than "model"
  697. /// NOTE: This function does not use a jinja parser. It only support a pre-defined list of template. See more: https://github.com/ggerganov/llama.cpp/wiki/Templates-supported-by-llama_chat_apply_template
  698. /// @param tmpl A Jinja template to use for this chat. If this is nullptr, the model’s default chat template will be used instead.
  699. /// @param chat Pointer to a list of multiple llama_chat_message
  700. /// @param n_msg Number of llama_chat_message in this chat
  701. /// @param add_ass Whether to end the prompt with the token(s) that indicate the start of an assistant message.
  702. /// @param buf A buffer to hold the output formatted prompt. The recommended alloc size is 2 * (total number of characters of all messages)
  703. /// @param length The size of the allocated buffer
  704. /// @return The total number of bytes of the formatted prompt. If is it larger than the size of buffer, you may need to re-alloc it and then re-apply the template.
  705. LLAMA_API int32_t llama_chat_apply_template(
  706. const struct llama_model * model,
  707. const char * tmpl,
  708. const struct llama_chat_message * chat,
  709. size_t n_msg,
  710. bool add_ass,
  711. char * buf,
  712. int32_t length);
  713. //
  714. // Grammar
  715. //
  716. LLAMA_API struct llama_grammar * llama_grammar_init(
  717. const llama_grammar_element ** rules,
  718. size_t n_rules,
  719. size_t start_rule_index);
  720. LLAMA_API void llama_grammar_free(struct llama_grammar * grammar);
  721. LLAMA_API struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar);
  722. //
  723. // Sampling functions
  724. //
  725. // Sets the current rng seed.
  726. LLAMA_API void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed);
  727. /// @details Repetition penalty described in CTRL academic paper https://arxiv.org/abs/1909.05858, with negative logit fix.
  728. /// @details Frequency and presence penalties described in OpenAI API https://platform.openai.com/docs/api-reference/parameter-details.
  729. LLAMA_API void llama_sample_repetition_penalties(
  730. struct llama_context * ctx,
  731. llama_token_data_array * candidates,
  732. const llama_token * last_tokens,
  733. size_t penalty_last_n,
  734. float penalty_repeat,
  735. float penalty_freq,
  736. float penalty_present);
  737. /// @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
  738. /// @param logits Logits extracted from the original generation context.
  739. /// @param logits_guidance Logits extracted from 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.
  740. /// @param scale Guidance strength. 1.0f means no guidance. Higher values mean stronger guidance.
  741. LLAMA_API void llama_sample_apply_guidance(
  742. struct llama_context * ctx,
  743. float * logits,
  744. float * logits_guidance,
  745. float scale);
  746. /// @details Sorts candidate tokens by their logits in descending order and calculate probabilities based on logits.
  747. LLAMA_API void llama_sample_softmax(
  748. struct llama_context * ctx,
  749. llama_token_data_array * candidates);
  750. /// @details Top-K sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
  751. LLAMA_API void llama_sample_top_k(
  752. struct llama_context * ctx,
  753. llama_token_data_array * candidates,
  754. int32_t k,
  755. size_t min_keep);
  756. /// @details Nucleus sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
  757. LLAMA_API void llama_sample_top_p(
  758. struct llama_context * ctx,
  759. llama_token_data_array * candidates,
  760. float p,
  761. size_t min_keep);
  762. /// @details Minimum P sampling as described in https://github.com/ggerganov/llama.cpp/pull/3841
  763. LLAMA_API void llama_sample_min_p(
  764. struct llama_context * ctx,
  765. llama_token_data_array * candidates,
  766. float p,
  767. size_t min_keep);
  768. /// @details Tail Free Sampling described in https://www.trentonbricken.com/Tail-Free-Sampling/.
  769. LLAMA_API void llama_sample_tail_free(
  770. struct llama_context * ctx,
  771. llama_token_data_array * candidates,
  772. float z,
  773. size_t min_keep);
  774. /// @details Locally Typical Sampling implementation described in the paper https://arxiv.org/abs/2202.00666.
  775. LLAMA_API void llama_sample_typical(
  776. struct llama_context * ctx,
  777. llama_token_data_array * candidates,
  778. float p,
  779. size_t min_keep);
  780. /// @details Dynamic temperature implementation described in the paper https://arxiv.org/abs/2309.02772.
  781. LLAMA_API void llama_sample_entropy(
  782. struct llama_context * ctx,
  783. llama_token_data_array * candidates_p,
  784. float min_temp,
  785. float max_temp,
  786. float exponent_val);
  787. LLAMA_API void llama_sample_temp(
  788. struct llama_context * ctx,
  789. llama_token_data_array * candidates,
  790. float temp);
  791. /// @details Apply constraints from grammar
  792. LLAMA_API void llama_sample_grammar(
  793. struct llama_context * ctx,
  794. llama_token_data_array * candidates,
  795. const struct llama_grammar * grammar);
  796. /// @details Mirostat 1.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
  797. /// @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.
  798. /// @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.
  799. /// @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.
  800. /// @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.
  801. /// @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.
  802. LLAMA_API llama_token llama_sample_token_mirostat(
  803. struct llama_context * ctx,
  804. llama_token_data_array * candidates,
  805. float tau,
  806. float eta,
  807. int32_t m,
  808. float * mu);
  809. /// @details Mirostat 2.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
  810. /// @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.
  811. /// @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.
  812. /// @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.
  813. /// @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.
  814. LLAMA_API llama_token llama_sample_token_mirostat_v2(
  815. struct llama_context * ctx,
  816. llama_token_data_array * candidates,
  817. float tau,
  818. float eta,
  819. float * mu);
  820. /// @details Selects the token with the highest probability.
  821. /// Does not compute the token probabilities. Use llama_sample_softmax() instead.
  822. LLAMA_API llama_token llama_sample_token_greedy(
  823. struct llama_context * ctx,
  824. llama_token_data_array * candidates);
  825. /// @details Randomly selects a token from the candidates based on their probabilities using the RNG of ctx.
  826. LLAMA_API llama_token llama_sample_token(
  827. struct llama_context * ctx,
  828. llama_token_data_array * candidates);
  829. /// @details Accepts the sampled token into the grammar
  830. LLAMA_API void llama_grammar_accept_token(
  831. struct llama_context * ctx,
  832. struct llama_grammar * grammar,
  833. llama_token token);
  834. //
  835. // Beam search
  836. //
  837. struct llama_beam_view {
  838. const llama_token * tokens;
  839. size_t n_tokens;
  840. float p; // Cumulative beam probability (renormalized relative to all beams)
  841. bool eob; // Callback should set this to true when a beam is at end-of-beam.
  842. };
  843. // Passed to beam_search_callback function.
  844. // Whenever 0 < common_prefix_length, this number of tokens should be copied from any of the beams
  845. // (e.g. beams[0]) as they will be removed (shifted) from all beams in all subsequent callbacks.
  846. // These pointers are valid only during the synchronous callback, so should not be saved.
  847. struct llama_beams_state {
  848. struct llama_beam_view * beam_views;
  849. size_t n_beams; // Number of elements in beam_views[].
  850. size_t common_prefix_length; // Current max length of prefix tokens shared by all beams.
  851. bool last_call; // True iff this is the last callback invocation.
  852. };
  853. // Type of pointer to the beam_search_callback function.
  854. // void* callback_data is any custom data passed to llama_beam_search, that is subsequently
  855. // passed back to beam_search_callback. This avoids having to use global variables in the callback.
  856. typedef void (*llama_beam_search_callback_fn_t)(void * callback_data, struct llama_beams_state);
  857. /// @details Deterministically returns entire sentence constructed by a beam search.
  858. /// @param ctx Pointer to the llama_context.
  859. /// @param callback Invoked for each iteration of the beam_search loop, passing in beams_state.
  860. /// @param callback_data A pointer that is simply passed back to callback.
  861. /// @param n_beams Number of beams to use.
  862. /// @param n_past Number of tokens already evaluated.
  863. /// @param n_predict Maximum number of tokens to predict. EOS may occur earlier.
  864. LLAMA_API void llama_beam_search(
  865. struct llama_context * ctx,
  866. llama_beam_search_callback_fn_t callback,
  867. void * callback_data,
  868. size_t n_beams,
  869. int32_t n_past,
  870. int32_t n_predict);
  871. /// @details Build a split GGUF final path for this chunk.
  872. /// llama_split_path(split_path, sizeof(split_path), "/models/ggml-model-q4_0", 2, 4) => split_path = "/models/ggml-model-q4_0-00002-of-00004.gguf"
  873. // Returns the split_path length.
  874. LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count);
  875. /// @details Extract the path prefix from the split_path if and only if the split_no and split_count match.
  876. /// llama_split_prefix(split_prefix, 64, "/models/ggml-model-q4_0-00002-of-00004.gguf", 2, 4) => split_prefix = "/models/ggml-model-q4_0"
  877. // Returns the split_prefix length.
  878. LLAMA_API int llama_split_prefix(char * split_prefix, size_t maxlen, const char * split_path, int split_no, int split_count);
  879. // Performance information
  880. LLAMA_API struct llama_timings llama_get_timings(struct llama_context * ctx);
  881. LLAMA_API void llama_print_timings(struct llama_context * ctx);
  882. LLAMA_API void llama_reset_timings(struct llama_context * ctx);
  883. // Print system information
  884. LLAMA_API const char * llama_print_system_info(void);
  885. // Set callback for all future logging events.
  886. // If this is not called, or NULL is supplied, everything is output on stderr.
  887. LLAMA_API void llama_log_set(ggml_log_callback log_callback, void * user_data);
  888. LLAMA_API void llama_dump_timing_info_yaml(FILE * stream, const struct llama_context * ctx);
  889. #ifdef __cplusplus
  890. }
  891. #endif
  892. // Internal API to be implemented by llama.cpp and used by tests/benchmarks only
  893. #ifdef LLAMA_API_INTERNAL
  894. #include <random>
  895. #include <string>
  896. #include <vector>
  897. struct ggml_tensor;
  898. struct llama_partial_utf8 {
  899. uint32_t value; // bit value so far (unshifted)
  900. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  901. };
  902. struct llama_grammar {
  903. const std::vector<std::vector<llama_grammar_element>> rules;
  904. std::vector<std::vector<const llama_grammar_element *>> stacks;
  905. // buffer for partially generated UTF-8 sequence from accepted tokens
  906. llama_partial_utf8 partial_utf8;
  907. };
  908. struct llama_grammar_candidate {
  909. size_t index;
  910. const uint32_t * code_points;
  911. llama_partial_utf8 partial_utf8;
  912. };
  913. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  914. struct llama_context * ctx
  915. );
  916. void llama_grammar_accept(
  917. const std::vector<std::vector<llama_grammar_element>> & rules,
  918. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  919. const uint32_t chr,
  920. std::vector<std::vector<const llama_grammar_element *>> & new_stacks);
  921. std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  922. const std::string & src,
  923. llama_partial_utf8 partial_start);
  924. // Randomly selects a token from the candidates based on their probabilities using given std::mt19937.
  925. // This is a temporary workaround in order to fix race conditions when sampling with multiple sequences.
  926. llama_token llama_sample_token_with_rng(struct llama_context * ctx, llama_token_data_array * candidates, std::mt19937 & rng);
  927. #endif // LLAMA_API_INTERNAL
  928. #endif // LLAMA_H