cui-llama.rn 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/android/src/main/jni.cpp +9 -9
  2. package/cpp/common.cpp +163 -60
  3. package/cpp/common.h +43 -12
  4. package/cpp/ggml-alloc.c +1042 -1037
  5. package/cpp/ggml-backend-impl.h +255 -256
  6. package/cpp/ggml-backend-reg.cpp +582 -582
  7. package/cpp/ggml-backend.cpp +2002 -2002
  8. package/cpp/ggml-backend.h +354 -352
  9. package/cpp/ggml-common.h +1853 -1853
  10. package/cpp/ggml-cpp.h +39 -39
  11. package/cpp/ggml-cpu-aarch64.cpp +4247 -4247
  12. package/cpp/ggml-cpu-aarch64.h +8 -8
  13. package/cpp/ggml-cpu-impl.h +386 -386
  14. package/cpp/ggml-cpu-quants.c +10920 -10839
  15. package/cpp/ggml-cpu-traits.cpp +36 -36
  16. package/cpp/ggml-cpu-traits.h +38 -38
  17. package/cpp/ggml-cpu.c +329 -60
  18. package/cpp/ggml-cpu.cpp +10 -2
  19. package/cpp/ggml-cpu.h +135 -135
  20. package/cpp/ggml-impl.h +567 -567
  21. package/cpp/ggml-metal-impl.h +17 -17
  22. package/cpp/ggml-metal.m +4884 -4884
  23. package/cpp/ggml-quants.c +5238 -5238
  24. package/cpp/ggml-threading.h +14 -14
  25. package/cpp/ggml.c +6514 -6448
  26. package/cpp/ggml.h +2194 -2163
  27. package/cpp/gguf.cpp +1329 -1325
  28. package/cpp/gguf.h +202 -202
  29. package/cpp/json-schema-to-grammar.cpp +1045 -1045
  30. package/cpp/json-schema-to-grammar.h +8 -8
  31. package/cpp/json.hpp +24766 -24766
  32. package/cpp/llama-adapter.cpp +347 -346
  33. package/cpp/llama-adapter.h +74 -73
  34. package/cpp/llama-arch.cpp +1487 -1434
  35. package/cpp/llama-arch.h +400 -395
  36. package/cpp/llama-batch.cpp +368 -368
  37. package/cpp/llama-batch.h +88 -88
  38. package/cpp/llama-chat.cpp +578 -567
  39. package/cpp/llama-chat.h +52 -51
  40. package/cpp/llama-context.cpp +1775 -1771
  41. package/cpp/llama-context.h +128 -128
  42. package/cpp/llama-cparams.cpp +1 -1
  43. package/cpp/llama-cparams.h +37 -37
  44. package/cpp/llama-cpp.h +30 -30
  45. package/cpp/llama-grammar.cpp +1139 -1139
  46. package/cpp/llama-grammar.h +143 -143
  47. package/cpp/llama-hparams.cpp +71 -71
  48. package/cpp/llama-hparams.h +139 -140
  49. package/cpp/llama-impl.cpp +167 -167
  50. package/cpp/llama-impl.h +61 -61
  51. package/cpp/llama-kv-cache.cpp +718 -718
  52. package/cpp/llama-kv-cache.h +218 -218
  53. package/cpp/llama-mmap.cpp +2 -1
  54. package/cpp/llama-mmap.h +67 -67
  55. package/cpp/llama-model-loader.cpp +1124 -1011
  56. package/cpp/llama-model-loader.h +167 -158
  57. package/cpp/llama-model.cpp +3997 -2202
  58. package/cpp/llama-model.h +370 -391
  59. package/cpp/llama-sampling.cpp +2408 -2406
  60. package/cpp/llama-sampling.h +32 -48
  61. package/cpp/llama-vocab.cpp +3247 -1982
  62. package/cpp/llama-vocab.h +125 -182
  63. package/cpp/llama.cpp +416 -2886
  64. package/cpp/llama.h +1323 -1285
  65. package/cpp/log.cpp +401 -401
  66. package/cpp/log.h +121 -121
  67. package/cpp/rn-llama.hpp +18 -12
  68. package/cpp/sampling.cpp +505 -500
  69. package/cpp/sgemm.cpp +2597 -2597
  70. package/cpp/speculative.cpp +277 -274
  71. package/cpp/speculative.h +28 -28
  72. package/cpp/unicode.cpp +2 -3
  73. package/package.json +1 -1
