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