package/cpp/llama.h CHANGED
@@ -1,1285 +1,1323 @@
1
- #ifndef LLAMA_H
2
- #define LLAMA_H
3
-
4
- #include "ggml.h"
5
- #include "ggml-cpu.h"
6
- #include "ggml-backend.h"
7
-
8
- #include <stddef.h>
9
- #include <stdint.h>
10
- #include <stdio.h>
11
- #include <stdbool.h>
12
- #include <random>
13
-
14
- #ifdef LLAMA_SHARED
15
- # if defined(_WIN32) && !defined(__MINGW32__)
16
- # ifdef LLAMA_BUILD
17
- # define LLAMA_API __declspec(dllexport)
18
- # else
19
- # define LLAMA_API __declspec(dllimport)
20
- # endif
21
- # else
22
- # define LLAMA_API __attribute__ ((visibility ("default")))
23
- # endif
24
- #else
25
- # define LLAMA_API
26
- #endif
27
-
28
- #ifdef __GNUC__
29
- # define DEPRECATED(func, hint) func __attribute__((deprecated(hint)))
30
- #elif defined(_MSC_VER)
31
- # define DEPRECATED(func, hint) __declspec(deprecated(hint)) func
32
- #else
33
- # define DEPRECATED(func, hint) func
34
- #endif
35
-
36
- #define LLAMA_DEFAULT_SEED 0xFFFFFFFF
37
-
38
- #define LLAMA_TOKEN_NULL -1
39
-
40
- #define LLAMA_FILE_MAGIC_GGLA 0x67676c61u // 'ggla'
41
- #define LLAMA_FILE_MAGIC_GGSN 0x6767736eu // 'ggsn'
42
- #define LLAMA_FILE_MAGIC_GGSQ 0x67677371u // 'ggsq'
43
-
44
- #define LLAMA_SESSION_MAGIC LLAMA_FILE_MAGIC_GGSN
45
- #define LLAMA_SESSION_VERSION 9
46
-
47
- #define LLAMA_STATE_SEQ_MAGIC LLAMA_FILE_MAGIC_GGSQ
48
- #define LLAMA_STATE_SEQ_VERSION 2
49
-
50
- #ifdef __cplusplus
51
- extern "C" {
52
- #endif
53
-
54
- //
55
- // C interface
56
- //
57
- // TODO: show sample usage
58
- //
59
-
60
- // struct llama_vocab; // TODO: add in the future
61
- struct llama_model;
62
- struct llama_context;
63
- struct llama_sampler;
64
-
65
- typedef int32_t llama_pos;
66
- typedef int32_t llama_token;
67
- typedef int32_t llama_seq_id;
68
-
69
- enum llama_vocab_type {
70
- LLAMA_VOCAB_TYPE_NONE = 0, // For models without vocab
71
- LLAMA_VOCAB_TYPE_SPM = 1, // LLaMA tokenizer based on byte-level BPE with byte fallback
72
- LLAMA_VOCAB_TYPE_BPE = 2, // GPT-2 tokenizer based on byte-level BPE
73
- LLAMA_VOCAB_TYPE_WPM = 3, // BERT tokenizer based on WordPiece
74
- LLAMA_VOCAB_TYPE_UGM = 4, // T5 tokenizer based on Unigram
75
- LLAMA_VOCAB_TYPE_RWKV = 5, // RWKV tokenizer based on greedy tokenization
76
- };
77
-
78
- // pre-tokenization types
79
- enum llama_vocab_pre_type {
80
- LLAMA_VOCAB_PRE_TYPE_DEFAULT = 0,
81
- LLAMA_VOCAB_PRE_TYPE_LLAMA3 = 1,
82
- LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM = 2,
83
- LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER = 3,
84
- LLAMA_VOCAB_PRE_TYPE_FALCON = 4,
85
- LLAMA_VOCAB_PRE_TYPE_MPT = 5,
86
- LLAMA_VOCAB_PRE_TYPE_STARCODER = 6,
87
- LLAMA_VOCAB_PRE_TYPE_GPT2 = 7,
88
- LLAMA_VOCAB_PRE_TYPE_REFACT = 8,
89
- LLAMA_VOCAB_PRE_TYPE_COMMAND_R = 9,
90
- LLAMA_VOCAB_PRE_TYPE_STABLELM2 = 10,
91
- LLAMA_VOCAB_PRE_TYPE_QWEN2 = 11,
92
- LLAMA_VOCAB_PRE_TYPE_OLMO = 12,
93
- LLAMA_VOCAB_PRE_TYPE_DBRX = 13,
94
- LLAMA_VOCAB_PRE_TYPE_SMAUG = 14,
95
- LLAMA_VOCAB_PRE_TYPE_PORO = 15,
96
- LLAMA_VOCAB_PRE_TYPE_CHATGLM3 = 16,
97
- LLAMA_VOCAB_PRE_TYPE_CHATGLM4 = 17,
98
- LLAMA_VOCAB_PRE_TYPE_VIKING = 18,
99
- LLAMA_VOCAB_PRE_TYPE_JAIS = 19,
100
- LLAMA_VOCAB_PRE_TYPE_TEKKEN = 20,
101
- LLAMA_VOCAB_PRE_TYPE_SMOLLM = 21,
102
- LLAMA_VOCAB_PRE_TYPE_CODESHELL = 22,
103
- LLAMA_VOCAB_PRE_TYPE_BLOOM = 23,
104
- LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH = 24,
105
- LLAMA_VOCAB_PRE_TYPE_EXAONE = 25,
106
- LLAMA_VOCAB_PRE_TYPE_CHAMELEON = 26,
107
- LLAMA_VOCAB_PRE_TYPE_MINERVA = 27,
108
- LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM = 28,
109
- };
110
-
111
- enum llama_rope_type {
112
- LLAMA_ROPE_TYPE_NONE = -1,
113
- LLAMA_ROPE_TYPE_NORM = 0,
114
- LLAMA_ROPE_TYPE_NEOX = LM_GGML_ROPE_TYPE_NEOX,
115
- LLAMA_ROPE_TYPE_MROPE = LM_GGML_ROPE_TYPE_MROPE,
116
- LLAMA_ROPE_TYPE_VISION = LM_GGML_ROPE_TYPE_VISION,
117
- };
118
-
119
- enum llama_token_type { //TODO: remove, required until per token attributes are available from GGUF file
120
- LLAMA_TOKEN_TYPE_UNDEFINED = 0,
121
- LLAMA_TOKEN_TYPE_NORMAL = 1,
122
- LLAMA_TOKEN_TYPE_UNKNOWN = 2,
123
- LLAMA_TOKEN_TYPE_CONTROL = 3,
124
- LLAMA_TOKEN_TYPE_USER_DEFINED = 4,
125
- LLAMA_TOKEN_TYPE_UNUSED = 5,
126
- LLAMA_TOKEN_TYPE_BYTE = 6,
127
- };
128
-
129
- enum llama_token_attr {
130
- LLAMA_TOKEN_ATTR_UNDEFINED = 0,
131
- LLAMA_TOKEN_ATTR_UNKNOWN = 1 << 0,
132
- LLAMA_TOKEN_ATTR_UNUSED = 1 << 1,
133
- LLAMA_TOKEN_ATTR_NORMAL = 1 << 2,
134
- LLAMA_TOKEN_ATTR_CONTROL = 1 << 3, // SPECIAL?
135
- LLAMA_TOKEN_ATTR_USER_DEFINED = 1 << 4,
136
- LLAMA_TOKEN_ATTR_BYTE = 1 << 5,
137
- LLAMA_TOKEN_ATTR_NORMALIZED = 1 << 6,
138
- LLAMA_TOKEN_ATTR_LSTRIP = 1 << 7,
139
- LLAMA_TOKEN_ATTR_RSTRIP = 1 << 8,
140
- LLAMA_TOKEN_ATTR_SINGLE_WORD = 1 << 9,
141
- };
142
-
143
- // model file types
144
- enum llama_ftype {
145
- LLAMA_FTYPE_ALL_F32 = 0,
146
- LLAMA_FTYPE_MOSTLY_F16 = 1, // except 1d tensors
147
- LLAMA_FTYPE_MOSTLY_Q4_0 = 2, // except 1d tensors
148
- LLAMA_FTYPE_MOSTLY_Q4_1 = 3, // except 1d tensors
149
- // LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16 = 4, // tok_embeddings.weight and output.weight are F16
150
- // LLAMA_FTYPE_MOSTLY_Q4_2 = 5, // support has been removed
151
- // LLAMA_FTYPE_MOSTLY_Q4_3 = 6, // support has been removed
152
- LLAMA_FTYPE_MOSTLY_Q8_0 = 7, // except 1d tensors
153
- LLAMA_FTYPE_MOSTLY_Q5_0 = 8, // except 1d tensors
154
- LLAMA_FTYPE_MOSTLY_Q5_1 = 9, // except 1d tensors
155
- LLAMA_FTYPE_MOSTLY_Q2_K = 10, // except 1d tensors
156
- LLAMA_FTYPE_MOSTLY_Q3_K_S = 11, // except 1d tensors
157
- LLAMA_FTYPE_MOSTLY_Q3_K_M = 12, // except 1d tensors
158
- LLAMA_FTYPE_MOSTLY_Q3_K_L = 13, // except 1d tensors
159
- LLAMA_FTYPE_MOSTLY_Q4_K_S = 14, // except 1d tensors
160
- LLAMA_FTYPE_MOSTLY_Q4_K_M = 15, // except 1d tensors
161
- LLAMA_FTYPE_MOSTLY_Q5_K_S = 16, // except 1d tensors
162
- LLAMA_FTYPE_MOSTLY_Q5_K_M = 17, // except 1d tensors
163
- LLAMA_FTYPE_MOSTLY_Q6_K = 18, // except 1d tensors
164
- LLAMA_FTYPE_MOSTLY_IQ2_XXS = 19, // except 1d tensors
165
- LLAMA_FTYPE_MOSTLY_IQ2_XS = 20, // except 1d tensors
166
- LLAMA_FTYPE_MOSTLY_Q2_K_S = 21, // except 1d tensors
167
- LLAMA_FTYPE_MOSTLY_IQ3_XS = 22, // except 1d tensors
168
- LLAMA_FTYPE_MOSTLY_IQ3_XXS = 23, // except 1d tensors
169
- LLAMA_FTYPE_MOSTLY_IQ1_S = 24, // except 1d tensors
170
- LLAMA_FTYPE_MOSTLY_IQ4_NL = 25, // except 1d tensors
171
- LLAMA_FTYPE_MOSTLY_IQ3_S = 26, // except 1d tensors
172
- LLAMA_FTYPE_MOSTLY_IQ3_M = 27, // except 1d tensors
173
- LLAMA_FTYPE_MOSTLY_IQ2_S = 28, // except 1d tensors
174
- LLAMA_FTYPE_MOSTLY_IQ2_M = 29, // except 1d tensors
175
- LLAMA_FTYPE_MOSTLY_IQ4_XS = 30, // except 1d tensors
176
- LLAMA_FTYPE_MOSTLY_IQ1_M = 31, // except 1d tensors
177
- LLAMA_FTYPE_MOSTLY_BF16 = 32, // except 1d tensors
178
- //LLAMA_FTYPE_MOSTLY_Q4_0_4_4 = 33, // removed from gguf files, use Q4_0 and runtime repack
179
- //LLAMA_FTYPE_MOSTLY_Q4_0_4_8 = 34, // removed from gguf files, use Q4_0 and runtime repack
180
- //LLAMA_FTYPE_MOSTLY_Q4_0_8_8 = 35, // removed from gguf files, use Q4_0 and runtime repack
181
- LLAMA_FTYPE_MOSTLY_TQ1_0 = 36, // except 1d tensors
182
- LLAMA_FTYPE_MOSTLY_TQ2_0 = 37, // except 1d tensors
183
-
184
- LLAMA_FTYPE_GUESSED = 1024, // not specified in the model file
185
- };
186
-
187
- enum llama_rope_scaling_type {
188
- LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED = -1,
189
- LLAMA_ROPE_SCALING_TYPE_NONE = 0,
190
- LLAMA_ROPE_SCALING_TYPE_LINEAR = 1,
191
- LLAMA_ROPE_SCALING_TYPE_YARN = 2,
192
- LLAMA_ROPE_SCALING_TYPE_LONGROPE = 3,
193
- LLAMA_ROPE_SCALING_TYPE_MAX_VALUE = LLAMA_ROPE_SCALING_TYPE_LONGROPE,
194
- };
195
-
196
- enum llama_pooling_type {
197
- LLAMA_POOLING_TYPE_UNSPECIFIED = -1,
198
- LLAMA_POOLING_TYPE_NONE = 0,
199
- LLAMA_POOLING_TYPE_MEAN = 1,
200
- LLAMA_POOLING_TYPE_CLS = 2,
201
- LLAMA_POOLING_TYPE_LAST = 3,
202
- LLAMA_POOLING_TYPE_RANK = 4, // used by reranking models to attach the classification head to the graph
203
- };
204
-
205
- enum llama_attention_type {
206
- LLAMA_ATTENTION_TYPE_UNSPECIFIED = -1,
207
- LLAMA_ATTENTION_TYPE_CAUSAL = 0,
208
- LLAMA_ATTENTION_TYPE_NON_CAUSAL = 1,
209
- };
210
-
211
- enum llama_split_mode {
212
- LLAMA_SPLIT_MODE_NONE = 0, // single GPU
213
- LLAMA_SPLIT_MODE_LAYER = 1, // split layers and KV across GPUs
214
- LLAMA_SPLIT_MODE_ROW = 2, // split layers and KV across GPUs, use tensor parallelism if supported
215
- };
216
-
217
- // TODO: simplify (https://github.com/ggerganov/llama.cpp/pull/9294#pullrequestreview-2286561979)
218
- typedef struct llama_token_data {
219
- llama_token id; // token id
220
- float logit; // log-odds of the token
221
- float p; // probability of the token
222
- } llama_token_data;
223
-
224
- typedef struct llama_token_data_array {
225
- // TODO: consider SoA
226
- // NOTE: this pointer can be modified by the samplers
227
- llama_token_data * data;
228
- size_t size;
229
- int64_t selected; // this is the index in the data array (i.e. not the token id)
230
- bool sorted;
231
- } llama_token_data_array;
232
-
233
- typedef bool (*llama_progress_callback)(float progress, void * user_data);
234
-
235
- // Input data for llama_decode
236
- // A llama_batch object can contain input about one or many sequences
237
- // The provided arrays (i.e. token, embd, pos, etc.) must have size of n_tokens
238
- //
239
- // - token : the token ids of the input (used when embd is NULL)
240
- // - embd : token embeddings (i.e. float vector of size n_embd) (used when token is NULL)
241
- // - pos : the positions of the respective token in the sequence
242
- // (if set to NULL, the token position will be tracked automatically by llama_decode)
243
- // - seq_id : the sequence to which the respective token belongs
244
- // (if set to NULL, the sequence ID will be assumed to be 0)
245
- // - logits : if zero, the logits (and/or the embeddings) for the respective token will not be output
246
- // (if set to NULL, only the logits for last token will be returned)
247
- //
248
- typedef struct llama_batch {
249
- int32_t n_tokens;
250
-
251
- llama_token * token;
252
- float * embd;
253
- llama_pos * pos;
254
- int32_t * n_seq_id;
255
- llama_seq_id ** seq_id;
256
- int8_t * logits; // TODO: rename this to "output"
257
- } llama_batch;
258
-
259
- enum llama_model_kv_override_type {
260
- LLAMA_KV_OVERRIDE_TYPE_INT,
261
- LLAMA_KV_OVERRIDE_TYPE_FLOAT,
262
- LLAMA_KV_OVERRIDE_TYPE_BOOL,
263
- LLAMA_KV_OVERRIDE_TYPE_STR,
264
- };
265
-
266
- struct llama_model_kv_override {
267
- enum llama_model_kv_override_type tag;
268
-
269
- char key[128];
270
-
271
- union {
272
- int64_t val_i64;
273
- double val_f64;
274
- bool val_bool;
275
- char val_str[128];
276
- };
277
- };
278
-
279
- struct llama_model_params {
280
- // NULL-terminated list of devices to use for offloading (if NULL, all available devices are used)
281
- lm_ggml_backend_dev_t * devices;
282
-
283
- int32_t n_gpu_layers; // number of layers to store in VRAM
284
- enum llama_split_mode split_mode; // how to split the model across multiple GPUs
285
-
286
- // the GPU that is used for the entire model when split_mode is LLAMA_SPLIT_MODE_NONE
287
- int32_t main_gpu;
288
-
289
- // proportion of the model (layers or rows) to offload to each GPU, size: llama_max_devices()
290
- const float * tensor_split;
291
-
292
- // comma separated list of RPC servers to use for offloading
293
- const char * rpc_servers;
294
-
295
- // Called with a progress value between 0.0 and 1.0. Pass NULL to disable.
296
- // If the provided progress_callback returns true, model loading continues.
297
- // If it returns false, model loading is immediately aborted.
298
- llama_progress_callback progress_callback;
299
-
300
- // context pointer passed to the progress callback
301
- void * progress_callback_user_data;
302
-
303
- // override key-value pairs of the model meta data
304
- const struct llama_model_kv_override * kv_overrides;
305
-
306
- // Keep the booleans together to avoid misalignment during copy-by-value.
307
- bool vocab_only; // only load the vocabulary, no weights
308
- bool use_mmap; // use mmap if possible
309
- bool use_mlock; // force system to keep model in RAM
310
- bool check_tensors; // validate model tensor data
311
- };
312
-
313
- // NOTE: changing the default values of parameters marked as [EXPERIMENTAL] may cause crashes or incorrect results in certain configurations
314
- // https://github.com/ggerganov/llama.cpp/pull/7544
315
- struct llama_context_params {
316
- uint32_t n_ctx; // text context, 0 = from model
317
- uint32_t n_batch; // logical maximum batch size that can be submitted to llama_decode
318
- uint32_t n_ubatch; // physical maximum batch size
319
- uint32_t n_seq_max; // max number of sequences (i.e. distinct states for recurrent models)
320
- int32_t n_threads; // number of threads to use for generation
321
- int32_t n_threads_batch; // number of threads to use for batch processing
322
-
323
- enum llama_rope_scaling_type rope_scaling_type; // RoPE scaling type, from `enum llama_rope_scaling_type`
324
- enum llama_pooling_type pooling_type; // whether to pool (sum) embedding results by sequence id
325
- enum llama_attention_type attention_type; // attention type to use for embeddings
326
-
327
- // ref: https://github.com/ggerganov/llama.cpp/pull/2054
328
- float rope_freq_base; // RoPE base frequency, 0 = from model
329
- float rope_freq_scale; // RoPE frequency scaling factor, 0 = from model
330
- float yarn_ext_factor; // YaRN extrapolation mix factor, negative = from model
331
- float yarn_attn_factor; // YaRN magnitude scaling factor
332
- float yarn_beta_fast; // YaRN low correction dim
333
- float yarn_beta_slow; // YaRN high correction dim
334
- uint32_t yarn_orig_ctx; // YaRN original context size
335
- float defrag_thold; // defragment the KV cache if holes/size > thold, < 0 disabled (default)
336
-
337
- lm_ggml_backend_sched_eval_callback cb_eval;
338
- void * cb_eval_user_data;
339
-
340
- enum lm_ggml_type type_k; // data type for K cache [EXPERIMENTAL]
341
- enum lm_ggml_type type_v; // data type for V cache [EXPERIMENTAL]
342
-
343
- // Keep the booleans together and at the end of the struct to avoid misalignment during copy-by-value.
344
- // TODO: move at the end of the struct
345
- bool logits_all; // the llama_decode() call computes all logits, not just the last one (DEPRECATED - set llama_batch.logits instead)
346
- bool embeddings; // if true, extract embeddings (together with logits)
347
- bool offload_kqv; // whether to offload the KQV ops (including the KV cache) to GPU
348
- bool flash_attn; // whether to use flash attention [EXPERIMENTAL]
349
- bool no_perf; // whether to measure performance timings
350
-
351
- // Abort callback
352
- // if it returns true, execution of llama_decode() will be aborted
353
- // currently works only with CPU execution
354
- lm_ggml_abort_callback abort_callback;
355
- void * abort_callback_data;
356
- };
357
-
358
- // model quantization parameters
359
- typedef struct llama_model_quantize_params {
360
- int32_t nthread; // number of threads to use for quantizing, if <=0 will use std::thread::hardware_concurrency()
361
- enum llama_ftype ftype; // quantize to this llama_ftype
362
- enum lm_ggml_type output_tensor_type; // output tensor type
363
- enum lm_ggml_type token_embedding_type; // token embeddings tensor type
364
- bool allow_requantize; // allow quantizing non-f32/f16 tensors
365
- bool quantize_output_tensor; // quantize output.weight
366
- bool only_copy; // only copy tensors - ftype, allow_requantize and quantize_output_tensor are ignored
367
- bool pure; // quantize all tensors to the default type
368
- bool keep_split; // quantize to the same number of shards
369
- void * imatrix; // pointer to importance matrix data
370
- void * kv_overrides; // pointer to vector containing overrides
371
- } llama_model_quantize_params;
372
-
373
- typedef struct llama_logit_bias {
374
- llama_token token;
375
- float bias;
376
- } llama_logit_bias;
377
-
378
- typedef struct llama_sampler_chain_params {
379
- bool no_perf; // whether to measure performance timings
380
- } llama_sampler_chain_params;
381
-
382
- // used in chat template
383
- typedef struct llama_chat_message {
384
- const char * role;
385
- const char * content;
386
- } llama_chat_message;
387
-
388
- // lora adapter
389
- // TODO: rename to llama_adapter_lora
390
- struct llama_lora_adapter;
391
-
392
- // Helpers for getting default parameters
393
- // TODO: update API to start accepting pointers to params structs (https://github.com/ggerganov/llama.cpp/discussions/9172)
394
- LLAMA_API struct llama_model_params llama_model_default_params(void);
395
- LLAMA_API struct llama_context_params llama_context_default_params(void);
396
- LLAMA_API struct llama_sampler_chain_params llama_sampler_chain_default_params(void);
397
- LLAMA_API struct llama_model_quantize_params llama_model_quantize_default_params(void);
398
-
399
- // Initialize the llama + ggml backend
400
- // If numa is true, use NUMA optimizations
401
- // Call once at the start of the program
402
- LLAMA_API void llama_backend_init(void);
403
-
404
- //optional:
405
- LLAMA_API void llama_numa_init(enum lm_ggml_numa_strategy numa);
406
-
407
- // Optional: an auto threadpool gets created in ggml if not passed explicitly
408
- LLAMA_API void llama_attach_threadpool(
409
- struct llama_context * ctx,
410
- lm_ggml_threadpool_t threadpool,
411
- lm_ggml_threadpool_t threadpool_batch);
412
- LLAMA_API void llama_detach_threadpool(struct llama_context * ctx);
413
-
414
- // Call once at the end of the program - currently only used for MPI
415
- LLAMA_API void llama_backend_free(void);
416
-
417
- DEPRECATED(LLAMA_API struct llama_model * llama_load_model_from_file(
418
- const char * path_model,
419
- struct llama_model_params params),
420
- "use llama_model_load_from_file instead");
421
-
422
- LLAMA_API struct llama_model * llama_model_load_from_file(
423
- const char * path_model,
424
- struct llama_model_params params);
425
-
426
- DEPRECATED(LLAMA_API void llama_free_model(struct llama_model * model),
427
- "use llama_model_free instead");
428
-
429
- LLAMA_API void llama_model_free(struct llama_model * model);
430
-
431
- // TODO: rename to llama_init_from_model
432
- LLAMA_API struct llama_context * llama_new_context_with_model(
433
- struct llama_model * model,
434
- struct llama_context_params params);
435
-
436
- // Frees all allocated memory
437
- LLAMA_API void llama_free(struct llama_context * ctx);
438
-
439
- LLAMA_API int64_t llama_time_us(void);
440
-
441
- LLAMA_API size_t llama_max_devices(void);
442
-
443
- LLAMA_API bool llama_supports_mmap (void);
444
- LLAMA_API bool llama_supports_mlock (void);
445
- LLAMA_API bool llama_supports_gpu_offload(void);
446
- LLAMA_API bool llama_supports_rpc (void);
447
-
448
- LLAMA_API uint32_t llama_n_ctx (const struct llama_context * ctx);
449
- LLAMA_API uint32_t llama_n_batch (const struct llama_context * ctx);
450
- LLAMA_API uint32_t llama_n_ubatch (const struct llama_context * ctx);
451
- LLAMA_API uint32_t llama_n_seq_max (const struct llama_context * ctx);
452
-
453
- LLAMA_API int32_t llama_n_vocab (const struct llama_model * model);
454
- LLAMA_API int32_t llama_n_ctx_train(const struct llama_model * model);
455
- LLAMA_API int32_t llama_n_embd (const struct llama_model * model);
456
- LLAMA_API int32_t llama_n_layer (const struct llama_model * model);
457
- LLAMA_API int32_t llama_n_head (const struct llama_model * model);
458
-
459
- LLAMA_API const struct llama_model * llama_get_model(const struct llama_context * ctx);
460
-
461
- LLAMA_API enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx);
462
- LLAMA_API enum llama_vocab_type llama_vocab_type (const struct llama_model * model);
463
- LLAMA_API enum llama_rope_type llama_rope_type (const struct llama_model * model);
464
-
465
- // Get the model's RoPE frequency scaling factor
466
- LLAMA_API float llama_rope_freq_scale_train(const struct llama_model * model);
467
-
468
- // Functions to access the model's GGUF metadata scalar values
469
- // - The functions return the length of the string on success, or -1 on failure
470
- // - The output string is always null-terminated and cleared on failure
471
- // - When retrieving a string, an extra byte must be allocated to account for the null terminator
472
- // - GGUF array values are not supported by these functions
473
-
474
- // Get metadata value as a string by key name
475
- LLAMA_API int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size);
476
-
477
- // Get the number of metadata key/value pairs
478
- LLAMA_API int32_t llama_model_meta_count(const struct llama_model * model);
479
-
480
- // Get metadata key name by index
481
- LLAMA_API int32_t llama_model_meta_key_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size);
482
-
483
- // Get metadata value as a string by index
484
- 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);
485
-
486
- // Get a string describing the model type
487
- LLAMA_API int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size);
488
-
489
- // Returns the total size of all the tensors in the model in bytes
490
- LLAMA_API uint64_t llama_model_size(const struct llama_model * model);
491
-
492
- // Returns the total number of parameters in the model
493
- LLAMA_API uint64_t llama_model_n_params(const struct llama_model * model);
494
-
495
- // Returns true if the model contains an encoder that requires llama_encode() call
496
- LLAMA_API bool llama_model_has_encoder(const struct llama_model * model);
497
-
498
- // Returns true if the model contains a decoder that requires llama_decode() call
499
- LLAMA_API bool llama_model_has_decoder(const struct llama_model * model);
500
-
501
- // For encoder-decoder models, this function returns id of the token that must be provided
502
- // to the decoder to start generating output sequence. For other models, it returns -1.
503
- LLAMA_API llama_token llama_model_decoder_start_token(const struct llama_model * model);
504
-
505
- // Returns true if the model is recurrent (like Mamba, RWKV, etc.)
506
- LLAMA_API bool llama_model_is_recurrent(const struct llama_model * model);
507
-
508
- // Returns 0 on success
509
- LLAMA_API uint32_t llama_model_quantize(
510
- const char * fname_inp,
511
- const char * fname_out,
512
- const llama_model_quantize_params * params);
513
-
514
- //
515
- // Adapters
516
- //
517
-
518
- // Load a LoRA adapter from file
519
- // TODO: rename to llama_adapter_lora_init
520
- LLAMA_API struct llama_lora_adapter * llama_lora_adapter_init(
521
- struct llama_model * model,
522
- const char * path_lora);
523
-
524
- // Add a loaded LoRA adapter to given context
525
- // This will not modify model's weight
526
- // TODO: rename to llama_set_adapter_lora
527
- LLAMA_API int32_t llama_lora_adapter_set(
528
- struct llama_context * ctx,
529
- struct llama_lora_adapter * adapter,
530
- float scale);
531
-
532
- // Remove a specific LoRA adapter from given context
533
- // Return -1 if the adapter is not present in the context
534
- // TODO: rename to llama_rm_adapter_lora
535
- LLAMA_API int32_t llama_lora_adapter_remove(
536
- struct llama_context * ctx,
537
- struct llama_lora_adapter * adapter);
538
-
539
- // Remove all LoRA adapters from given context
540
- // TODO: rename to llama_clear_adapter_lora
541
- LLAMA_API void llama_lora_adapter_clear(struct llama_context * ctx);
542
-
543
- // Manually free a LoRA adapter
544
- // Note: loaded adapters will be free when the associated model is deleted
545
- // TODO: rename to llama_adapter_lora_free
546
- LLAMA_API void llama_lora_adapter_free(struct llama_lora_adapter * adapter);
547
-
548
- // Apply a loaded control vector to a llama_context, or if data is NULL, clear
549
- // the currently loaded vector.
550
- // n_embd should be the size of a single layer's control, and data should point
551
- // to an n_embd x n_layers buffer starting from layer 1.
552
- // il_start and il_end are the layer range the vector should apply to (both inclusive)
553
- // See llama_control_vector_load in common to load a control vector.
554
- // TODO: rename to llama_adapter_cvec_apply
555
- LLAMA_API int32_t llama_control_vector_apply(
556
- struct llama_context * lctx,
557
- const float * data,
558
- size_t len,
559
- int32_t n_embd,
560
- int32_t il_start,
561
- int32_t il_end);
562
-
563
- //
564
- // KV cache
565
- //
566
-
567
- // TODO: remove llama_kv_cache_view_* API
568
-
569
- // Information associated with an individual cell in the KV cache view.
570
- struct llama_kv_cache_view_cell {
571
- // The position for this cell. Takes KV cache shifts into account.
572
- // May be negative if the cell is not populated.
573
- llama_pos pos;
574
- };
575
-
576
- // An updateable view of the KV cache.
577
- struct llama_kv_cache_view {
578
- // Number of KV cache cells. This will be the same as the context size.
579
- int32_t n_cells;
580
-
581
- // Maximum number of sequences that can exist in a cell. It's not an error
582
- // if there are more sequences in a cell than this value, however they will
583
- // not be visible in the view cells_sequences.
584
- int32_t n_seq_max;
585
-
586
- // Number of tokens in the cache. For example, if there are two populated
587
- // cells, the first with 1 sequence id in it and the second with 2 sequence
588
- // ids then you'll have 3 tokens.
589
- int32_t token_count;
590
-
591
- // Number of populated cache cells.
592
- int32_t used_cells;
593
-
594
- // Maximum contiguous empty slots in the cache.
595
- int32_t max_contiguous;
596
-
597
- // Index to the start of the max_contiguous slot range. Can be negative
598
- // when cache is full.
599
- int32_t max_contiguous_idx;
600
-
601
- // Information for an individual cell.
602
- struct llama_kv_cache_view_cell * cells;
603
-
604
- // The sequences for each cell. There will be n_seq_max items per cell.
605
- llama_seq_id * cells_sequences;
606
- };
607
-
608
- // Create an empty KV cache view. (use only for debugging purposes)
609
- LLAMA_API struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max);
610
-
611
- // Free a KV cache view. (use only for debugging purposes)
612
- LLAMA_API void llama_kv_cache_view_free(struct llama_kv_cache_view * view);
613
-
614
- // Update the KV cache view structure with the current state of the KV cache. (use only for debugging purposes)
615
- // TODO: change signature to llama_kv_cache_view_update(struct llama_kv_cache_view * view, const struct llama_context * ctx)
616
- LLAMA_API void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view);
617
-
618
- ///
619
-
620
- // Returns the number of tokens in the KV cache (slow, use only for debug)
621
- // If a KV cell has multiple sequences assigned to it, it will be counted multiple times
622
- LLAMA_API int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx);
623
-
624
- // Returns the number of used KV cells (i.e. have at least one sequence assigned to them)
625
- LLAMA_API int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx);
626
-
627
- // Clear the KV cache - both cell info is erased and KV data is zeroed
628
- LLAMA_API void llama_kv_cache_clear(
629
- struct llama_context * ctx);
630
-
631
- // Removes all tokens that belong to the specified sequence and have positions in [p0, p1)
632
- // Returns false if a partial sequence cannot be removed. Removing a whole sequence never fails
633
- // seq_id < 0 : match any sequence
634
- // p0 < 0 : [0, p1]
635
- // p1 < 0 : [p0, inf)
636
- LLAMA_API bool llama_kv_cache_seq_rm(
637
- struct llama_context * ctx,
638
- llama_seq_id seq_id,
639
- llama_pos p0,
640
- llama_pos p1);
641
-
642
- // Copy all tokens that belong to the specified sequence to another sequence
643
- // Note that this does not allocate extra KV cache memory - it simply assigns the tokens to the new sequence
644
- // p0 < 0 : [0, p1]
645
- // p1 < 0 : [p0, inf)
646
- LLAMA_API void llama_kv_cache_seq_cp(
647
- struct llama_context * ctx,
648
- llama_seq_id seq_id_src,
649
- llama_seq_id seq_id_dst,
650
- llama_pos p0,
651
- llama_pos p1);
652
-
653
- // Removes all tokens that do not belong to the specified sequence
654
- LLAMA_API void llama_kv_cache_seq_keep(
655
- struct llama_context * ctx,
656
- llama_seq_id seq_id);
657
-
658
- // Adds relative position "delta" to all tokens that belong to the specified sequence and have positions in [p0, p1)
659
- // If the KV cache is RoPEd, the KV data is updated accordingly:
660
- // - lazily on next llama_decode()
661
- // - explicitly with llama_kv_cache_update()
662
- // p0 < 0 : [0, p1]
663
- // p1 < 0 : [p0, inf)
664
- LLAMA_API void llama_kv_cache_seq_add(
665
- struct llama_context * ctx,
666
- llama_seq_id seq_id,
667
- llama_pos p0,
668
- llama_pos p1,
669
- llama_pos delta);
670
-
671
- // Integer division of the positions by factor of `d > 1`
672
- // If the KV cache is RoPEd, the KV data is updated accordingly:
673
- // - lazily on next llama_decode()
674
- // - explicitly with llama_kv_cache_update()
675
- // p0 < 0 : [0, p1]
676
- // p1 < 0 : [p0, inf)
677
- LLAMA_API void llama_kv_cache_seq_div(
678
- struct llama_context * ctx,
679
- llama_seq_id seq_id,
680
- llama_pos p0,
681
- llama_pos p1,
682
- int d);
683
-
684
- // Returns the largest position present in the KV cache for the specified sequence
685
- LLAMA_API llama_pos llama_kv_cache_seq_pos_max(
686
- struct llama_context * ctx,
687
- llama_seq_id seq_id);
688
-
689
- // TODO: the llama_kv_cache_defrag and llama_kv_cache_update API tightly couples llama_context with llama_kv_cache
690
- // how to avoid this?
691
-
692
- // Defragment the KV cache
693
- // This will be applied:
694
- // - lazily on next llama_decode()
695
- // - explicitly with llama_kv_cache_update()
696
- LLAMA_API void llama_kv_cache_defrag(struct llama_context * ctx);
697
-
698
- // Apply the KV cache updates (such as K-shifts, defragmentation, etc.)
699
- LLAMA_API void llama_kv_cache_update(struct llama_context * ctx);
700
-
701
- // Check if the context supports KV cache shifting
702
- LLAMA_API bool llama_kv_cache_can_shift(struct llama_context * ctx);
703
-
704
- //
705
- // State / sessions
706
- //
707
-
708
- // Returns the *actual* size in bytes of the state
709
- // (logits, embedding and kv_cache)
710
- // Only use when saving the state, not when restoring it, otherwise the size may be too small.
711
- LLAMA_API size_t llama_state_get_size(struct llama_context * ctx);
712
- LLAMA_API DEPRECATED(size_t llama_get_state_size(struct llama_context * ctx),
713
- "use llama_state_get_size instead");
714
-
715
- // Copies the state to the specified destination address.
716
- // Destination needs to have allocated enough memory.
717
- // Returns the number of bytes copied
718
- LLAMA_API size_t llama_state_get_data(
719
- struct llama_context * ctx,
720
- uint8_t * dst,
721
- size_t size);
722
- LLAMA_API DEPRECATED(size_t llama_copy_state_data(
723
- struct llama_context * ctx,
724
- uint8_t * dst),
725
- "use llama_state_get_data instead");
726
-
727
- // Set the state reading from the specified address
728
- // Returns the number of bytes read
729
- LLAMA_API size_t llama_state_set_data(
730
- struct llama_context * ctx,
731
- const uint8_t * src,
732
- size_t size);
733
- LLAMA_API DEPRECATED(size_t llama_set_state_data(
734
- struct llama_context * ctx,
735
- const uint8_t * src),
736
- "use llama_state_set_data instead");
737
-
738
- // Save/load session file
739
- LLAMA_API bool llama_state_load_file(
740
- struct llama_context * ctx,
741
- const char * path_session,
742
- llama_token * tokens_out,
743
- size_t n_token_capacity,
744
- size_t * n_token_count_out);
745
- LLAMA_API DEPRECATED(bool llama_load_session_file(
746
- struct llama_context * ctx,
747
- const char * path_session,
748
- llama_token * tokens_out,
749
- size_t n_token_capacity,
750
- size_t * n_token_count_out),
751
- "use llama_state_load_file instead");
752
-
753
- LLAMA_API bool llama_state_save_file(
754
- struct llama_context * ctx,
755
- const char * path_session,
756
- const llama_token * tokens,
757
- size_t n_token_count);
758
- LLAMA_API DEPRECATED(bool llama_save_session_file(
759
- struct llama_context * ctx,
760
- const char * path_session,
761
- const llama_token * tokens,
762
- size_t n_token_count),
763
- "use llama_state_save_file instead");
764
-
765
- // Get the exact size needed to copy the KV cache of a single sequence
766
- LLAMA_API size_t llama_state_seq_get_size(
767
- struct llama_context * ctx,
768
- llama_seq_id seq_id);
769
-
770
- // Copy the KV cache of a single sequence into the specified buffer
771
- LLAMA_API size_t llama_state_seq_get_data(
772
- struct llama_context * ctx,
773
- uint8_t * dst,
774
- size_t size,
775
- llama_seq_id seq_id);
776
-
777
- // Copy the sequence data (originally copied with `llama_state_seq_get_data`) into the specified sequence
778
- // Returns:
779
- // - Positive: Ok
780
- // - Zero: Failed to load
781
- LLAMA_API size_t llama_state_seq_set_data(
782
- struct llama_context * ctx,
783
- const uint8_t * src,
784
- size_t size,
785
- llama_seq_id dest_seq_id);
786
-
787
- LLAMA_API size_t llama_state_seq_save_file(
788
- struct llama_context * ctx,
789
- const char * filepath,
790
- llama_seq_id seq_id,
791
- const llama_token * tokens,
792
- size_t n_token_count);
793
-
794
- LLAMA_API size_t llama_state_seq_load_file(
795
- struct llama_context * ctx,
796
- const char * filepath,
797
- llama_seq_id dest_seq_id,
798
- llama_token * tokens_out,
799
- size_t n_token_capacity,
800
- size_t * n_token_count_out);
801
-
802
- //
803
- // Decoding
804
- //
805
-
806
- // Return batch for single sequence of tokens
807
- // The sequence ID will be fixed to 0
808
- // The position of the tokens will be tracked automatically by llama_decode
809
- //
810
- // NOTE: this is a helper function to facilitate transition to the new batch API - avoid using it
811
- //
812
- LLAMA_API struct llama_batch llama_batch_get_one(
813
- llama_token * tokens,
814
- int32_t n_tokens);
815
-
816
- // Allocates a batch of tokens on the heap that can hold a maximum of n_tokens
817
- // Each token can be assigned up to n_seq_max sequence ids
818
- // The batch has to be freed with llama_batch_free()
819
- // If embd != 0, llama_batch.embd will be allocated with size of n_tokens * embd * sizeof(float)
820
- // Otherwise, llama_batch.token will be allocated to store n_tokens llama_token
821
- // The rest of the llama_batch members are allocated with size n_tokens
822
- // All members are left uninitialized
823
- LLAMA_API struct llama_batch llama_batch_init(
824
- int32_t n_tokens,
825
- int32_t embd,
826
- int32_t n_seq_max);
827
-
828
- // Frees a batch of tokens allocated with llama_batch_init()
829
- LLAMA_API void llama_batch_free(struct llama_batch batch);
830
-
831
- // Processes a batch of tokens with the ecoder part of the encoder-decoder model.
832
- // Stores the encoder output internally for later use by the decoder cross-attention layers.
833
- // 0 - success
834
- // < 0 - error. the KV cache state is restored to the state before this call
835
- LLAMA_API int32_t llama_encode(
836
- struct llama_context * ctx,
837
- struct llama_batch batch);
838
-
839
- // Positive return values does not mean a fatal error, but rather a warning.
840
- // 0 - success
841
- // 1 - could not find a KV slot for the batch (try reducing the size of the batch or increase the context)
842
- // < 0 - error. the KV cache state is restored to the state before this call
843
- LLAMA_API int32_t llama_decode(
844
- struct llama_context * ctx,
845
- struct llama_batch batch);
846
-
847
- // Set the number of threads used for decoding
848
- // n_threads is the number of threads used for generation (single token)
849
- // n_threads_batch is the number of threads used for prompt and batch processing (multiple tokens)
850
- LLAMA_API void llama_set_n_threads(struct llama_context * ctx, int32_t n_threads, int32_t n_threads_batch);
851
-
852
- // Get the number of threads used for generation of a single token.
853
- LLAMA_API int32_t llama_n_threads(struct llama_context * ctx);
854
-
855
- // Get the number of threads used for prompt and batch processing (multiple token).
856
- LLAMA_API int32_t llama_n_threads_batch(struct llama_context * ctx);
857
-
858
- // Set whether the model is in embeddings mode or not
859
- // If true, embeddings will be returned but logits will not
860
- LLAMA_API void llama_set_embeddings(struct llama_context * ctx, bool embeddings);
861
-
862
- // Set whether to use causal attention or not
863
- // If set to true, the model will only attend to the past tokens
864
- LLAMA_API void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn);
865
-
866
- // Set abort callback
867
- LLAMA_API void llama_set_abort_callback(struct llama_context * ctx, lm_ggml_abort_callback abort_callback, void * abort_callback_data);
868
-
869
- // Wait until all computations are finished
870
- // This is automatically done when using one of the functions below to obtain the computation results
871
- // and is not necessary to call it explicitly in most cases
872
- LLAMA_API void llama_synchronize(struct llama_context * ctx);
873
-
874
- // Token logits obtained from the last call to llama_decode()
875
- // The logits for which llama_batch.logits[i] != 0 are stored contiguously
876
- // in the order they have appeared in the batch.
877
- // Rows: number of tokens for which llama_batch.logits[i] != 0
878
- // Cols: n_vocab
879
- LLAMA_API float * llama_get_logits(struct llama_context * ctx);
880
-
881
- // Logits for the ith token. For positive indices, Equivalent to:
882
- // llama_get_logits(ctx) + ctx->output_ids[i]*n_vocab
883
- // Negative indicies can be used to access logits in reverse order, -1 is the last logit.
884
- // returns NULL for invalid ids.
885
- LLAMA_API float * llama_get_logits_ith(struct llama_context * ctx, int32_t i);
886
-
887
- // Get all output token embeddings.
888
- // when pooling_type == LLAMA_POOLING_TYPE_NONE or when using a generative model,
889
- // the embeddings for which llama_batch.logits[i] != 0 are stored contiguously
890
- // in the order they have appeared in the batch.
891
- // shape: [n_outputs*n_embd]
892
- // Otherwise, returns NULL.
893
- LLAMA_API float * llama_get_embeddings(struct llama_context * ctx);
894
-
895
- // Get the embeddings for the ith token. For positive indices, Equivalent to:
896
- // llama_get_embeddings(ctx) + ctx->output_ids[i]*n_embd
897
- // Negative indicies can be used to access embeddings in reverse order, -1 is the last embedding.
898
- // shape: [n_embd] (1-dimensional)
899
- // returns NULL for invalid ids.
900
- LLAMA_API float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i);
901
-
902
- // Get the embeddings for a sequence id
903
- // Returns NULL if pooling_type is LLAMA_POOLING_TYPE_NONE
904
- // when pooling_type == LLAMA_POOLING_TYPE_RANK, returns float[1] with the rank of the sequence
905
- // otherwise: float[n_embd] (1-dimensional)
906
- LLAMA_API float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id);
907
-
908
- //
909
- // Vocab
910
- //
911
-
912
- LLAMA_API const char * llama_token_get_text(const struct llama_model * model, llama_token token);
913
-
914
- LLAMA_API float llama_token_get_score(const struct llama_model * model, llama_token token);
915
-
916
- LLAMA_API enum llama_token_attr llama_token_get_attr(const struct llama_model * model, llama_token token);
917
-
918
- // Check if the token is supposed to end generation (end-of-generation, eg. EOS, EOT, etc.)
919
- LLAMA_API bool llama_token_is_eog(const struct llama_model * model, llama_token token);
920
-
921
- // Identify if Token Id is a control token or a render-able token
922
- LLAMA_API bool llama_token_is_control(const struct llama_model * model, llama_token token);
923
-
924
- // Special tokens
925
- LLAMA_API llama_token llama_token_bos(const struct llama_model * model); // beginning-of-sentence
926
- LLAMA_API llama_token llama_token_eos(const struct llama_model * model); // end-of-sentence
927
- LLAMA_API llama_token llama_token_eot(const struct llama_model * model); // end-of-turn
928
- LLAMA_API llama_token llama_token_cls(const struct llama_model * model); // classification
929
- LLAMA_API llama_token llama_token_sep(const struct llama_model * model); // sentence separator
930
- LLAMA_API llama_token llama_token_nl (const struct llama_model * model); // next-line
931
- LLAMA_API llama_token llama_token_pad(const struct llama_model * model); // padding
932
-
933
- LLAMA_API bool llama_add_bos_token(const struct llama_model * model);
934
- LLAMA_API bool llama_add_eos_token(const struct llama_model * model);
935
-
936
- // infill tokens
937
- DEPRECATED(LLAMA_API llama_token llama_token_prefix(const struct llama_model * model), "use llama_token_fim_pre instead");
938
- DEPRECATED(LLAMA_API llama_token llama_token_middle(const struct llama_model * model), "use llama_token_fim_mid instead");
939
- DEPRECATED(LLAMA_API llama_token llama_token_suffix(const struct llama_model * model), "use llama_token_fim_suf instead");
940
-
941
- LLAMA_API llama_token llama_token_fim_pre(const struct llama_model * model);
942
- LLAMA_API llama_token llama_token_fim_suf(const struct llama_model * model);
943
- LLAMA_API llama_token llama_token_fim_mid(const struct llama_model * model);
944
- LLAMA_API llama_token llama_token_fim_pad(const struct llama_model * model);
945
- LLAMA_API llama_token llama_token_fim_rep(const struct llama_model * model);
946
- LLAMA_API llama_token llama_token_fim_sep(const struct llama_model * model);
947
-
948
- //
949
- // Tokenization
950
- //
951
- // The API is thread-safe.
952
- //
953
-
954
- /// @details Convert the provided text into tokens.
955
- /// @param tokens The tokens pointer must be large enough to hold the resulting tokens.
956
- /// @return Returns the number of tokens on success, no more than n_tokens_max
957
- /// @return Returns a negative number on failure - the number of tokens that would have been returned
958
- /// @param add_special Allow to add BOS and EOS tokens if model is configured to do so.
959
- /// @param parse_special Allow tokenizing special and/or control tokens which otherwise are not exposed and treated
960
- /// as plaintext. Does not insert a leading space.
961
- LLAMA_API int32_t llama_tokenize(
962
- const struct llama_model * model,
963
- const char * text,
964
- int32_t text_len,
965
- llama_token * tokens,
966
- int32_t n_tokens_max,
967
- bool add_special,
968
- bool parse_special);
969
-
970
- // Token Id -> Piece.
971
- // Uses the vocabulary in the provided context.
972
- // Does not write null terminator to the buffer.
973
- // User can skip up to 'lstrip' leading spaces before copying (useful when encoding/decoding multiple tokens with 'add_space_prefix')
974
- // @param special If true, special tokens are rendered in the output.
975
- LLAMA_API int32_t llama_token_to_piece(
976
- const struct llama_model * model,
977
- llama_token token,
978
- char * buf,
979
- int32_t length,
980
- int32_t lstrip,
981
- bool special);
982
-
983
- /// @details Convert the provided tokens into text (inverse of llama_tokenize()).
984
- /// @param text The char pointer must be large enough to hold the resulting text.
985
- /// @return Returns the number of chars/bytes on success, no more than text_len_max.
986
- /// @return Returns a negative number on failure - the number of chars/bytes that would have been returned.
987
- /// @param remove_special Allow to remove BOS and EOS tokens if model is configured to do so.
988
- /// @param unparse_special If true, special tokens are rendered in the output.
989
- LLAMA_API int32_t llama_detokenize(
990
- const struct llama_model * model,
991
- const llama_token * tokens,
992
- int32_t n_tokens,
993
- char * text,
994
- int32_t text_len_max,
995
- bool remove_special,
996
- bool unparse_special);
997
-
998
- //
999
- // Chat templates
1000
- //
1001
-
1002
- /// Apply chat template. Inspired by hf apply_chat_template() on python.
1003
- /// Both "model" and "custom_template" are optional, but at least one is required. "custom_template" has higher precedence than "model"
1004
- /// 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
1005
- /// @param tmpl A Jinja template to use for this chat. If this is nullptr, the model’s default chat template will be used instead.
1006
- /// @param chat Pointer to a list of multiple llama_chat_message
1007
- /// @param n_msg Number of llama_chat_message in this chat
1008
- /// @param add_ass Whether to end the prompt with the token(s) that indicate the start of an assistant message.
1009
- /// @param buf A buffer to hold the output formatted prompt. The recommended alloc size is 2 * (total number of characters of all messages)
1010
- /// @param length The size of the allocated buffer
1011
- /// @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.
1012
- LLAMA_API int32_t llama_chat_apply_template(
1013
- const struct llama_model * model,
1014
- const char * tmpl,
1015
- const struct llama_chat_message * chat,
1016
- size_t n_msg,
1017
- bool add_ass,
1018
- char * buf,
1019
- int32_t length);
1020
-
1021
- // Get list of built-in chat templates
1022
- LLAMA_API int32_t llama_chat_builtin_templates(const char ** output, size_t len);
1023
-
1024
- //
1025
- // Sampling API
1026
- //
1027
- // Sample usage:
1028
- //
1029
- // // prepare the sampling chain at the start
1030
- // auto sparams = llama_sampler_chain_default_params();
1031
- //
1032
- // llama_sampler * smpl = llama_sampler_chain_init(sparams);
1033
- //
1034
- // llama_sampler_chain_add(smpl, llama_sampler_init_top_k(50));
1035
- // llama_sampler_chain_add(smpl, llama_sampler_init_top_p(0.9, 1));
1036
- // llama_sampler_chain_add(smpl, llama_sampler_init_temp (0.8));
1037
- //
1038
- // // typically, the chain should end with a sampler such as "greedy", "dist" or "mirostat"
1039
- // // this sampler will be responsible to select the actual token
1040
- // llama_sampler_chain_add(smpl, llama_sampler_init_dist(seed));
1041
- //
1042
- // ...
1043
- //
1044
- // // decoding loop:
1045
- // while (...) {
1046
- // ...
1047
- //
1048
- // llama_decode(ctx, batch);
1049
- //
1050
- // // sample from the logits of the last token in the batch
1051
- // const llama_token id = llama_sampler_sample(smpl, ctx, -1);
1052
- //
1053
- // // accepting the token updates the internal state of certain samplers (e.g. grammar, repetition, etc.)
1054
- // llama_sampler_accept(smpl, id);
1055
- // ...
1056
- // }
1057
- //
1058
- // llama_sampler_free(smpl);
1059
- //
1060
- // TODO: In the future, llama_sampler will be utilized to offload the sampling to the backends (e.g. GPU).
1061
- // TODO: in the future, the entire sampling API that uses llama_model should start using llama_vocab
1062
- //
1063
-
1064
- typedef void * llama_sampler_context_t;
1065
-
1066
- // user code can implement the interface below in order to create custom llama_sampler
1067
- struct llama_sampler_i {
1068
- const char * (*name) (const struct llama_sampler * smpl); // can be NULL
1069
- void (*accept)( struct llama_sampler * smpl, llama_token token); // can be NULL
1070
- void (*apply) ( struct llama_sampler * smpl, llama_token_data_array * cur_p); // required
1071
- void (*reset) ( struct llama_sampler * smpl); // can be NULL
1072
- struct llama_sampler * (*clone) (const struct llama_sampler * smpl); // can be NULL if ctx is NULL
1073
- void (*free) ( struct llama_sampler * smpl); // can be NULL if ctx is NULL
1074
-
1075
- // TODO: API for internal libllama usage for appending the sampling to an existing lm_ggml_cgraph
1076
- //void (*apply_ggml) (struct llama_sampler * smpl, ...);
1077
- };
1078
-
1079
- struct llama_sampler {
1080
- struct llama_sampler_i * iface;
1081
- llama_sampler_context_t ctx;
1082
- };
1083
-
1084
- // mirror of llama_sampler_i:
1085
- LLAMA_API const char * llama_sampler_name (const struct llama_sampler * smpl);
1086
- LLAMA_API void llama_sampler_accept( struct llama_sampler * smpl, llama_token token);
1087
- LLAMA_API void llama_sampler_apply ( struct llama_sampler * smpl, llama_token_data_array * cur_p);
1088
- LLAMA_API void llama_sampler_reset ( struct llama_sampler * smpl);
1089
- LLAMA_API struct llama_sampler * llama_sampler_clone (const struct llama_sampler * smpl);
1090
- // important: do not free if the sampler has been added to a llama_sampler_chain (via llama_sampler_chain_add)
1091
- LLAMA_API void llama_sampler_free ( struct llama_sampler * smpl);
1092
-
1093
- // llama_sampler_chain
1094
- // a type of llama_sampler that can chain multiple samplers one after another
1095
-
1096
- LLAMA_API struct llama_sampler * llama_sampler_chain_init(struct llama_sampler_chain_params params);
1097
-
1098
- // important: takes ownership of the sampler object and will free it when llama_sampler_free is called
1099
- LLAMA_API void llama_sampler_chain_add( struct llama_sampler * chain, struct llama_sampler * smpl);
1100
- LLAMA_API struct llama_sampler * llama_sampler_chain_get(const struct llama_sampler * chain, int32_t i);
1101
- LLAMA_API int llama_sampler_chain_n (const struct llama_sampler * chain);
1102
-
1103
- // after removing a sampler, the chain will no longer own it, and it will not be freed when the chain is freed
1104
- LLAMA_API struct llama_sampler * llama_sampler_chain_remove( struct llama_sampler * chain, int32_t i);
1105
-
1106
- // available samplers:
1107
-
1108
- LLAMA_API struct llama_sampler * llama_sampler_init_greedy(void);
1109
- LLAMA_API struct llama_sampler * llama_sampler_init_dist (uint32_t seed);
1110
-
1111
- /// @details Sorts candidate tokens by their logits in descending order and calculate probabilities based on logits.
1112
- /// NOTE: Avoid using on the full vocabulary as the sorting can become slow. For example, apply top-k or top-p sampling first.
1113
- DEPRECATED(LLAMA_API struct llama_sampler * llama_sampler_init_softmax (void),
1114
- "will be removed in the future (see https://github.com/ggerganov/llama.cpp/pull/9896#discussion_r1800920915)");
1115
-
1116
- /// @details Top-K sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
1117
- LLAMA_API struct llama_sampler * llama_sampler_init_top_k (int32_t k);
1118
-
1119
- /// @details Nucleus sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
1120
- LLAMA_API struct llama_sampler * llama_sampler_init_top_p (float p, size_t min_keep);
1121
-
1122
- /// @details Minimum P sampling as described in https://github.com/ggerganov/llama.cpp/pull/3841
1123
- LLAMA_API struct llama_sampler * llama_sampler_init_min_p (float p, size_t min_keep);
1124
-
1125
- /// @details Locally Typical Sampling implementation described in the paper https://arxiv.org/abs/2202.00666.
1126
- LLAMA_API struct llama_sampler * llama_sampler_init_typical (float p, size_t min_keep);
1127
-
1128
- /// #details Updates the logits l_i` = l_i/t. When t <= 0.0f, the maximum logit is kept at it's original value, the rest are set to -inf
1129
- LLAMA_API struct llama_sampler * llama_sampler_init_temp (float t);
1130
-
1131
- /// @details Dynamic temperature implementation (a.k.a. entropy) described in the paper https://arxiv.org/abs/2309.02772.
1132
- LLAMA_API struct llama_sampler * llama_sampler_init_temp_ext (float t, float delta, float exponent);
1133
-
1134
- /// @details XTC sampler as described in https://github.com/oobabooga/text-generation-webui/pull/6335
1135
- LLAMA_API struct llama_sampler * llama_sampler_init_xtc (float p, float t, size_t min_keep, uint32_t seed);
1136
-
1137
- /// @details Mirostat 1.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
1138
- /// @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.
1139
- /// @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.
1140
- /// @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.
1141
- /// @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.
1142
- /// @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.
1143
- LLAMA_API struct llama_sampler * llama_sampler_init_mirostat(
1144
- int32_t n_vocab,
1145
- uint32_t seed,
1146
- float tau,
1147
- float eta,
1148
- int32_t m);
1149
-
1150
- /// @details Mirostat 2.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
1151
- /// @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.
1152
- /// @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.
1153
- /// @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.
1154
- /// @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.
1155
- LLAMA_API struct llama_sampler * llama_sampler_init_mirostat_v2(
1156
- uint32_t seed,
1157
- float tau,
1158
- float eta);
1159
-
1160
- LLAMA_API struct llama_sampler * llama_sampler_init_grammar(
1161
- const struct llama_model * model,
1162
- const char * grammar_str,
1163
- const char * grammar_root);
1164
-
1165
- /// NOTE: Avoid using on the full vocabulary as searching for repeated tokens can become slow. For example, apply top-k or top-p sampling first.
1166
- LLAMA_API struct llama_sampler * llama_sampler_init_penalties(
1167
- int32_t penalty_last_n, // last n tokens to penalize (0 = disable penalty, -1 = context size)
1168
- float penalty_repeat, // 1.0 = disabled
1169
- float penalty_freq, // 0.0 = disabled
1170
- float penalty_present); // 0.0 = disabled
1171
-
1172
- /// @details DRY sampler, designed by p-e-w, as described in: https://github.com/oobabooga/text-generation-webui/pull/5677, porting Koboldcpp implementation authored by pi6am: https://github.com/LostRuins/koboldcpp/pull/982
1173
- LLAMA_API struct llama_sampler * llama_sampler_init_dry(
1174
- const struct llama_model * model,
1175
- float dry_multiplier,
1176
- float dry_base,
1177
- int32_t dry_allowed_length,
1178
- int32_t dry_penalty_last_n,
1179
- const char ** seq_breakers,
1180
- size_t num_breakers);
1181
-
1182
- LLAMA_API struct llama_sampler * llama_sampler_init_logit_bias(
1183
- int32_t n_vocab,
1184
- int32_t n_logit_bias,
1185
- const llama_logit_bias * logit_bias);
1186
-
1187
- // this sampler is meant to be used for fill-in-the-middle infilling
1188
- // it's supposed to be used after top_k + top_p sampling
1189
- //
1190
- // 1. if the sum of the EOG probs times the number of candidates is higher than the sum of the other probs -> pick EOG
1191
- // 2. combine probs of tokens that have the same prefix
1192
- //
1193
- // example:
1194
- //
1195
- // - before:
1196
- // "hel": 0.5
1197
- // "hell": 0.2
1198
- // "hello": 0.1
1199
- // "dummy": 0.1
1200
- //
1201
- // - after:
1202
- // "hel": 0.8
1203
- // "dummy": 0.1
1204
- //
1205
- // 3. discard non-EOG tokens with low prob
1206
- // 4. if no tokens are left -> pick EOT
1207
- //
1208
- LLAMA_API struct llama_sampler * llama_sampler_init_infill(const struct llama_model * model);
1209
-
1210
- // Returns the seed used by the sampler if applicable, LLAMA_DEFAULT_SEED otherwise
1211
- LLAMA_API uint32_t llama_sampler_get_seed(const struct llama_sampler * smpl);
1212
-
1213
- /// @details Sample and accept a token from the idx-th output of the last evaluation
1214
- //
1215
- // Shorthand for:
1216
- // const auto * logits = llama_get_logits_ith(ctx, idx);
1217
- // llama_token_data_array cur_p = { ... init from logits ... };
1218
- // llama_sampler_apply(smpl, &cur_p);
1219
- // auto token = cur_p.data[cur_p.selected].id;
1220
- // llama_sampler_accept(smpl, token);
1221
- // return token;
1222
- // Returns the sampled token
1223
- LLAMA_API llama_token llama_sampler_sample(struct llama_sampler * smpl, struct llama_context * ctx, int32_t idx);
1224
-
1225
- // TODO: extend in the future
1226
- //LLAMA_API void llama_decode_with_sampler(struct llama_context * ctx, struct llama_sampler * smpl, struct llama_batch batch, ...);
1227
-
1228
- //
1229
- // Model split
1230
- //
1231
-
1232
- /// @details Build a split GGUF final path for this chunk.
1233
- /// 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"
1234
- // Returns the split_path length.
1235
- LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count);
1236
-
1237
- /// @details Extract the path prefix from the split_path if and only if the split_no and split_count match.
1238
- /// llama_split_prefix(split_prefix, 64, "/models/ggml-model-q4_0-00002-of-00004.gguf", 2, 4) => split_prefix = "/models/ggml-model-q4_0"
1239
- // Returns the split_prefix length.
1240
- LLAMA_API int llama_split_prefix(char * split_prefix, size_t maxlen, const char * split_path, int split_no, int split_count);
1241
-
1242
- // Print system information
1243
- LLAMA_API const char * llama_print_system_info(void);
1244
-
1245
- // Set callback for all future logging events.
1246
- // If this is not called, or NULL is supplied, everything is output on stderr.
1247
- LLAMA_API void llama_log_set(lm_ggml_log_callback log_callback, void * user_data);
1248
-
1249
- //
1250
- // Performance utils
1251
- //
1252
- // NOTE: Used by llama.cpp examples, avoid using in third-party apps. Instead, do your own performance measurements.
1253
- //
1254
-
1255
- struct llama_perf_context_data {
1256
- double t_start_ms;
1257
- double t_load_ms;
1258
- double t_p_eval_ms;
1259
- double t_eval_ms;
1260
-
1261
- int32_t n_p_eval;
1262
- int32_t n_eval;
1263
- };
1264
-
1265
- struct llama_perf_sampler_data {
1266
- double t_sample_ms;
1267
-
1268
- int32_t n_sample;
1269
- };
1270
-
1271
- LLAMA_API struct llama_perf_context_data llama_perf_context (const struct llama_context * ctx);
1272
- LLAMA_API void llama_perf_context_print(const struct llama_context * ctx);
1273
- LLAMA_API void llama_perf_context_reset( struct llama_context * ctx);
1274
-
1275
- // NOTE: the following work only with samplers constructed via llama_sampler_chain_init
1276
- LLAMA_API struct llama_perf_sampler_data llama_perf_sampler (const struct llama_sampler * chain);
1277
- LLAMA_API void llama_perf_sampler_print(const struct llama_sampler * chain);
1278
- LLAMA_API void llama_perf_sampler_reset( struct llama_sampler * chain);
1279
-
1280
- #ifdef __cplusplus
1281
- }
1282
- #endif
1283
-
1284
-
1285
- #endif // LLAMA_H
1
+ #ifndef LLAMA_H
2
+ #define LLAMA_H
3
+
4
+ #include "ggml.h"
5
+ #include "ggml-cpu.h"
6
+ #include "ggml-backend.h"
7
+
8
+ #include <stddef.h>
9
+ #include <stdint.h>
10
+ #include <stdio.h>
11
+ #include <stdbool.h>
12
+ #include <random>
13
+
14
+ #ifdef LLAMA_SHARED
15
+ # if defined(_WIN32) && !defined(__MINGW32__)
16
+ # ifdef LLAMA_BUILD
17
+ # define LLAMA_API __declspec(dllexport)
18
+ # else
19
+ # define LLAMA_API __declspec(dllimport)
20
+ # endif
21
+ # else
22
+ # define LLAMA_API __attribute__ ((visibility ("default")))
23
+ # endif
24
+ #else
25
+ # define LLAMA_API
26
+ #endif
27
+
28
+ #ifdef __GNUC__
29
+ # define DEPRECATED(func, hint) func __attribute__((deprecated(hint)))
30
+ #elif defined(_MSC_VER)
31
+ # define DEPRECATED(func, hint) __declspec(deprecated(hint)) func
32
+ #else
33
+ # define DEPRECATED(func, hint) func
34
+ #endif
35
+
36
+ #define LLAMA_DEFAULT_SEED 0xFFFFFFFF
37
+
38
+ #define LLAMA_TOKEN_NULL -1
39
+
40
+ #define LLAMA_FILE_MAGIC_GGLA 0x67676c61u // 'ggla'
41
+ #define LLAMA_FILE_MAGIC_GGSN 0x6767736eu // 'ggsn'
42
+ #define LLAMA_FILE_MAGIC_GGSQ 0x67677371u // 'ggsq'
43
+
44
+ #define LLAMA_SESSION_MAGIC LLAMA_FILE_MAGIC_GGSN
45
+ #define LLAMA_SESSION_VERSION 9
46
+
47
+ #define LLAMA_STATE_SEQ_MAGIC LLAMA_FILE_MAGIC_GGSQ
48
+ #define LLAMA_STATE_SEQ_VERSION 2
49
+
50
+ #ifdef __cplusplus
51
+ extern "C" {
52
+ #endif
53
+
54
+ //
55
+ // C interface
56
+ //
57
+ // TODO: show sample usage
58
+ //
59
+
60
+ struct llama_vocab;
61
+ struct llama_model;
62
+ struct llama_context;
63
+ struct llama_sampler;
64
+
65
+ typedef int32_t llama_pos;
66
+ typedef int32_t llama_token;
67
+ typedef int32_t llama_seq_id;
68
+
69
+ enum llama_vocab_type {
70
+ LLAMA_VOCAB_TYPE_NONE = 0, // For models without vocab
71
+ LLAMA_VOCAB_TYPE_SPM = 1, // LLaMA tokenizer based on byte-level BPE with byte fallback
72
+ LLAMA_VOCAB_TYPE_BPE = 2, // GPT-2 tokenizer based on byte-level BPE
73
+ LLAMA_VOCAB_TYPE_WPM = 3, // BERT tokenizer based on WordPiece
74
+ LLAMA_VOCAB_TYPE_UGM = 4, // T5 tokenizer based on Unigram
75
+ LLAMA_VOCAB_TYPE_RWKV = 5, // RWKV tokenizer based on greedy tokenization
76
+ };
77
+
78
+ // pre-tokenization types
79
+ enum llama_vocab_pre_type {
80
+ LLAMA_VOCAB_PRE_TYPE_DEFAULT = 0,
81
+ LLAMA_VOCAB_PRE_TYPE_LLAMA3 = 1,
82
+ LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM = 2,
83
+ LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER = 3,
84
+ LLAMA_VOCAB_PRE_TYPE_FALCON = 4,
85
+ LLAMA_VOCAB_PRE_TYPE_MPT = 5,
86
+ LLAMA_VOCAB_PRE_TYPE_STARCODER = 6,
87
+ LLAMA_VOCAB_PRE_TYPE_GPT2 = 7,
88
+ LLAMA_VOCAB_PRE_TYPE_REFACT = 8,
89
+ LLAMA_VOCAB_PRE_TYPE_COMMAND_R = 9,
90
+ LLAMA_VOCAB_PRE_TYPE_STABLELM2 = 10,
91
+ LLAMA_VOCAB_PRE_TYPE_QWEN2 = 11,
92
+ LLAMA_VOCAB_PRE_TYPE_OLMO = 12,
93
+ LLAMA_VOCAB_PRE_TYPE_DBRX = 13,
94
+ LLAMA_VOCAB_PRE_TYPE_SMAUG = 14,
95
+ LLAMA_VOCAB_PRE_TYPE_PORO = 15,
96
+ LLAMA_VOCAB_PRE_TYPE_CHATGLM3 = 16,
97
+ LLAMA_VOCAB_PRE_TYPE_CHATGLM4 = 17,
98
+ LLAMA_VOCAB_PRE_TYPE_VIKING = 18,
99
+ LLAMA_VOCAB_PRE_TYPE_JAIS = 19,
100
+ LLAMA_VOCAB_PRE_TYPE_TEKKEN = 20,
101
+ LLAMA_VOCAB_PRE_TYPE_SMOLLM = 21,
102
+ LLAMA_VOCAB_PRE_TYPE_CODESHELL = 22,
103
+ LLAMA_VOCAB_PRE_TYPE_BLOOM = 23,
104
+ LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH = 24,
105
+ LLAMA_VOCAB_PRE_TYPE_EXAONE = 25,
106
+ LLAMA_VOCAB_PRE_TYPE_CHAMELEON = 26,
107
+ LLAMA_VOCAB_PRE_TYPE_MINERVA = 27,
108
+ LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM = 28,
109
+ };
110
+
111
+ enum llama_rope_type {
112
+ LLAMA_ROPE_TYPE_NONE = -1,
113
+ LLAMA_ROPE_TYPE_NORM = 0,
114
+ LLAMA_ROPE_TYPE_NEOX = LM_GGML_ROPE_TYPE_NEOX,
115
+ LLAMA_ROPE_TYPE_MROPE = LM_GGML_ROPE_TYPE_MROPE,
116
+ LLAMA_ROPE_TYPE_VISION = LM_GGML_ROPE_TYPE_VISION,
117
+ };
118
+
119
+ enum llama_token_type { //TODO: remove, required until per token attributes are available from GGUF file
120
+ LLAMA_TOKEN_TYPE_UNDEFINED = 0,
121
+ LLAMA_TOKEN_TYPE_NORMAL = 1,
122
+ LLAMA_TOKEN_TYPE_UNKNOWN = 2,
123
+ LLAMA_TOKEN_TYPE_CONTROL = 3,
124
+ LLAMA_TOKEN_TYPE_USER_DEFINED = 4,
125
+ LLAMA_TOKEN_TYPE_UNUSED = 5,
126
+ LLAMA_TOKEN_TYPE_BYTE = 6,
127
+ };
128
+
129
+ enum llama_token_attr {
130
+ LLAMA_TOKEN_ATTR_UNDEFINED = 0,
131
+ LLAMA_TOKEN_ATTR_UNKNOWN = 1 << 0,
132
+ LLAMA_TOKEN_ATTR_UNUSED = 1 << 1,
133
+ LLAMA_TOKEN_ATTR_NORMAL = 1 << 2,
134
+ LLAMA_TOKEN_ATTR_CONTROL = 1 << 3, // SPECIAL?
135
+ LLAMA_TOKEN_ATTR_USER_DEFINED = 1 << 4,
136
+ LLAMA_TOKEN_ATTR_BYTE = 1 << 5,
137
+ LLAMA_TOKEN_ATTR_NORMALIZED = 1 << 6,
138
+ LLAMA_TOKEN_ATTR_LSTRIP = 1 << 7,
139
+ LLAMA_TOKEN_ATTR_RSTRIP = 1 << 8,
140
+ LLAMA_TOKEN_ATTR_SINGLE_WORD = 1 << 9,
141
+ };
142
+
143
+ // model file types
144
+ enum llama_ftype {
145
+ LLAMA_FTYPE_ALL_F32 = 0,
146
+ LLAMA_FTYPE_MOSTLY_F16 = 1, // except 1d tensors
147
+ LLAMA_FTYPE_MOSTLY_Q4_0 = 2, // except 1d tensors
148
+ LLAMA_FTYPE_MOSTLY_Q4_1 = 3, // except 1d tensors
149
+ // LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16 = 4, // tok_embeddings.weight and output.weight are F16
150
+ // LLAMA_FTYPE_MOSTLY_Q4_2 = 5, // support has been removed
151
+ // LLAMA_FTYPE_MOSTLY_Q4_3 = 6, // support has been removed
152
+ LLAMA_FTYPE_MOSTLY_Q8_0 = 7, // except 1d tensors
153
+ LLAMA_FTYPE_MOSTLY_Q5_0 = 8, // except 1d tensors
154
+ LLAMA_FTYPE_MOSTLY_Q5_1 = 9, // except 1d tensors
155
+ LLAMA_FTYPE_MOSTLY_Q2_K = 10, // except 1d tensors
156
+ LLAMA_FTYPE_MOSTLY_Q3_K_S = 11, // except 1d tensors
157
+ LLAMA_FTYPE_MOSTLY_Q3_K_M = 12, // except 1d tensors
158
+ LLAMA_FTYPE_MOSTLY_Q3_K_L = 13, // except 1d tensors
159
+ LLAMA_FTYPE_MOSTLY_Q4_K_S = 14, // except 1d tensors
160
+ LLAMA_FTYPE_MOSTLY_Q4_K_M = 15, // except 1d tensors
161
+ LLAMA_FTYPE_MOSTLY_Q5_K_S = 16, // except 1d tensors
162
+ LLAMA_FTYPE_MOSTLY_Q5_K_M = 17, // except 1d tensors
163
+ LLAMA_FTYPE_MOSTLY_Q6_K = 18, // except 1d tensors
164
+ LLAMA_FTYPE_MOSTLY_IQ2_XXS = 19, // except 1d tensors
165
+ LLAMA_FTYPE_MOSTLY_IQ2_XS = 20, // except 1d tensors
166
+ LLAMA_FTYPE_MOSTLY_Q2_K_S = 21, // except 1d tensors
167
+ LLAMA_FTYPE_MOSTLY_IQ3_XS = 22, // except 1d tensors
168
+ LLAMA_FTYPE_MOSTLY_IQ3_XXS = 23, // except 1d tensors
169
+ LLAMA_FTYPE_MOSTLY_IQ1_S = 24, // except 1d tensors
170
+ LLAMA_FTYPE_MOSTLY_IQ4_NL = 25, // except 1d tensors
171
+ LLAMA_FTYPE_MOSTLY_IQ3_S = 26, // except 1d tensors
172
+ LLAMA_FTYPE_MOSTLY_IQ3_M = 27, // except 1d tensors
173
+ LLAMA_FTYPE_MOSTLY_IQ2_S = 28, // except 1d tensors
174
+ LLAMA_FTYPE_MOSTLY_IQ2_M = 29, // except 1d tensors
175
+ LLAMA_FTYPE_MOSTLY_IQ4_XS = 30, // except 1d tensors
176
+ LLAMA_FTYPE_MOSTLY_IQ1_M = 31, // except 1d tensors
177
+ LLAMA_FTYPE_MOSTLY_BF16 = 32, // except 1d tensors
178
+ //LLAMA_FTYPE_MOSTLY_Q4_0_4_4 = 33, // removed from gguf files, use Q4_0 and runtime repack
179
+ //LLAMA_FTYPE_MOSTLY_Q4_0_4_8 = 34, // removed from gguf files, use Q4_0 and runtime repack
180
+ //LLAMA_FTYPE_MOSTLY_Q4_0_8_8 = 35, // removed from gguf files, use Q4_0 and runtime repack
181
+ LLAMA_FTYPE_MOSTLY_TQ1_0 = 36, // except 1d tensors
182
+ LLAMA_FTYPE_MOSTLY_TQ2_0 = 37, // except 1d tensors
183
+
184
+ LLAMA_FTYPE_GUESSED = 1024, // not specified in the model file
185
+ };
186
+
187
+ enum llama_rope_scaling_type {
188
+ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED = -1,
189
+ LLAMA_ROPE_SCALING_TYPE_NONE = 0,
190
+ LLAMA_ROPE_SCALING_TYPE_LINEAR = 1,
191
+ LLAMA_ROPE_SCALING_TYPE_YARN = 2,
192
+ LLAMA_ROPE_SCALING_TYPE_LONGROPE = 3,
193
+ LLAMA_ROPE_SCALING_TYPE_MAX_VALUE = LLAMA_ROPE_SCALING_TYPE_LONGROPE,
194
+ };
195
+
196
+ enum llama_pooling_type {
197
+ LLAMA_POOLING_TYPE_UNSPECIFIED = -1,
198
+ LLAMA_POOLING_TYPE_NONE = 0,
199
+ LLAMA_POOLING_TYPE_MEAN = 1,
200
+ LLAMA_POOLING_TYPE_CLS = 2,
201
+ LLAMA_POOLING_TYPE_LAST = 3,
202
+ LLAMA_POOLING_TYPE_RANK = 4, // used by reranking models to attach the classification head to the graph
203
+ };
204
+
205
+ enum llama_attention_type {
206
+ LLAMA_ATTENTION_TYPE_UNSPECIFIED = -1,
207
+ LLAMA_ATTENTION_TYPE_CAUSAL = 0,
208
+ LLAMA_ATTENTION_TYPE_NON_CAUSAL = 1,
209
+ };
210
+
211
+ enum llama_split_mode {
212
+ LLAMA_SPLIT_MODE_NONE = 0, // single GPU
213
+ LLAMA_SPLIT_MODE_LAYER = 1, // split layers and KV across GPUs
214
+ LLAMA_SPLIT_MODE_ROW = 2, // split layers and KV across GPUs, use tensor parallelism if supported
215
+ };
216
+
217
+ // TODO: simplify (https://github.com/ggerganov/llama.cpp/pull/9294#pullrequestreview-2286561979)
218
+ typedef struct llama_token_data {
219
+ llama_token id; // token id
220
+ float logit; // log-odds of the token
221
+ float p; // probability of the token
222
+ } llama_token_data;
223
+
224
+ typedef struct llama_token_data_array {
225
+ // TODO: consider SoA
226
+ // NOTE: this pointer can be modified by the samplers
227
+ llama_token_data * data;
228
+ size_t size;
229
+ int64_t selected; // this is the index in the data array (i.e. not the token id)
230
+ bool sorted;
231
+ } llama_token_data_array;
232
+
233
+ typedef bool (*llama_progress_callback)(float progress, void * user_data);
234
+
235
+ // Input data for llama_decode
236
+ // A llama_batch object can contain input about one or many sequences
237
+ // The provided arrays (i.e. token, embd, pos, etc.) must have size of n_tokens
238
+ //
239
+ // - token : the token ids of the input (used when embd is NULL)
240
+ // - embd : token embeddings (i.e. float vector of size n_embd) (used when token is NULL)
241
+ // - pos : the positions of the respective token in the sequence
242
+ // (if set to NULL, the token position will be tracked automatically by llama_decode)
243
+ // - seq_id : the sequence to which the respective token belongs
244
+ // (if set to NULL, the sequence ID will be assumed to be 0)
245
+ // - logits : if zero, the logits (and/or the embeddings) for the respective token will not be output
246
+ // (if set to NULL, only the logits for last token will be returned)
247
+ //
248
+ typedef struct llama_batch {
249
+ int32_t n_tokens;
250
+
251
+ llama_token * token;
252
+ float * embd;
253
+ llama_pos * pos;
254
+ int32_t * n_seq_id;
255
+ llama_seq_id ** seq_id;
256
+ int8_t * logits; // TODO: rename this to "output"
257
+ } llama_batch;
258
+
259
+ enum llama_model_kv_override_type {
260
+ LLAMA_KV_OVERRIDE_TYPE_INT,
261
+ LLAMA_KV_OVERRIDE_TYPE_FLOAT,
262
+ LLAMA_KV_OVERRIDE_TYPE_BOOL,
263
+ LLAMA_KV_OVERRIDE_TYPE_STR,
264
+ };
265
+
266
+ struct llama_model_kv_override {
267
+ enum llama_model_kv_override_type tag;
268
+
269
+ char key[128];
270
+
271
+ union {
272
+ int64_t val_i64;
273
+ double val_f64;
274
+ bool val_bool;
275
+ char val_str[128];
276
+ };
277
+ };
278
+
279
+ struct llama_model_params {
280
+ // NULL-terminated list of devices to use for offloading (if NULL, all available devices are used)
281
+ lm_ggml_backend_dev_t * devices;
282
+
283
+ int32_t n_gpu_layers; // number of layers to store in VRAM
284
+ enum llama_split_mode split_mode; // how to split the model across multiple GPUs
285
+
286
+ // the GPU that is used for the entire model when split_mode is LLAMA_SPLIT_MODE_NONE
287
+ int32_t main_gpu;
288
+
289
+ // proportion of the model (layers or rows) to offload to each GPU, size: llama_max_devices()
290
+ const float * tensor_split;
291
+
292
+ // Called with a progress value between 0.0 and 1.0. Pass NULL to disable.
293
+ // If the provided progress_callback returns true, model loading continues.
294
+ // If it returns false, model loading is immediately aborted.
295
+ llama_progress_callback progress_callback;
296
+
297
+ // context pointer passed to the progress callback
298
+ void * progress_callback_user_data;
299
+
300
+ // override key-value pairs of the model meta data
301
+ const struct llama_model_kv_override * kv_overrides;
302
+
303
+ // Keep the booleans together to avoid misalignment during copy-by-value.
304
+ bool vocab_only; // only load the vocabulary, no weights
305
+ bool use_mmap; // use mmap if possible
306
+ bool use_mlock; // force system to keep model in RAM
307
+ bool check_tensors; // validate model tensor data
308
+ };
309
+
310
+ // NOTE: changing the default values of parameters marked as [EXPERIMENTAL] may cause crashes or incorrect results in certain configurations
311
+ // https://github.com/ggerganov/llama.cpp/pull/7544
312
+ struct llama_context_params {
313
+ uint32_t n_ctx; // text context, 0 = from model
314
+ uint32_t n_batch; // logical maximum batch size that can be submitted to llama_decode
315
+ uint32_t n_ubatch; // physical maximum batch size
316
+ uint32_t n_seq_max; // max number of sequences (i.e. distinct states for recurrent models)
317
+ int32_t n_threads; // number of threads to use for generation
318
+ int32_t n_threads_batch; // number of threads to use for batch processing
319
+
320
+ enum llama_rope_scaling_type rope_scaling_type; // RoPE scaling type, from `enum llama_rope_scaling_type`
321
+ enum llama_pooling_type pooling_type; // whether to pool (sum) embedding results by sequence id
322
+ enum llama_attention_type attention_type; // attention type to use for embeddings
323
+
324
+ // ref: https://github.com/ggerganov/llama.cpp/pull/2054
325
+ float rope_freq_base; // RoPE base frequency, 0 = from model
326
+ float rope_freq_scale; // RoPE frequency scaling factor, 0 = from model
327
+ float yarn_ext_factor; // YaRN extrapolation mix factor, negative = from model
328
+ float yarn_attn_factor; // YaRN magnitude scaling factor
329
+ float yarn_beta_fast; // YaRN low correction dim
330
+ float yarn_beta_slow; // YaRN high correction dim
331
+ uint32_t yarn_orig_ctx; // YaRN original context size
332
+ float defrag_thold; // defragment the KV cache if holes/size > thold, < 0 disabled (default)
333
+
334
+ lm_ggml_backend_sched_eval_callback cb_eval;
335
+ void * cb_eval_user_data;
336
+
337
+ enum lm_ggml_type type_k; // data type for K cache [EXPERIMENTAL]
338
+ enum lm_ggml_type type_v; // data type for V cache [EXPERIMENTAL]
339
+
340
+ // Keep the booleans together and at the end of the struct to avoid misalignment during copy-by-value.
341
+ // TODO: move at the end of the struct
342
+ bool logits_all; // the llama_decode() call computes all logits, not just the last one (DEPRECATED - set llama_batch.logits instead)
343
+ bool embeddings; // if true, extract embeddings (together with logits)
344
+ bool offload_kqv; // whether to offload the KQV ops (including the KV cache) to GPU
345
+ bool flash_attn; // whether to use flash attention [EXPERIMENTAL]
346
+ bool no_perf; // whether to measure performance timings
347
+
348
+ // Abort callback
349
+ // if it returns true, execution of llama_decode() will be aborted
350
+ // currently works only with CPU execution
351
+ lm_ggml_abort_callback abort_callback;
352
+ void * abort_callback_data;
353
+ };
354
+
355
+ // model quantization parameters
356
+ typedef struct llama_model_quantize_params {
357
+ int32_t nthread; // number of threads to use for quantizing, if <=0 will use std::thread::hardware_concurrency()
358
+ enum llama_ftype ftype; // quantize to this llama_ftype
359
+ enum lm_ggml_type output_tensor_type; // output tensor type
360
+ enum lm_ggml_type token_embedding_type; // token embeddings tensor type
361
+ bool allow_requantize; // allow quantizing non-f32/f16 tensors
362
+ bool quantize_output_tensor; // quantize output.weight
363
+ bool only_copy; // only copy tensors - ftype, allow_requantize and quantize_output_tensor are ignored
364
+ bool pure; // quantize all tensors to the default type
365
+ bool keep_split; // quantize to the same number of shards
366
+ void * imatrix; // pointer to importance matrix data
367
+ void * kv_overrides; // pointer to vector containing overrides
368
+ } llama_model_quantize_params;
369
+
370
+ typedef struct llama_logit_bias {
371
+ llama_token token;
372
+ float bias;
373
+ } llama_logit_bias;
374
+
375
+ typedef struct llama_sampler_chain_params {
376
+ bool no_perf; // whether to measure performance timings
377
+ } llama_sampler_chain_params;
378
+
379
+ // used in chat template
380
+ typedef struct llama_chat_message {
381
+ const char * role;
382
+ const char * content;
383
+ } llama_chat_message;
384
+
385
+ // lora adapter
386
+ struct llama_adapter_lora;
387
+
388
+ // Helpers for getting default parameters
389
+ // TODO: update API to start accepting pointers to params structs (https://github.com/ggerganov/llama.cpp/discussions/9172)
390
+ LLAMA_API struct llama_model_params llama_model_default_params(void);
391
+ LLAMA_API struct llama_context_params llama_context_default_params(void);
392
+ LLAMA_API struct llama_sampler_chain_params llama_sampler_chain_default_params(void);
393
+ LLAMA_API struct llama_model_quantize_params llama_model_quantize_default_params(void);
394
+
395
+ // Initialize the llama + ggml backend
396
+ // If numa is true, use NUMA optimizations
397
+ // Call once at the start of the program
398
+ LLAMA_API void llama_backend_init(void);
399
+
400
+ // Call once at the end of the program - currently only used for MPI
401
+ LLAMA_API void llama_backend_free(void);
402
+
403
+ //optional:
404
+ LLAMA_API void llama_numa_init(enum lm_ggml_numa_strategy numa);
405
+
406
+ // Optional: an auto threadpool gets created in ggml if not passed explicitly
407
+ LLAMA_API void llama_attach_threadpool(
408
+ struct llama_context * ctx,
409
+ lm_ggml_threadpool_t threadpool,
410
+ lm_ggml_threadpool_t threadpool_batch);
411
+
412
+ LLAMA_API void llama_detach_threadpool(struct llama_context * ctx);
413
+
414
+ DEPRECATED(LLAMA_API struct llama_model * llama_load_model_from_file(
415
+ const char * path_model,
416
+ struct llama_model_params params),
417
+ "use llama_model_load_from_file instead");
418
+
419
+ // Load the model from a file
420
+ // If the file is split into multiple parts, the file name must follow this pattern: <name>-%05d-of-%05d.gguf
421
+ // If the split file name does not follow this pattern, use llama_model_load_from_splits
422
+ LLAMA_API struct llama_model * llama_model_load_from_file(
423
+ const char * path_model,
424
+ struct llama_model_params params);
425
+
426
+ // Load the model from multiple splits (support custom naming scheme)
427
+ // The paths must be in the correct order
428
+ LLAMA_API struct llama_model * llama_model_load_from_splits(
429
+ const char ** paths,
430
+ size_t n_paths,
431
+ struct llama_model_params params);
432
+
433
+ DEPRECATED(LLAMA_API void llama_free_model(struct llama_model * model),
434
+ "use llama_model_free instead");
435
+
436
+ LLAMA_API void llama_model_free(struct llama_model * model);
437
+
438
+ LLAMA_API struct llama_context * llama_init_from_model(
439
+ struct llama_model * model,
440
+ struct llama_context_params params);
441
+
442
+ DEPRECATED(LLAMA_API struct llama_context * llama_new_context_with_model(
443
+ struct llama_model * model,
444
+ struct llama_context_params params),
445
+ "use llama_init_from_model instead");
446
+
447
+ // Frees all allocated memory
448
+ LLAMA_API void llama_free(struct llama_context * ctx);
449
+
450
+ LLAMA_API int64_t llama_time_us(void);
451
+
452
+ LLAMA_API size_t llama_max_devices(void);
453
+
454
+ LLAMA_API bool llama_supports_mmap (void);
455
+ LLAMA_API bool llama_supports_mlock (void);
456
+ LLAMA_API bool llama_supports_gpu_offload(void);
457
+ LLAMA_API bool llama_supports_rpc (void);
458
+
459
+ LLAMA_API uint32_t llama_n_ctx (const struct llama_context * ctx);
460
+ LLAMA_API uint32_t llama_n_batch (const struct llama_context * ctx);
461
+ LLAMA_API uint32_t llama_n_ubatch (const struct llama_context * ctx);
462
+ LLAMA_API uint32_t llama_n_seq_max (const struct llama_context * ctx);
463
+
464
+ DEPRECATED(LLAMA_API int32_t llama_n_ctx_train(const struct llama_model * model), "use llama_model_n_ctx_train instead");
465
+ DEPRECATED(LLAMA_API int32_t llama_n_embd (const struct llama_model * model), "use llama_model_n_embd instead");
466
+ DEPRECATED(LLAMA_API int32_t llama_n_layer (const struct llama_model * model), "use llama_model_n_layer instead");
467
+ DEPRECATED(LLAMA_API int32_t llama_n_head (const struct llama_model * model), "use llama_model_n_head instead");
468
+
469
+ DEPRECATED(LLAMA_API int32_t llama_n_vocab (const struct llama_vocab * vocab), "use llama_vocab_n_tokens instead");
470
+
471
+ LLAMA_API const struct llama_model * llama_get_model (const struct llama_context * ctx);
472
+ LLAMA_API enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx);
473
+
474
+ LLAMA_API const struct llama_vocab * llama_model_get_vocab(const struct llama_model * model);
475
+ LLAMA_API enum llama_rope_type llama_model_rope_type(const struct llama_model * model);
476
+
477
+ LLAMA_API int32_t llama_model_n_ctx_train(const struct llama_model * model);
478
+ LLAMA_API int32_t llama_model_n_embd (const struct llama_model * model);
479
+ LLAMA_API int32_t llama_model_n_layer (const struct llama_model * model);
480
+ LLAMA_API int32_t llama_model_n_head (const struct llama_model * model);
481
+
482
+ // Get the model's RoPE frequency scaling factor
483
+ LLAMA_API float llama_model_rope_freq_scale_train(const struct llama_model * model);
484
+
485
+ LLAMA_API enum llama_vocab_type llama_vocab_type(const struct llama_vocab * vocab);
486
+
487
+ LLAMA_API int32_t llama_vocab_n_tokens(const struct llama_vocab * vocab);
488
+
489
+ // Functions to access the model's GGUF metadata scalar values
490
+ // - The functions return the length of the string on success, or -1 on failure
491
+ // - The output string is always null-terminated and cleared on failure
492
+ // - When retrieving a string, an extra byte must be allocated to account for the null terminator
493
+ // - GGUF array values are not supported by these functions
494
+
495
+ // Get metadata value as a string by key name
496
+ LLAMA_API int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size);
497
+
498
+ // Get the number of metadata key/value pairs
499
+ LLAMA_API int32_t llama_model_meta_count(const struct llama_model * model);
500
+
501
+ // Get metadata key name by index
502
+ LLAMA_API int32_t llama_model_meta_key_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size);
503
+
504
+ // Get metadata value as a string by index
505
+ 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);
506
+
507
+ // Get a string describing the model type
508
+ LLAMA_API int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size);
509
+
510
+ // Returns the total size of all the tensors in the model in bytes
511
+ LLAMA_API uint64_t llama_model_size(const struct llama_model * model);
512
+
513
+ // Get the default chat template. Returns nullptr if not available
514
+ LLAMA_API const char * llama_model_chat_template(const struct llama_model * model);
515
+
516
+ // Returns the total number of parameters in the model
517
+ LLAMA_API uint64_t llama_model_n_params(const struct llama_model * model);
518
+
519
+ // Returns true if the model contains an encoder that requires llama_encode() call
520
+ LLAMA_API bool llama_model_has_encoder(const struct llama_model * model);
521
+
522
+ // Returns true if the model contains a decoder that requires llama_decode() call
523
+ LLAMA_API bool llama_model_has_decoder(const struct llama_model * model);
524
+
525
+ // For encoder-decoder models, this function returns id of the token that must be provided
526
+ // to the decoder to start generating output sequence. For other models, it returns -1.
527
+ LLAMA_API llama_token llama_model_decoder_start_token(const struct llama_model * model);
528
+
529
+ // Returns true if the model is recurrent (like Mamba, RWKV, etc.)
530
+ LLAMA_API bool llama_model_is_recurrent(const struct llama_model * model);
531
+
532
+ // Returns 0 on success
533
+ LLAMA_API uint32_t llama_model_quantize(
534
+ const char * fname_inp,
535
+ const char * fname_out,
536
+ const llama_model_quantize_params * params);
537
+
538
+ //
539
+ // Adapters
540
+ //
541
+
542
+ // Load a LoRA adapter from file
543
+ LLAMA_API struct llama_adapter_lora * llama_adapter_lora_init(
544
+ struct llama_model * model,
545
+ const char * path_lora);
546
+
547
+ // Manually free a LoRA adapter
548
+ // Note: loaded adapters will be free when the associated model is deleted
549
+ LLAMA_API void llama_adapter_lora_free(struct llama_adapter_lora * adapter);
550
+
551
+ // The following functions operate on a llama_context, hence the naming: llama_verb_...
552
+
553
+ // Add a loaded LoRA adapter to given context
554
+ // This will not modify model's weight
555
+ LLAMA_API int32_t llama_set_adapter_lora(
556
+ struct llama_context * ctx,
557
+ struct llama_adapter_lora * adapter,
558
+ float scale);
559
+
560
+ // Remove a specific LoRA adapter from given context
561
+ // Return -1 if the adapter is not present in the context
562
+ LLAMA_API int32_t llama_rm_adapter_lora(
563
+ struct llama_context * ctx,
564
+ struct llama_adapter_lora * adapter);
565
+
566
+ // Remove all LoRA adapters from given context
567
+ LLAMA_API void llama_clear_adapter_lora(struct llama_context * ctx);
568
+
569
+ // Apply a loaded control vector to a llama_context, or if data is NULL, clear
570
+ // the currently loaded vector.
571
+ // n_embd should be the size of a single layer's control, and data should point
572
+ // to an n_embd x n_layers buffer starting from layer 1.
573
+ // il_start and il_end are the layer range the vector should apply to (both inclusive)
574
+ // See llama_control_vector_load in common to load a control vector.
575
+ LLAMA_API int32_t llama_apply_adapter_cvec(
576
+ struct llama_context * ctx,
577
+ const float * data,
578
+ size_t len,
579
+ int32_t n_embd,
580
+ int32_t il_start,
581
+ int32_t il_end);
582
+
583
+ //
584
+ // KV cache
585
+ //
586
+
587
+ // TODO: remove llama_kv_cache_view_* API
588
+
589
+ // Information associated with an individual cell in the KV cache view.
590
+ struct llama_kv_cache_view_cell {
591
+ // The position for this cell. Takes KV cache shifts into account.
592
+ // May be negative if the cell is not populated.
593
+ llama_pos pos;
594
+ };
595
+
596
+ // An updateable view of the KV cache.
597
+ struct llama_kv_cache_view {
598
+ // Number of KV cache cells. This will be the same as the context size.
599
+ int32_t n_cells;
600
+
601
+ // Maximum number of sequences that can exist in a cell. It's not an error
602
+ // if there are more sequences in a cell than this value, however they will
603
+ // not be visible in the view cells_sequences.
604
+ int32_t n_seq_max;
605
+
606
+ // Number of tokens in the cache. For example, if there are two populated
607
+ // cells, the first with 1 sequence id in it and the second with 2 sequence
608
+ // ids then you'll have 3 tokens.
609
+ int32_t token_count;
610
+
611
+ // Number of populated cache cells.
612
+ int32_t used_cells;
613
+
614
+ // Maximum contiguous empty slots in the cache.
615
+ int32_t max_contiguous;
616
+
617
+ // Index to the start of the max_contiguous slot range. Can be negative
618
+ // when cache is full.
619
+ int32_t max_contiguous_idx;
620
+
621
+ // Information for an individual cell.
622
+ struct llama_kv_cache_view_cell * cells;
623
+
624
+ // The sequences for each cell. There will be n_seq_max items per cell.
625
+ llama_seq_id * cells_sequences;
626
+ };
627
+
628
+ // Create an empty KV cache view. (use only for debugging purposes)
629
+ LLAMA_API struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max);
630
+
631
+ // Free a KV cache view. (use only for debugging purposes)
632
+ LLAMA_API void llama_kv_cache_view_free(struct llama_kv_cache_view * view);
633
+
634
+ // Update the KV cache view structure with the current state of the KV cache. (use only for debugging purposes)
635
+ // TODO: change signature to llama_kv_cache_view_update(struct llama_kv_cache_view * view, const struct llama_context * ctx)
636
+ LLAMA_API void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view);
637
+
638
+ ///
639
+
640
+ // Returns the number of tokens in the KV cache (slow, use only for debug)
641
+ // If a KV cell has multiple sequences assigned to it, it will be counted multiple times
642
+ LLAMA_API int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx);
643
+
644
+ // Returns the number of used KV cells (i.e. have at least one sequence assigned to them)
645
+ LLAMA_API int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx);
646
+
647
+ // Clear the KV cache - both cell info is erased and KV data is zeroed
648
+ LLAMA_API void llama_kv_cache_clear(
649
+ struct llama_context * ctx);
650
+
651
+ // Removes all tokens that belong to the specified sequence and have positions in [p0, p1)
652
+ // Returns false if a partial sequence cannot be removed. Removing a whole sequence never fails
653
+ // seq_id < 0 : match any sequence
654
+ // p0 < 0 : [0, p1]
655
+ // p1 < 0 : [p0, inf)
656
+ LLAMA_API bool llama_kv_cache_seq_rm(
657
+ struct llama_context * ctx,
658
+ llama_seq_id seq_id,
659
+ llama_pos p0,
660
+ llama_pos p1);
661
+
662
+ // Copy all tokens that belong to the specified sequence to another sequence
663
+ // Note that this does not allocate extra KV cache memory - it simply assigns the tokens to the new sequence
664
+ // p0 < 0 : [0, p1]
665
+ // p1 < 0 : [p0, inf)
666
+ LLAMA_API void llama_kv_cache_seq_cp(
667
+ struct llama_context * ctx,
668
+ llama_seq_id seq_id_src,
669
+ llama_seq_id seq_id_dst,
670
+ llama_pos p0,
671
+ llama_pos p1);
672
+
673
+ // Removes all tokens that do not belong to the specified sequence
674
+ LLAMA_API void llama_kv_cache_seq_keep(
675
+ struct llama_context * ctx,
676
+ llama_seq_id seq_id);
677
+
678
+ // Adds relative position "delta" to all tokens that belong to the specified sequence and have positions in [p0, p1)
679
+ // If the KV cache is RoPEd, the KV data is updated accordingly:
680
+ // - lazily on next llama_decode()
681
+ // - explicitly with llama_kv_cache_update()
682
+ // p0 < 0 : [0, p1]
683
+ // p1 < 0 : [p0, inf)
684
+ LLAMA_API void llama_kv_cache_seq_add(
685
+ struct llama_context * ctx,
686
+ llama_seq_id seq_id,
687
+ llama_pos p0,
688
+ llama_pos p1,
689
+ llama_pos delta);
690
+
691
+ // Integer division of the positions by factor of `d > 1`
692
+ // If the KV cache is RoPEd, the KV data is updated accordingly:
693
+ // - lazily on next llama_decode()
694
+ // - explicitly with llama_kv_cache_update()
695
+ // p0 < 0 : [0, p1]
696
+ // p1 < 0 : [p0, inf)
697
+ LLAMA_API void llama_kv_cache_seq_div(
698
+ struct llama_context * ctx,
699
+ llama_seq_id seq_id,
700
+ llama_pos p0,
701
+ llama_pos p1,
702
+ int d);
703
+
704
+ // Returns the largest position present in the KV cache for the specified sequence
705
+ LLAMA_API llama_pos llama_kv_cache_seq_pos_max(
706
+ struct llama_context * ctx,
707
+ llama_seq_id seq_id);
708
+
709
+ // TODO: the llama_kv_cache_defrag and llama_kv_cache_update API tightly couples llama_context with llama_kv_cache
710
+ // how to avoid this?
711
+
712
+ // Defragment the KV cache
713
+ // This will be applied:
714
+ // - lazily on next llama_decode()
715
+ // - explicitly with llama_kv_cache_update()
716
+ LLAMA_API void llama_kv_cache_defrag(struct llama_context * ctx);
717
+
718
+ // Apply the KV cache updates (such as K-shifts, defragmentation, etc.)
719
+ LLAMA_API void llama_kv_cache_update(struct llama_context * ctx);
720
+
721
+ // Check if the context supports KV cache shifting
722
+ LLAMA_API bool llama_kv_cache_can_shift(struct llama_context * ctx);
723
+
724
+ //
725
+ // State / sessions
726
+ //
727
+
728
+ // Returns the *actual* size in bytes of the state
729
+ // (logits, embedding and kv_cache)
730
+ // Only use when saving the state, not when restoring it, otherwise the size may be too small.
731
+ LLAMA_API size_t llama_state_get_size(struct llama_context * ctx);
732
+ LLAMA_API DEPRECATED(size_t llama_get_state_size(struct llama_context * ctx),
733
+ "use llama_state_get_size instead");
734
+
735
+ // Copies the state to the specified destination address.
736
+ // Destination needs to have allocated enough memory.
737
+ // Returns the number of bytes copied
738
+ LLAMA_API size_t llama_state_get_data(
739
+ struct llama_context * ctx,
740
+ uint8_t * dst,
741
+ size_t size);
742
+ LLAMA_API DEPRECATED(size_t llama_copy_state_data(
743
+ struct llama_context * ctx,
744
+ uint8_t * dst),
745
+ "use llama_state_get_data instead");
746
+
747
+ // Set the state reading from the specified address
748
+ // Returns the number of bytes read
749
+ LLAMA_API size_t llama_state_set_data(
750
+ struct llama_context * ctx,
751
+ const uint8_t * src,
752
+ size_t size);
753
+ LLAMA_API DEPRECATED(size_t llama_set_state_data(
754
+ struct llama_context * ctx,
755
+ const uint8_t * src),
756
+ "use llama_state_set_data instead");
757
+
758
+ // Save/load session file
759
+ LLAMA_API bool llama_state_load_file(
760
+ struct llama_context * ctx,
761
+ const char * path_session,
762
+ llama_token * tokens_out,
763
+ size_t n_token_capacity,
764
+ size_t * n_token_count_out);
765
+ LLAMA_API DEPRECATED(bool llama_load_session_file(
766
+ struct llama_context * ctx,
767
+ const char * path_session,
768
+ llama_token * tokens_out,
769
+ size_t n_token_capacity,
770
+ size_t * n_token_count_out),
771
+ "use llama_state_load_file instead");
772
+
773
+ LLAMA_API bool llama_state_save_file(
774
+ struct llama_context * ctx,
775
+ const char * path_session,
776
+ const llama_token * tokens,
777
+ size_t n_token_count);
778
+ LLAMA_API DEPRECATED(bool llama_save_session_file(
779
+ struct llama_context * ctx,
780
+ const char * path_session,
781
+ const llama_token * tokens,
782
+ size_t n_token_count),
783
+ "use llama_state_save_file instead");
784
+
785
+ // Get the exact size needed to copy the KV cache of a single sequence
786
+ LLAMA_API size_t llama_state_seq_get_size(
787
+ struct llama_context * ctx,
788
+ llama_seq_id seq_id);
789
+
790
+ // Copy the KV cache of a single sequence into the specified buffer
791
+ LLAMA_API size_t llama_state_seq_get_data(
792
+ struct llama_context * ctx,
793
+ uint8_t * dst,
794
+ size_t size,
795
+ llama_seq_id seq_id);
796
+
797
+ // Copy the sequence data (originally copied with `llama_state_seq_get_data`) into the specified sequence
798
+ // Returns:
799
+ // - Positive: Ok
800
+ // - Zero: Failed to load
801
+ LLAMA_API size_t llama_state_seq_set_data(
802
+ struct llama_context * ctx,
803
+ const uint8_t * src,
804
+ size_t size,
805
+ llama_seq_id dest_seq_id);
806
+
807
+ LLAMA_API size_t llama_state_seq_save_file(
808
+ struct llama_context * ctx,
809
+ const char * filepath,
810
+ llama_seq_id seq_id,
811
+ const llama_token * tokens,
812
+ size_t n_token_count);
813
+
814
+ LLAMA_API size_t llama_state_seq_load_file(
815
+ struct llama_context * ctx,
816
+ const char * filepath,
817
+ llama_seq_id dest_seq_id,
818
+ llama_token * tokens_out,
819
+ size_t n_token_capacity,
820
+ size_t * n_token_count_out);
821
+
822
+ //
823
+ // Decoding
824
+ //
825
+
826
+ // Return batch for single sequence of tokens
827
+ // The sequence ID will be fixed to 0
828
+ // The position of the tokens will be tracked automatically by llama_decode
829
+ //
830
+ // NOTE: this is a helper function to facilitate transition to the new batch API - avoid using it
831
+ //
832
+ LLAMA_API struct llama_batch llama_batch_get_one(
833
+ llama_token * tokens,
834
+ int32_t n_tokens);
835
+
836
+ // Allocates a batch of tokens on the heap that can hold a maximum of n_tokens
837
+ // Each token can be assigned up to n_seq_max sequence ids
838
+ // The batch has to be freed with llama_batch_free()
839
+ // If embd != 0, llama_batch.embd will be allocated with size of n_tokens * embd * sizeof(float)
840
+ // Otherwise, llama_batch.token will be allocated to store n_tokens llama_token
841
+ // The rest of the llama_batch members are allocated with size n_tokens
842
+ // All members are left uninitialized
843
+ LLAMA_API struct llama_batch llama_batch_init(
844
+ int32_t n_tokens,
845
+ int32_t embd,
846
+ int32_t n_seq_max);
847
+
848
+ // Frees a batch of tokens allocated with llama_batch_init()
849
+ LLAMA_API void llama_batch_free(struct llama_batch batch);
850
+
851
+ // Processes a batch of tokens with the ecoder part of the encoder-decoder model.
852
+ // Stores the encoder output internally for later use by the decoder cross-attention layers.
853
+ // 0 - success
854
+ // < 0 - error. the KV cache state is restored to the state before this call
855
+ LLAMA_API int32_t llama_encode(
856
+ struct llama_context * ctx,
857
+ struct llama_batch batch);
858
+
859
+ // Positive return values does not mean a fatal error, but rather a warning.
860
+ // 0 - success
861
+ // 1 - could not find a KV slot for the batch (try reducing the size of the batch or increase the context)
862
+ // < 0 - error. the KV cache state is restored to the state before this call
863
+ LLAMA_API int32_t llama_decode(
864
+ struct llama_context * ctx,
865
+ struct llama_batch batch);
866
+
867
+ // Set the number of threads used for decoding
868
+ // n_threads is the number of threads used for generation (single token)
869
+ // n_threads_batch is the number of threads used for prompt and batch processing (multiple tokens)
870
+ LLAMA_API void llama_set_n_threads(struct llama_context * ctx, int32_t n_threads, int32_t n_threads_batch);
871
+
872
+ // Get the number of threads used for generation of a single token.
873
+ LLAMA_API int32_t llama_n_threads(struct llama_context * ctx);
874
+
875
+ // Get the number of threads used for prompt and batch processing (multiple token).
876
+ LLAMA_API int32_t llama_n_threads_batch(struct llama_context * ctx);
877
+
878
+ // Set whether the model is in embeddings mode or not
879
+ // If true, embeddings will be returned but logits will not
880
+ LLAMA_API void llama_set_embeddings(struct llama_context * ctx, bool embeddings);
881
+
882
+ // Set whether to use causal attention or not
883
+ // If set to true, the model will only attend to the past tokens
884
+ LLAMA_API void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn);
885
+
886
+ // Set abort callback
887
+ LLAMA_API void llama_set_abort_callback(struct llama_context * ctx, lm_ggml_abort_callback abort_callback, void * abort_callback_data);
888
+
889
+ // Wait until all computations are finished
890
+ // This is automatically done when using one of the functions below to obtain the computation results
891
+ // and is not necessary to call it explicitly in most cases
892
+ LLAMA_API void llama_synchronize(struct llama_context * ctx);
893
+
894
+ // Token logits obtained from the last call to llama_decode()
895
+ // The logits for which llama_batch.logits[i] != 0 are stored contiguously
896
+ // in the order they have appeared in the batch.
897
+ // Rows: number of tokens for which llama_batch.logits[i] != 0
898
+ // Cols: n_vocab
899
+ LLAMA_API float * llama_get_logits(struct llama_context * ctx);
900
+
901
+ // Logits for the ith token. For positive indices, Equivalent to:
902
+ // llama_get_logits(ctx) + ctx->output_ids[i]*n_vocab
903
+ // Negative indicies can be used to access logits in reverse order, -1 is the last logit.
904
+ // returns NULL for invalid ids.
905
+ LLAMA_API float * llama_get_logits_ith(struct llama_context * ctx, int32_t i);
906
+
907
+ // Get all output token embeddings.
908
+ // when pooling_type == LLAMA_POOLING_TYPE_NONE or when using a generative model,
909
+ // the embeddings for which llama_batch.logits[i] != 0 are stored contiguously
910
+ // in the order they have appeared in the batch.
911
+ // shape: [n_outputs*n_embd]
912
+ // Otherwise, returns NULL.
913
+ LLAMA_API float * llama_get_embeddings(struct llama_context * ctx);
914
+
915
+ // Get the embeddings for the ith token. For positive indices, Equivalent to:
916
+ // llama_get_embeddings(ctx) + ctx->output_ids[i]*n_embd
917
+ // Negative indicies can be used to access embeddings in reverse order, -1 is the last embedding.
918
+ // shape: [n_embd] (1-dimensional)
919
+ // returns NULL for invalid ids.
920
+ LLAMA_API float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i);
921
+
922
+ // Get the embeddings for a sequence id
923
+ // Returns NULL if pooling_type is LLAMA_POOLING_TYPE_NONE
924
+ // when pooling_type == LLAMA_POOLING_TYPE_RANK, returns float[1] with the rank of the sequence
925
+ // otherwise: float[n_embd] (1-dimensional)
926
+ LLAMA_API float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id);
927
+
928
+ //
929
+ // Vocab
930
+ //
931
+
932
+ LLAMA_API const char * llama_vocab_get_text(const struct llama_vocab * vocab, llama_token token);
933
+
934
+ LLAMA_API float llama_vocab_get_score(const struct llama_vocab * vocab, llama_token token);
935
+
936
+ LLAMA_API enum llama_token_attr llama_vocab_get_attr(const struct llama_vocab * vocab, llama_token token);
937
+
938
+ // Check if the token is supposed to end generation (end-of-generation, eg. EOS, EOT, etc.)
939
+ LLAMA_API bool llama_vocab_is_eog(const struct llama_vocab * vocab, llama_token token);
940
+
941
+ // Identify if Token Id is a control token or a render-able token
942
+ LLAMA_API bool llama_vocab_is_control(const struct llama_vocab * vocab, llama_token token);
943
+
944
+ // Special tokens
945
+ LLAMA_API llama_token llama_vocab_bos(const struct llama_vocab * vocab); // beginning-of-sentence
946
+ LLAMA_API llama_token llama_vocab_eos(const struct llama_vocab * vocab); // end-of-sentence
947
+ LLAMA_API llama_token llama_vocab_eot(const struct llama_vocab * vocab); // end-of-turn
948
+ LLAMA_API llama_token llama_vocab_sep(const struct llama_vocab * vocab); // sentence separator
949
+ LLAMA_API llama_token llama_vocab_nl (const struct llama_vocab * vocab); // next-line
950
+ LLAMA_API llama_token llama_vocab_pad(const struct llama_vocab * vocab); // padding
951
+
952
+ LLAMA_API bool llama_vocab_get_add_bos(const struct llama_vocab * vocab);
953
+ LLAMA_API bool llama_vocab_get_add_eos(const struct llama_vocab * vocab);
954
+
955
+ LLAMA_API llama_token llama_vocab_fim_pre(const struct llama_vocab * vocab);
956
+ LLAMA_API llama_token llama_vocab_fim_suf(const struct llama_vocab * vocab);
957
+ LLAMA_API llama_token llama_vocab_fim_mid(const struct llama_vocab * vocab);
958
+ LLAMA_API llama_token llama_vocab_fim_pad(const struct llama_vocab * vocab);
959
+ LLAMA_API llama_token llama_vocab_fim_rep(const struct llama_vocab * vocab);
960
+ LLAMA_API llama_token llama_vocab_fim_sep(const struct llama_vocab * vocab);
961
+
962
+ DEPRECATED(LLAMA_API const char * llama_token_get_text(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_text instead");
963
+ DEPRECATED(LLAMA_API float llama_token_get_score(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_score instead");
964
+ DEPRECATED(LLAMA_API enum llama_token_attr llama_token_get_attr(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_attr instead");
965
+ DEPRECATED(LLAMA_API bool llama_token_is_eog(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_is_eog instead");
966
+ DEPRECATED(LLAMA_API bool llama_token_is_control(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_is_control instead");
967
+ DEPRECATED(LLAMA_API llama_token llama_token_bos(const struct llama_vocab * vocab), "use llama_vocab_bos instead");
968
+ DEPRECATED(LLAMA_API llama_token llama_token_eos(const struct llama_vocab * vocab), "use llama_vocab_eos instead");
969
+ DEPRECATED(LLAMA_API llama_token llama_token_eot(const struct llama_vocab * vocab), "use llama_vocab_eot instead");
970
+ DEPRECATED(LLAMA_API llama_token llama_token_cls(const struct llama_vocab * vocab), "use llama_vocab_cls instead");
971
+ DEPRECATED(LLAMA_API llama_token llama_token_sep(const struct llama_vocab * vocab), "use llama_vocab_sep instead");
972
+ DEPRECATED(LLAMA_API llama_token llama_token_nl (const struct llama_vocab * vocab), "use llama_vocab_nl instead");
973
+ DEPRECATED(LLAMA_API llama_token llama_token_pad(const struct llama_vocab * vocab), "use llama_vocab_pad instead");
974
+ DEPRECATED(LLAMA_API bool llama_add_bos_token(const struct llama_vocab * vocab), "use llama_vocab_get_add_bos instead");
975
+ DEPRECATED(LLAMA_API bool llama_add_eos_token(const struct llama_vocab * vocab), "use llama_vocab_get_add_eos instead");
976
+ DEPRECATED(LLAMA_API llama_token llama_token_fim_pre(const struct llama_vocab * vocab), "use llama_vocab_fim_pre instead");
977
+ DEPRECATED(LLAMA_API llama_token llama_token_fim_suf(const struct llama_vocab * vocab), "use llama_vocab_fim_suf instead");
978
+ DEPRECATED(LLAMA_API llama_token llama_token_fim_mid(const struct llama_vocab * vocab), "use llama_vocab_fim_mid instead");
979
+ DEPRECATED(LLAMA_API llama_token llama_token_fim_pad(const struct llama_vocab * vocab), "use llama_vocab_fim_pad instead");
980
+ DEPRECATED(LLAMA_API llama_token llama_token_fim_rep(const struct llama_vocab * vocab), "use llama_vocab_fim_rep instead");
981
+ DEPRECATED(LLAMA_API llama_token llama_token_fim_sep(const struct llama_vocab * vocab), "use llama_vocab_fim_sep instead");
982
+
983
+ // CLS is equivalent to BOS
984
+ DEPRECATED(LLAMA_API llama_token llama_vocab_cls(const struct llama_vocab * vocab), // classification
985
+ "use llama_vocab_bos instead");
986
+
987
+ //
988
+ // Tokenization
989
+ //
990
+ // The API is thread-safe.
991
+ //
992
+
993
+ /// @details Convert the provided text into tokens.
994
+ /// @param tokens The tokens pointer must be large enough to hold the resulting tokens.
995
+ /// @return Returns the number of tokens on success, no more than n_tokens_max
996
+ /// @return Returns a negative number on failure - the number of tokens that would have been returned
997
+ /// @param add_special Allow to add BOS and EOS tokens if model is configured to do so.
998
+ /// @param parse_special Allow tokenizing special and/or control tokens which otherwise are not exposed and treated
999
+ /// as plaintext. Does not insert a leading space.
1000
+ LLAMA_API int32_t llama_tokenize(
1001
+ const struct llama_vocab * vocab,
1002
+ const char * text,
1003
+ int32_t text_len,
1004
+ llama_token * tokens,
1005
+ int32_t n_tokens_max,
1006
+ bool add_special,
1007
+ bool parse_special);
1008
+
1009
+ // Token Id -> Piece.
1010
+ // Uses the vocabulary in the provided context.
1011
+ // Does not write null terminator to the buffer.
1012
+ // User can skip up to 'lstrip' leading spaces before copying (useful when encoding/decoding multiple tokens with 'add_space_prefix')
1013
+ // @param special If true, special tokens are rendered in the output.
1014
+ LLAMA_API int32_t llama_token_to_piece(
1015
+ const struct llama_vocab * vocab,
1016
+ llama_token token,
1017
+ char * buf,
1018
+ int32_t length,
1019
+ int32_t lstrip,
1020
+ bool special);
1021
+
1022
+ /// @details Convert the provided tokens into text (inverse of llama_tokenize()).
1023
+ /// @param text The char pointer must be large enough to hold the resulting text.
1024
+ /// @return Returns the number of chars/bytes on success, no more than text_len_max.
1025
+ /// @return Returns a negative number on failure - the number of chars/bytes that would have been returned.
1026
+ /// @param remove_special Allow to remove BOS and EOS tokens if model is configured to do so.
1027
+ /// @param unparse_special If true, special tokens are rendered in the output.
1028
+ LLAMA_API int32_t llama_detokenize(
1029
+ const struct llama_vocab * vocab,
1030
+ const llama_token * tokens,
1031
+ int32_t n_tokens,
1032
+ char * text,
1033
+ int32_t text_len_max,
1034
+ bool remove_special,
1035
+ bool unparse_special);
1036
+
1037
+ //
1038
+ // Chat templates
1039
+ //
1040
+
1041
+ /// Apply chat template. Inspired by hf apply_chat_template() on python.
1042
+ /// Both "model" and "custom_template" are optional, but at least one is required. "custom_template" has higher precedence than "model"
1043
+ /// 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
1044
+ /// @param tmpl A Jinja template to use for this chat. If this is nullptr, the model’s default chat template will be used instead.
1045
+ /// @param chat Pointer to a list of multiple llama_chat_message
1046
+ /// @param n_msg Number of llama_chat_message in this chat
1047
+ /// @param add_ass Whether to end the prompt with the token(s) that indicate the start of an assistant message.
1048
+ /// @param buf A buffer to hold the output formatted prompt. The recommended alloc size is 2 * (total number of characters of all messages)
1049
+ /// @param length The size of the allocated buffer
1050
+ /// @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.
1051
+ LLAMA_API int32_t llama_chat_apply_template(
1052
+ const char * tmpl,
1053
+ const struct llama_chat_message * chat,
1054
+ size_t n_msg,
1055
+ bool add_ass,
1056
+ char * buf,
1057
+ int32_t length);
1058
+
1059
+ // Get list of built-in chat templates
1060
+ LLAMA_API int32_t llama_chat_builtin_templates(const char ** output, size_t len);
1061
+
1062
+ //
1063
+ // Sampling API
1064
+ //
1065
+ // Sample usage:
1066
+ //
1067
+ // // prepare the sampling chain at the start
1068
+ // auto sparams = llama_sampler_chain_default_params();
1069
+ //
1070
+ // llama_sampler * smpl = llama_sampler_chain_init(sparams);
1071
+ //
1072
+ // llama_sampler_chain_add(smpl, llama_sampler_init_top_k(50));
1073
+ // llama_sampler_chain_add(smpl, llama_sampler_init_top_p(0.9, 1));
1074
+ // llama_sampler_chain_add(smpl, llama_sampler_init_temp (0.8));
1075
+ //
1076
+ // // typically, the chain should end with a sampler such as "greedy", "dist" or "mirostat"
1077
+ // // this sampler will be responsible to select the actual token
1078
+ // llama_sampler_chain_add(smpl, llama_sampler_init_dist(seed));
1079
+ //
1080
+ // ...
1081
+ //
1082
+ // // decoding loop:
1083
+ // while (...) {
1084
+ // ...
1085
+ //
1086
+ // llama_decode(ctx, batch);
1087
+ //
1088
+ // // sample from the logits of the last token in the batch
1089
+ // const llama_token id = llama_sampler_sample(smpl, ctx, -1);
1090
+ //
1091
+ // // accepting the token updates the internal state of certain samplers (e.g. grammar, repetition, etc.)
1092
+ // llama_sampler_accept(smpl, id);
1093
+ // ...
1094
+ // }
1095
+ //
1096
+ // llama_sampler_free(smpl);
1097
+ //
1098
+ // TODO: In the future, llama_sampler will be utilized to offload the sampling to the backends (e.g. GPU).
1099
+ //
1100
+
1101
+ typedef void * llama_sampler_context_t;
1102
+
1103
+ // user code can implement the interface below in order to create custom llama_sampler
1104
+ struct llama_sampler_i {
1105
+ const char * (*name) (const struct llama_sampler * smpl); // can be NULL
1106
+ void (*accept)( struct llama_sampler * smpl, llama_token token); // can be NULL
1107
+ void (*apply) ( struct llama_sampler * smpl, llama_token_data_array * cur_p); // required
1108
+ void (*reset) ( struct llama_sampler * smpl); // can be NULL
1109
+ struct llama_sampler * (*clone) (const struct llama_sampler * smpl); // can be NULL if ctx is NULL
1110
+ void (*free) ( struct llama_sampler * smpl); // can be NULL if ctx is NULL
1111
+
1112
+ // TODO: API for internal libllama usage for appending the sampling to an existing lm_ggml_cgraph
1113
+ //void (*apply_ggml) (struct llama_sampler * smpl, ...);
1114
+ };
1115
+
1116
+ struct llama_sampler {
1117
+ struct llama_sampler_i * iface;
1118
+ llama_sampler_context_t ctx;
1119
+ };
1120
+
1121
+ // mirror of llama_sampler_i:
1122
+ LLAMA_API const char * llama_sampler_name (const struct llama_sampler * smpl);
1123
+ LLAMA_API void llama_sampler_accept( struct llama_sampler * smpl, llama_token token);
1124
+ LLAMA_API void llama_sampler_apply ( struct llama_sampler * smpl, llama_token_data_array * cur_p);
1125
+ LLAMA_API void llama_sampler_reset ( struct llama_sampler * smpl);
1126
+ LLAMA_API struct llama_sampler * llama_sampler_clone (const struct llama_sampler * smpl);
1127
+ // important: do not free if the sampler has been added to a llama_sampler_chain (via llama_sampler_chain_add)
1128
+ LLAMA_API void llama_sampler_free ( struct llama_sampler * smpl);
1129
+
1130
+ // llama_sampler_chain
1131
+ // a type of llama_sampler that can chain multiple samplers one after another
1132
+
1133
+ LLAMA_API struct llama_sampler * llama_sampler_chain_init(struct llama_sampler_chain_params params);
1134
+
1135
+ // important: takes ownership of the sampler object and will free it when llama_sampler_free is called
1136
+ LLAMA_API void llama_sampler_chain_add( struct llama_sampler * chain, struct llama_sampler * smpl);
1137
+ LLAMA_API struct llama_sampler * llama_sampler_chain_get(const struct llama_sampler * chain, int32_t i);
1138
+ LLAMA_API int llama_sampler_chain_n (const struct llama_sampler * chain);
1139
+
1140
+ // after removing a sampler, the chain will no longer own it, and it will not be freed when the chain is freed
1141
+ LLAMA_API struct llama_sampler * llama_sampler_chain_remove( struct llama_sampler * chain, int32_t i);
1142
+
1143
+ // available samplers:
1144
+
1145
+ LLAMA_API struct llama_sampler * llama_sampler_init_greedy(void);
1146
+ LLAMA_API struct llama_sampler * llama_sampler_init_dist (uint32_t seed);
1147
+
1148
+ /// @details Sorts candidate tokens by their logits in descending order and calculate probabilities based on logits.
1149
+ /// NOTE: Avoid using on the full vocabulary as the sorting can become slow. For example, apply top-k or top-p sampling first.
1150
+ DEPRECATED(LLAMA_API struct llama_sampler * llama_sampler_init_softmax (void),
1151
+ "will be removed in the future (see https://github.com/ggerganov/llama.cpp/pull/9896#discussion_r1800920915)");
1152
+
1153
+ /// @details Top-K sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
1154
+ LLAMA_API struct llama_sampler * llama_sampler_init_top_k (int32_t k);
1155
+
1156
+ /// @details Nucleus sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
1157
+ LLAMA_API struct llama_sampler * llama_sampler_init_top_p (float p, size_t min_keep);
1158
+
1159
+ /// @details Minimum P sampling as described in https://github.com/ggerganov/llama.cpp/pull/3841
1160
+ LLAMA_API struct llama_sampler * llama_sampler_init_min_p (float p, size_t min_keep);
1161
+
1162
+ /// @details Locally Typical Sampling implementation described in the paper https://arxiv.org/abs/2202.00666.
1163
+ LLAMA_API struct llama_sampler * llama_sampler_init_typical (float p, size_t min_keep);
1164
+
1165
+ /// #details Updates the logits l_i` = l_i/t. When t <= 0.0f, the maximum logit is kept at it's original value, the rest are set to -inf
1166
+ LLAMA_API struct llama_sampler * llama_sampler_init_temp (float t);
1167
+
1168
+ /// @details Dynamic temperature implementation (a.k.a. entropy) described in the paper https://arxiv.org/abs/2309.02772.
1169
+ LLAMA_API struct llama_sampler * llama_sampler_init_temp_ext (float t, float delta, float exponent);
1170
+
1171
+ /// @details XTC sampler as described in https://github.com/oobabooga/text-generation-webui/pull/6335
1172
+ LLAMA_API struct llama_sampler * llama_sampler_init_xtc (float p, float t, size_t min_keep, uint32_t seed);
1173
+
1174
+ /// @details Mirostat 1.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
1175
+ /// @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.
1176
+ /// @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.
1177
+ /// @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.
1178
+ /// @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.
1179
+ /// @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.
1180
+ LLAMA_API struct llama_sampler * llama_sampler_init_mirostat(
1181
+ int32_t n_vocab,
1182
+ uint32_t seed,
1183
+ float tau,
1184
+ float eta,
1185
+ int32_t m);
1186
+
1187
+ /// @details Mirostat 2.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
1188
+ /// @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.
1189
+ /// @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.
1190
+ /// @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.
1191
+ /// @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.
1192
+ LLAMA_API struct llama_sampler * llama_sampler_init_mirostat_v2(
1193
+ uint32_t seed,
1194
+ float tau,
1195
+ float eta);
1196
+
1197
+ LLAMA_API struct llama_sampler * llama_sampler_init_grammar(
1198
+ const struct llama_vocab * vocab,
1199
+ const char * grammar_str,
1200
+ const char * grammar_root);
1201
+
1202
+ /// NOTE: Avoid using on the full vocabulary as searching for repeated tokens can become slow. For example, apply top-k or top-p sampling first.
1203
+ LLAMA_API struct llama_sampler * llama_sampler_init_penalties(
1204
+ int32_t penalty_last_n, // last n tokens to penalize (0 = disable penalty, -1 = context size)
1205
+ float penalty_repeat, // 1.0 = disabled
1206
+ float penalty_freq, // 0.0 = disabled
1207
+ float penalty_present); // 0.0 = disabled
1208
+
1209
+ /// @details DRY sampler, designed by p-e-w, as described in: https://github.com/oobabooga/text-generation-webui/pull/5677, porting Koboldcpp implementation authored by pi6am: https://github.com/LostRuins/koboldcpp/pull/982
1210
+ LLAMA_API struct llama_sampler * llama_sampler_init_dry(
1211
+ const struct llama_vocab * vocab,
1212
+ int32_t n_ctx_train,
1213
+ float dry_multiplier,
1214
+ float dry_base,
1215
+ int32_t dry_allowed_length,
1216
+ int32_t dry_penalty_last_n,
1217
+ const char ** seq_breakers,
1218
+ size_t num_breakers);
1219
+
1220
+ LLAMA_API struct llama_sampler * llama_sampler_init_logit_bias(
1221
+ int32_t n_vocab,
1222
+ int32_t n_logit_bias,
1223
+ const llama_logit_bias * logit_bias);
1224
+
1225
+ // this sampler is meant to be used for fill-in-the-middle infilling
1226
+ // it's supposed to be used after top_k + top_p sampling
1227
+ //
1228
+ // 1. if the sum of the EOG probs times the number of candidates is higher than the sum of the other probs -> pick EOG
1229
+ // 2. combine probs of tokens that have the same prefix
1230
+ //
1231
+ // example:
1232
+ //
1233
+ // - before:
1234
+ // "hel": 0.5
1235
+ // "hell": 0.2
1236
+ // "hello": 0.1
1237
+ // "dummy": 0.1
1238
+ //
1239
+ // - after:
1240
+ // "hel": 0.8
1241
+ // "dummy": 0.1
1242
+ //
1243
+ // 3. discard non-EOG tokens with low prob
1244
+ // 4. if no tokens are left -> pick EOT
1245
+ //
1246
+ LLAMA_API struct llama_sampler * llama_sampler_init_infill(const struct llama_vocab * vocab);
1247
+
1248
+ // Returns the seed used by the sampler if applicable, LLAMA_DEFAULT_SEED otherwise
1249
+ LLAMA_API uint32_t llama_sampler_get_seed(const struct llama_sampler * smpl);
1250
+
1251
+ /// @details Sample and accept a token from the idx-th output of the last evaluation
1252
+ //
1253
+ // Shorthand for:
1254
+ // const auto * logits = llama_get_logits_ith(ctx, idx);
1255
+ // llama_token_data_array cur_p = { ... init from logits ... };
1256
+ // llama_sampler_apply(smpl, &cur_p);
1257
+ // auto token = cur_p.data[cur_p.selected].id;
1258
+ // llama_sampler_accept(smpl, token);
1259
+ // return token;
1260
+ // Returns the sampled token
1261
+ LLAMA_API llama_token llama_sampler_sample(struct llama_sampler * smpl, struct llama_context * ctx, int32_t idx);
1262
+
1263
+ // TODO: extend in the future
1264
+ //LLAMA_API void llama_decode_with_sampler(struct llama_context * ctx, struct llama_sampler * smpl, struct llama_batch batch, ...);
1265
+
1266
+ //
1267
+ // Model split
1268
+ //
1269
+
1270
+ /// @details Build a split GGUF final path for this chunk.
1271
+ /// 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"
1272
+ // Returns the split_path length.
1273
+ LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count);
1274
+
1275
+ /// @details Extract the path prefix from the split_path if and only if the split_no and split_count match.
1276
+ /// llama_split_prefix(split_prefix, 64, "/models/ggml-model-q4_0-00002-of-00004.gguf", 2, 4) => split_prefix = "/models/ggml-model-q4_0"
1277
+ // Returns the split_prefix length.
1278
+ LLAMA_API int llama_split_prefix(char * split_prefix, size_t maxlen, const char * split_path, int split_no, int split_count);
1279
+
1280
+ // Print system information
1281
+ LLAMA_API const char * llama_print_system_info(void);
1282
+
1283
+ // Set callback for all future logging events.
1284
+ // If this is not called, or NULL is supplied, everything is output on stderr.
1285
+ LLAMA_API void llama_log_set(lm_ggml_log_callback log_callback, void * user_data);
1286
+
1287
+ //
1288
+ // Performance utils
1289
+ //
1290
+ // NOTE: Used by llama.cpp examples, avoid using in third-party apps. Instead, do your own performance measurements.
1291
+ //
1292
+
1293
+ struct llama_perf_context_data {
1294
+ double t_start_ms;
1295
+ double t_load_ms;
1296
+ double t_p_eval_ms;
1297
+ double t_eval_ms;
1298
+
1299
+ int32_t n_p_eval;
1300
+ int32_t n_eval;
1301
+ };
1302
+
1303
+ struct llama_perf_sampler_data {
1304
+ double t_sample_ms;
1305
+
1306
+ int32_t n_sample;
1307
+ };
1308
+
1309
+ LLAMA_API struct llama_perf_context_data llama_perf_context (const struct llama_context * ctx);
1310
+ LLAMA_API void llama_perf_context_print(const struct llama_context * ctx);
1311
+ LLAMA_API void llama_perf_context_reset( struct llama_context * ctx);
1312
+
1313
+ // NOTE: the following work only with samplers constructed via llama_sampler_chain_init
1314
+ LLAMA_API struct llama_perf_sampler_data llama_perf_sampler (const struct llama_sampler * chain);
1315
+ LLAMA_API void llama_perf_sampler_print(const struct llama_sampler * chain);
1316
+ LLAMA_API void llama_perf_sampler_reset( struct llama_sampler * chain);
1317
+
1318
+ #ifdef __cplusplus
1319
+ }
1320
+ #endif
1321
+
1322
+
1323
+ #endif // LLAMA_H