llama-cpp-pro 0.2.2

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 (310) hide show
  1. package/CHANGELOG.md +295 -0
  2. package/LICENSE +21 -0
  3. package/LlamaCpp.podspec +33 -0
  4. package/LlamaCppCapacitor.podspec +33 -0
  5. package/Package.swift +29 -0
  6. package/README.md +93 -0
  7. package/android/build.gradle +88 -0
  8. package/android/src/main/AndroidManifest.xml +4 -0
  9. package/android/src/main/CMakeLists-arm64.txt +138 -0
  10. package/android/src/main/CMakeLists-x86_64.txt +141 -0
  11. package/android/src/main/CMakeLists.txt +138 -0
  12. package/android/src/main/java/ai/annadata/plugin/capacitor/LlamaCpp.java +1340 -0
  13. package/android/src/main/java/ai/annadata/plugin/capacitor/LlamaCppPlugin.java +814 -0
  14. package/android/src/main/java/ai/annadata/plugin/capacitor/ModelAdmissionController.java +214 -0
  15. package/android/src/main/jni-chat-session.cpp +261 -0
  16. package/android/src/main/jni-lora.cpp +197 -0
  17. package/android/src/main/jni-multimodal.cpp +167 -0
  18. package/android/src/main/jni-tts.cpp +290 -0
  19. package/android/src/main/jni-utils.h +148 -0
  20. package/android/src/main/jni.cpp +1808 -0
  21. package/android/src/main/jniLibs/arm64-v8a/libllama-cpp-arm64.so +0 -0
  22. package/android/src/main/res/.gitkeep +0 -0
  23. package/build-native.sh +280 -0
  24. package/cmake/desktop-metal-embed.cmake +30 -0
  25. package/cmake/desktop-sources.cmake +100 -0
  26. package/cmake/ggml-backends.cmake +44 -0
  27. package/cpp/LICENSE +21 -0
  28. package/cpp/README.md +15 -0
  29. package/cpp/anyascii.c +22223 -0
  30. package/cpp/anyascii.h +42 -0
  31. package/cpp/cap-completion.cpp +942 -0
  32. package/cpp/cap-completion.h +127 -0
  33. package/cpp/cap-embedding.cpp +193 -0
  34. package/cpp/cap-embedding.h +35 -0
  35. package/cpp/cap-ios-bridge.cpp +1810 -0
  36. package/cpp/cap-ios-bridge.h +61 -0
  37. package/cpp/cap-llama.cpp +412 -0
  38. package/cpp/cap-llama.h +161 -0
  39. package/cpp/cap-mtmd.hpp +602 -0
  40. package/cpp/cap-native-server.cpp +1095 -0
  41. package/cpp/cap-native-server.h +40 -0
  42. package/cpp/cap-tts.cpp +591 -0
  43. package/cpp/cap-tts.h +59 -0
  44. package/cpp/cap-wasm-fs.cpp +156 -0
  45. package/cpp/cap-wasm-jspi.cpp +19 -0
  46. package/cpp/cap-wasm-jspi.h +30 -0
  47. package/cpp/cap-wasm-vfs.cpp +22 -0
  48. package/cpp/chat-parser.cpp +393 -0
  49. package/cpp/chat-parser.h +120 -0
  50. package/cpp/chat.cpp +2315 -0
  51. package/cpp/chat.h +221 -0
  52. package/cpp/common.cpp +1664 -0
  53. package/cpp/common.h +744 -0
  54. package/cpp/ggml-alloc.c +1028 -0
  55. package/cpp/ggml-alloc.h +76 -0
  56. package/cpp/ggml-backend-impl.h +255 -0
  57. package/cpp/ggml-backend-reg.cpp +600 -0
  58. package/cpp/ggml-backend.cpp +2121 -0
  59. package/cpp/ggml-backend.h +354 -0
  60. package/cpp/ggml-common.h +1878 -0
  61. package/cpp/ggml-cpp.h +39 -0
  62. package/cpp/ggml-cpu/amx/amx.cpp +221 -0
  63. package/cpp/ggml-cpu/amx/amx.h +8 -0
  64. package/cpp/ggml-cpu/amx/common.h +91 -0
  65. package/cpp/ggml-cpu/amx/mmq.cpp +2512 -0
  66. package/cpp/ggml-cpu/amx/mmq.h +10 -0
  67. package/cpp/ggml-cpu/arch/arm/cpu-feats.cpp +94 -0
  68. package/cpp/ggml-cpu/arch/arm/quants.c +3650 -0
  69. package/cpp/ggml-cpu/arch/arm/repack.cpp +1891 -0
  70. package/cpp/ggml-cpu/arch/x86/cpu-feats.cpp +327 -0
  71. package/cpp/ggml-cpu/arch/x86/quants.c +3820 -0
  72. package/cpp/ggml-cpu/arch/x86/repack.cpp +6307 -0
  73. package/cpp/ggml-cpu/arch-fallback.h +215 -0
  74. package/cpp/ggml-cpu/binary-ops.cpp +158 -0
  75. package/cpp/ggml-cpu/binary-ops.h +16 -0
  76. package/cpp/ggml-cpu/common.h +73 -0
  77. package/cpp/ggml-cpu/ggml-cpu-impl.h +559 -0
  78. package/cpp/ggml-cpu/ggml-cpu.c +3578 -0
  79. package/cpp/ggml-cpu/ggml-cpu.cpp +672 -0
  80. package/cpp/ggml-cpu/ops.cpp +10587 -0
  81. package/cpp/ggml-cpu/ops.h +114 -0
  82. package/cpp/ggml-cpu/quants.c +1193 -0
  83. package/cpp/ggml-cpu/quants.h +97 -0
  84. package/cpp/ggml-cpu/repack.cpp +1982 -0
  85. package/cpp/ggml-cpu/repack.h +120 -0
  86. package/cpp/ggml-cpu/simd-mappings.h +1184 -0
  87. package/cpp/ggml-cpu/traits.cpp +36 -0
  88. package/cpp/ggml-cpu/traits.h +38 -0
  89. package/cpp/ggml-cpu/unary-ops.cpp +186 -0
  90. package/cpp/ggml-cpu/unary-ops.h +28 -0
  91. package/cpp/ggml-cpu/vec.cpp +348 -0
  92. package/cpp/ggml-cpu/vec.h +1121 -0
  93. package/cpp/ggml-cpu.h +145 -0
  94. package/cpp/ggml-impl.h +622 -0
  95. package/cpp/ggml-metal-impl.h +688 -0
  96. package/cpp/ggml-metal.h +66 -0
  97. package/cpp/ggml-metal.m +6833 -0
  98. package/cpp/ggml-metal.metal +10754 -0
  99. package/cpp/ggml-opt.cpp +1093 -0
  100. package/cpp/ggml-opt.h +256 -0
  101. package/cpp/ggml-quants.c +5324 -0
  102. package/cpp/ggml-quants.h +106 -0
  103. package/cpp/ggml-threading.cpp +12 -0
  104. package/cpp/ggml-threading.h +14 -0
  105. package/cpp/ggml.c +7108 -0
  106. package/cpp/ggml.h +2492 -0
  107. package/cpp/gguf.cpp +1358 -0
  108. package/cpp/gguf.h +202 -0
  109. package/cpp/json-partial.cpp +256 -0
  110. package/cpp/json-partial.h +38 -0
  111. package/cpp/json-schema-to-grammar.cpp +985 -0
  112. package/cpp/json-schema-to-grammar.h +21 -0
  113. package/cpp/llama-adapter.cpp +388 -0
  114. package/cpp/llama-adapter.h +76 -0
  115. package/cpp/llama-arch.cpp +2355 -0
  116. package/cpp/llama-arch.h +499 -0
  117. package/cpp/llama-batch.cpp +875 -0
  118. package/cpp/llama-batch.h +160 -0
  119. package/cpp/llama-chat.cpp +783 -0
  120. package/cpp/llama-chat.h +65 -0
  121. package/cpp/llama-context.cpp +2788 -0
  122. package/cpp/llama-context.h +306 -0
  123. package/cpp/llama-cparams.cpp +5 -0
  124. package/cpp/llama-cparams.h +41 -0
  125. package/cpp/llama-cpp.h +30 -0
  126. package/cpp/llama-grammar.cpp +1229 -0
  127. package/cpp/llama-grammar.h +173 -0
  128. package/cpp/llama-graph.cpp +1891 -0
  129. package/cpp/llama-graph.h +810 -0
  130. package/cpp/llama-hparams.cpp +180 -0
  131. package/cpp/llama-hparams.h +233 -0
  132. package/cpp/llama-impl.cpp +167 -0
  133. package/cpp/llama-impl.h +61 -0
  134. package/cpp/llama-io.cpp +15 -0
  135. package/cpp/llama-io.h +35 -0
  136. package/cpp/llama-kv-cache-iswa.cpp +318 -0
  137. package/cpp/llama-kv-cache-iswa.h +135 -0
  138. package/cpp/llama-kv-cache.cpp +2059 -0
  139. package/cpp/llama-kv-cache.h +374 -0
  140. package/cpp/llama-kv-cells.h +491 -0
  141. package/cpp/llama-memory-hybrid.cpp +258 -0
  142. package/cpp/llama-memory-hybrid.h +137 -0
  143. package/cpp/llama-memory-recurrent.cpp +1146 -0
  144. package/cpp/llama-memory-recurrent.h +179 -0
  145. package/cpp/llama-memory.cpp +59 -0
  146. package/cpp/llama-memory.h +119 -0
  147. package/cpp/llama-mmap.cpp +609 -0
  148. package/cpp/llama-mmap.h +68 -0
  149. package/cpp/llama-model-loader.cpp +1166 -0
  150. package/cpp/llama-model-loader.h +170 -0
  151. package/cpp/llama-model-saver.cpp +282 -0
  152. package/cpp/llama-model-saver.h +37 -0
  153. package/cpp/llama-model.cpp +19061 -0
  154. package/cpp/llama-model.h +491 -0
  155. package/cpp/llama-sampling.cpp +2575 -0
  156. package/cpp/llama-sampling.h +32 -0
  157. package/cpp/llama-vocab.cpp +3792 -0
  158. package/cpp/llama-vocab.h +176 -0
  159. package/cpp/llama.cpp +358 -0
  160. package/cpp/llama.h +1373 -0
  161. package/cpp/log.cpp +428 -0
  162. package/cpp/log.h +103 -0
  163. package/cpp/minja/chat-template.hpp +550 -0
  164. package/cpp/minja/minja.hpp +3009 -0
  165. package/cpp/nlohmann/json.hpp +25526 -0
  166. package/cpp/nlohmann/json_fwd.hpp +187 -0
  167. package/cpp/regex-partial.cpp +204 -0
  168. package/cpp/regex-partial.h +56 -0
  169. package/cpp/sampling.cpp +579 -0
  170. package/cpp/sampling.h +107 -0
  171. package/cpp/tools/mtmd/clip-impl.h +473 -0
  172. package/cpp/tools/mtmd/clip.cpp +4322 -0
  173. package/cpp/tools/mtmd/clip.h +106 -0
  174. package/cpp/tools/mtmd/miniaudio/miniaudio.h +93468 -0
  175. package/cpp/tools/mtmd/mtmd-audio.cpp +769 -0
  176. package/cpp/tools/mtmd/mtmd-audio.h +47 -0
  177. package/cpp/tools/mtmd/mtmd-helper.cpp +460 -0
  178. package/cpp/tools/mtmd/mtmd-helper.h +95 -0
  179. package/cpp/tools/mtmd/mtmd.cpp +1066 -0
  180. package/cpp/tools/mtmd/mtmd.h +302 -0
  181. package/cpp/tools/mtmd/stb/stb_image.h +7988 -0
  182. package/cpp/unicode-data.cpp +7034 -0
  183. package/cpp/unicode-data.h +20 -0
  184. package/cpp/unicode.cpp +1061 -0
  185. package/cpp/unicode.h +68 -0
  186. package/cpp/vendor/cpp-httplib/httplib.cpp +16509 -0
  187. package/cpp/vendor/cpp-httplib/httplib.h +3883 -0
  188. package/desktop/electron-builder.config.cjs +157 -0
  189. package/desktop/entitlements.mac.plist +12 -0
  190. package/desktop/package.json +11 -0
  191. package/desktop/resolve-package-root.cjs +88 -0
  192. package/desktop/src/main/backend-selector.cjs +148 -0
  193. package/desktop/src/main/gpu-probe.cjs +142 -0
  194. package/desktop/src/main/index.cjs +58 -0
  195. package/desktop/src/main/ipc-handlers.cjs +212 -0
  196. package/desktop/src/main/model-store.cjs +50 -0
  197. package/desktop/src/main/preload.cjs +39 -0
  198. package/desktop/src/main/sidecar-client.cjs +76 -0
  199. package/desktop/src/main/sidecar-manager.cjs +364 -0
  200. package/dist/docs.json +14357 -0
  201. package/dist/esm/definitions.d.ts +731 -0
  202. package/dist/esm/definitions.js +2 -0
  203. package/dist/esm/definitions.js.map +1 -0
  204. package/dist/esm/desktop.d.ts +37 -0
  205. package/dist/esm/desktop.js +133 -0
  206. package/dist/esm/desktop.js.map +1 -0
  207. package/dist/esm/index.d.ts +200 -0
  208. package/dist/esm/index.js +612 -0
  209. package/dist/esm/index.js.map +1 -0
  210. package/dist/esm/isomorphic/desktop.runtime.d.ts +37 -0
  211. package/dist/esm/isomorphic/desktop.runtime.js +36 -0
  212. package/dist/esm/isomorphic/desktop.runtime.js.map +1 -0
  213. package/dist/esm/isomorphic/errors.d.ts +6 -0
  214. package/dist/esm/isomorphic/errors.js +9 -0
  215. package/dist/esm/isomorphic/errors.js.map +1 -0
  216. package/dist/esm/isomorphic/model.admission.d.ts +17 -0
  217. package/dist/esm/isomorphic/model.admission.js +27 -0
  218. package/dist/esm/isomorphic/model.admission.js.map +1 -0
  219. package/dist/esm/isomorphic/model.scheduler.d.ts +31 -0
  220. package/dist/esm/isomorphic/model.scheduler.js +95 -0
  221. package/dist/esm/isomorphic/model.scheduler.js.map +1 -0
  222. package/dist/esm/isomorphic/provider.desktop.d.ts +40 -0
  223. package/dist/esm/isomorphic/provider.desktop.js +411 -0
  224. package/dist/esm/isomorphic/provider.desktop.js.map +1 -0
  225. package/dist/esm/isomorphic/provider.factory.d.ts +2 -0
  226. package/dist/esm/isomorphic/provider.factory.js +16 -0
  227. package/dist/esm/isomorphic/provider.factory.js.map +1 -0
  228. package/dist/esm/isomorphic/provider.interface.d.ts +76 -0
  229. package/dist/esm/isomorphic/provider.interface.js +2 -0
  230. package/dist/esm/isomorphic/provider.interface.js.map +1 -0
  231. package/dist/esm/isomorphic/provider.native.d.ts +18 -0
  232. package/dist/esm/isomorphic/provider.native.js +173 -0
  233. package/dist/esm/isomorphic/provider.native.js.map +1 -0
  234. package/dist/esm/isomorphic/provider.web.d.ts +88 -0
  235. package/dist/esm/isomorphic/provider.web.js +573 -0
  236. package/dist/esm/isomorphic/provider.web.js.map +1 -0
  237. package/dist/esm/isomorphic/sidecar-sse.d.ts +14 -0
  238. package/dist/esm/isomorphic/sidecar-sse.js +76 -0
  239. package/dist/esm/isomorphic/sidecar-sse.js.map +1 -0
  240. package/dist/esm/isomorphic/wasmMemoryCalibration.d.ts +26 -0
  241. package/dist/esm/isomorphic/wasmMemoryCalibration.js +60 -0
  242. package/dist/esm/isomorphic/wasmMemoryCalibration.js.map +1 -0
  243. package/dist/esm/isomorphic/wasmMemoryPolicy.d.ts +55 -0
  244. package/dist/esm/isomorphic/wasmMemoryPolicy.js +93 -0
  245. package/dist/esm/isomorphic/wasmMemoryPolicy.js.map +1 -0
  246. package/dist/esm/storage/manifest.d.ts +13 -0
  247. package/dist/esm/storage/manifest.js +87 -0
  248. package/dist/esm/storage/manifest.js.map +1 -0
  249. package/dist/esm/storage/opfs.store.d.ts +31 -0
  250. package/dist/esm/storage/opfs.store.js +241 -0
  251. package/dist/esm/storage/opfs.store.js.map +1 -0
  252. package/dist/esm/web.d.ts +206 -0
  253. package/dist/esm/web.js +521 -0
  254. package/dist/esm/web.js.map +1 -0
  255. package/dist/esm/workers/async-file.d.ts +13 -0
  256. package/dist/esm/workers/async-file.js +12 -0
  257. package/dist/esm/workers/async-file.js.map +1 -0
  258. package/dist/esm/workers/heapfs.d.ts +55 -0
  259. package/dist/esm/workers/heapfs.js +115 -0
  260. package/dist/esm/workers/heapfs.js.map +1 -0
  261. package/dist/esm/workers/wasm.engine.d.ts +86 -0
  262. package/dist/esm/workers/wasm.engine.js +504 -0
  263. package/dist/esm/workers/wasm.engine.js.map +1 -0
  264. package/dist/esm/workers/worker.protocol.d.ts +160 -0
  265. package/dist/esm/workers/worker.protocol.js +2 -0
  266. package/dist/esm/workers/worker.protocol.js.map +1 -0
  267. package/dist/plugin.cjs +3179 -0
  268. package/dist/plugin.cjs.map +1 -0
  269. package/dist/plugin.js +3181 -0
  270. package/dist/plugin.js.map +1 -0
  271. package/dist/wasm/llama_engine.d.ts +74 -0
  272. package/dist/wasm/llama_engine.js +1829 -0
  273. package/dist/wasm/llama_engine.wasm +0 -0
  274. package/dist/wasm/llama_engine_emscripten.mjs +2 -0
  275. package/dist/wasm/package.json +16 -0
  276. package/dist/workers/llm.worker.js +1226 -0
  277. package/dist/workers/llm.worker.js.map +7 -0
  278. package/extraResources/llama-wasm/llama_engine.d.ts +74 -0
  279. package/extraResources/llama-wasm/llama_engine.js +1829 -0
  280. package/extraResources/llama-wasm/llama_engine.wasm +0 -0
  281. package/extraResources/llama-wasm/llama_engine_emscripten.mjs +2 -0
  282. package/extraResources/llama-wasm/package.json +16 -0
  283. package/extraResources/sidecar/README.md +11 -0
  284. package/extraResources/sidecar/darwin-arm64 +0 -0
  285. package/extraResources/sidecar/darwin-x64 +0 -0
  286. package/ios/CMakeLists-arm64.txt +161 -0
  287. package/ios/CMakeLists-x86_64.txt +188 -0
  288. package/ios/CMakeLists.txt +161 -0
  289. package/ios/Frameworks/llama-cpp.framework/Info.plist +28 -0
  290. package/ios/Frameworks/llama-cpp.framework/llama-cpp +0 -0
  291. package/ios/Sources/LlamaCppCapacitor/LlamaCpp.swift +1365 -0
  292. package/ios/Sources/LlamaCppCapacitor/LlamaCppPlugin.swift +694 -0
  293. package/ios/Sources/LlamaCppCapacitor/LlamaNativeBridge.swift +349 -0
  294. package/ios/Sources/LlamaCppCapacitor/ModelAdmissionController.swift +177 -0
  295. package/ios/embed-metal-shaders.sh +24 -0
  296. package/ios/metal-embed.cmake +29 -0
  297. package/package.json +281 -0
  298. package/scripts/build-js-preserve-wasm.cjs +53 -0
  299. package/scripts/build-sidecar-linux.sh +6 -0
  300. package/scripts/build-sidecar-win.bat +19 -0
  301. package/scripts/build-sidecar.sh +184 -0
  302. package/scripts/embed-llama-ios-app-framework.sh +63 -0
  303. package/scripts/ensure-desktop-sidecar-bundle.cjs +103 -0
  304. package/scripts/ensure-llama-ios-xcframework.sh +108 -0
  305. package/scripts/fix-esm-extensions.cjs +45 -0
  306. package/scripts/prepare-js-dist.cjs +28 -0
  307. package/scripts/stage-desktop-resources.cjs +116 -0
  308. package/sidecar/CMakeLists.txt +192 -0
  309. package/sidecar/cap-sidecar-main.cpp +68 -0
  310. package/types/llama-cpp-pro.d.ts +441 -0
package/cpp/common.h ADDED
@@ -0,0 +1,744 @@
1
+ // Various helper functions and utilities
2
+
3
+ #pragma once
4
+
5
+ #include <set>
6
+ #include <sstream>
7
+ #include <string>
8
+ #include <string_view>
9
+ #include <vector>
10
+ #include <map>
11
+ #include <sstream>
12
+ #include <cmath>
13
+
14
+ #include "ggml-opt.h"
15
+ #include "llama-cpp.h"
16
+
17
+ #ifdef _WIN32
18
+ #define DIRECTORY_SEPARATOR '\\'
19
+ #else
20
+ #define DIRECTORY_SEPARATOR '/'
21
+ #endif // _WIN32
22
+
23
+ #define die(msg) do { fputs("error: " msg "\n", stderr); exit(1); } while (0)
24
+ #define die_fmt(fmt, ...) do { fprintf(stderr, "error: " fmt "\n", __VA_ARGS__); exit(1); } while (0)
25
+
26
+ #define print_build_info() do { \
27
+ fprintf(stderr, "%s: build = %d (%s)\n", __func__, LLAMA_BUILD_NUMBER, LLAMA_COMMIT); \
28
+ fprintf(stderr, "%s: built with %s for %s\n", __func__, LLAMA_COMPILER, LLAMA_BUILD_TARGET); \
29
+ } while(0)
30
+
31
+ #define DEFAULT_MODEL_PATH "models/7B/ggml-model-f16.gguf"
32
+
33
+ struct common_adapter_lora_info {
34
+ std::string path;
35
+ float scale;
36
+
37
+ struct llama_adapter_lora * ptr;
38
+ };
39
+
40
+ using llama_tokens = std::vector<llama_token>;
41
+
42
+ // build info
43
+ extern int LLAMA_BUILD_NUMBER;
44
+ extern const char * LLAMA_COMMIT;
45
+ extern const char * LLAMA_COMPILER;
46
+ extern const char * LLAMA_BUILD_TARGET;
47
+
48
+ struct common_control_vector_load_info;
49
+
50
+ //
51
+ // CPU utils
52
+ //
53
+
54
+ struct cpu_params {
55
+ int n_threads = -1;
56
+ bool cpumask[LM_GGML_MAX_N_THREADS] = {false}; // CPU affinity mask.
57
+ bool mask_valid = false; // Default: any CPU
58
+ enum lm_ggml_sched_priority priority = LM_GGML_SCHED_PRIO_NORMAL; // Scheduling prio : (0 - normal, 1 - medium, 2 - high, 3 - realtime)
59
+ bool strict_cpu = false; // Use strict CPU placement
60
+ uint32_t poll = 50; // Polling (busywait) level (0 - no polling, 100 - mostly polling)
61
+ };
62
+
63
+ int32_t cpu_get_num_physical_cores();
64
+ int32_t cpu_get_num_math();
65
+
66
+ //
67
+ // Common params
68
+ //
69
+
70
+ enum llama_example {
71
+ LLAMA_EXAMPLE_COMMON,
72
+ LLAMA_EXAMPLE_SPECULATIVE,
73
+ LLAMA_EXAMPLE_MAIN,
74
+ LLAMA_EXAMPLE_EMBEDDING,
75
+ LLAMA_EXAMPLE_PERPLEXITY,
76
+ LLAMA_EXAMPLE_RETRIEVAL,
77
+ LLAMA_EXAMPLE_PASSKEY,
78
+ LLAMA_EXAMPLE_IMATRIX,
79
+ LLAMA_EXAMPLE_BENCH,
80
+ LLAMA_EXAMPLE_SERVER,
81
+ LLAMA_EXAMPLE_CVECTOR_GENERATOR,
82
+ LLAMA_EXAMPLE_EXPORT_LORA,
83
+ LLAMA_EXAMPLE_MTMD,
84
+ LLAMA_EXAMPLE_LOOKUP,
85
+ LLAMA_EXAMPLE_PARALLEL,
86
+ LLAMA_EXAMPLE_TTS,
87
+ LLAMA_EXAMPLE_DIFFUSION,
88
+ LLAMA_EXAMPLE_FINETUNE,
89
+
90
+ LLAMA_EXAMPLE_COUNT,
91
+ };
92
+
93
+ enum common_sampler_type {
94
+ COMMON_SAMPLER_TYPE_NONE = 0,
95
+ COMMON_SAMPLER_TYPE_DRY = 1,
96
+ COMMON_SAMPLER_TYPE_TOP_K = 2,
97
+ COMMON_SAMPLER_TYPE_TOP_P = 3,
98
+ COMMON_SAMPLER_TYPE_MIN_P = 4,
99
+ //COMMON_SAMPLER_TYPE_TFS_Z = 5,
100
+ COMMON_SAMPLER_TYPE_TYPICAL_P = 6,
101
+ COMMON_SAMPLER_TYPE_TEMPERATURE = 7,
102
+ COMMON_SAMPLER_TYPE_XTC = 8,
103
+ COMMON_SAMPLER_TYPE_INFILL = 9,
104
+ COMMON_SAMPLER_TYPE_PENALTIES = 10,
105
+ COMMON_SAMPLER_TYPE_TOP_N_SIGMA = 11,
106
+ };
107
+
108
+ // dimensionality reduction methods, used by cvector-generator
109
+ enum dimre_method {
110
+ DIMRE_METHOD_PCA,
111
+ DIMRE_METHOD_MEAN,
112
+ };
113
+
114
+ enum common_conversation_mode {
115
+ COMMON_CONVERSATION_MODE_DISABLED = 0,
116
+ COMMON_CONVERSATION_MODE_ENABLED = 1,
117
+ COMMON_CONVERSATION_MODE_AUTO = 2,
118
+ };
119
+
120
+ enum common_grammar_trigger_type {
121
+ COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN,
122
+ COMMON_GRAMMAR_TRIGGER_TYPE_WORD,
123
+ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN,
124
+ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL,
125
+ };
126
+
127
+ struct common_grammar_trigger {
128
+ common_grammar_trigger_type type;
129
+ std::string value;
130
+ llama_token token = LLAMA_TOKEN_NULL;
131
+ };
132
+
133
+ // sampling parameters
134
+ struct common_params_sampling {
135
+ uint32_t seed = LLAMA_DEFAULT_SEED; // the seed used to initialize llama_sampler
136
+
137
+ int32_t n_prev = 64; // number of previous tokens to remember
138
+ int32_t n_probs = 0; // if greater than 0, output the probabilities of top n_probs tokens.
139
+ int32_t min_keep = 0; // 0 = disabled, otherwise samplers should return at least min_keep tokens
140
+ int32_t top_k = 40; // <= 0 to use vocab size
141
+ float top_p = 0.95f; // 1.0 = disabled
142
+ float min_p = 0.05f; // 0.0 = disabled
143
+ float xtc_probability = 0.00f; // 0.0 = disabled
144
+ float xtc_threshold = 0.10f; // > 0.5 disables XTC
145
+ float typ_p = 1.00f; // typical_p, 1.0 = disabled
146
+ float temp = 0.80f; // <= 0.0 to sample greedily, 0.0 to not output probabilities
147
+ float dynatemp_range = 0.00f; // 0.0 = disabled
148
+ float dynatemp_exponent = 1.00f; // controls how entropy maps to temperature in dynamic temperature sampler
149
+ int32_t penalty_last_n = 64; // last n tokens to penalize (0 = disable penalty, -1 = context size)
150
+ float penalty_repeat = 1.00f; // 1.0 = disabled
151
+ float penalty_freq = 0.00f; // 0.0 = disabled
152
+ float penalty_present = 0.00f; // 0.0 = disabled
153
+ float dry_multiplier = 0.0f; // 0.0 = disabled; DRY repetition penalty for tokens extending repetition:
154
+ float dry_base = 1.75f; // 0.0 = disabled; multiplier * base ^ (length of sequence before token - allowed length)
155
+ int32_t dry_allowed_length = 2; // tokens extending repetitions beyond this receive penalty
156
+ int32_t dry_penalty_last_n = -1; // how many tokens to scan for repetitions (0 = disable penalty, -1 = context size)
157
+ int32_t mirostat = 0; // 0 = disabled, 1 = mirostat, 2 = mirostat 2.0
158
+ float top_n_sigma = -1.00f;// -1.0 = disabled
159
+ float mirostat_tau = 5.00f; // target entropy
160
+ float mirostat_eta = 0.10f; // learning rate
161
+ bool ignore_eos = false;
162
+ bool no_perf = false; // disable performance metrics
163
+ bool timing_per_token = false;
164
+
165
+ std::vector<std::string> dry_sequence_breakers = {"\n", ":", "\"", "*"}; // default sequence breakers for DRY
166
+
167
+
168
+ std::vector<enum common_sampler_type> samplers = {
169
+ COMMON_SAMPLER_TYPE_PENALTIES,
170
+ COMMON_SAMPLER_TYPE_DRY,
171
+ COMMON_SAMPLER_TYPE_TOP_N_SIGMA,
172
+ COMMON_SAMPLER_TYPE_TOP_K,
173
+ COMMON_SAMPLER_TYPE_TYPICAL_P,
174
+ COMMON_SAMPLER_TYPE_TOP_P,
175
+ COMMON_SAMPLER_TYPE_MIN_P,
176
+ COMMON_SAMPLER_TYPE_XTC,
177
+ COMMON_SAMPLER_TYPE_TEMPERATURE,
178
+ };
179
+
180
+ std::string grammar; // optional BNF-like grammar to constrain sampling
181
+ bool grammar_lazy = false;
182
+ std::vector<common_grammar_trigger> grammar_triggers; // optional triggers (for lazy grammars)
183
+ std::set<llama_token> preserved_tokens;
184
+
185
+ std::vector<llama_logit_bias> logit_bias; // logit biases to apply
186
+ std::vector<llama_logit_bias> logit_bias_eog; // pre-calculated logit biases for EOG tokens
187
+
188
+ // print the parameters into a string
189
+ std::string print() const;
190
+ };
191
+
192
+ struct common_params_model {
193
+ std::string path = ""; // model local path // NOLINT
194
+ std::string url = ""; // model url to download // NOLINT
195
+ std::string hf_repo = ""; // HF repo // NOLINT
196
+ std::string hf_file = ""; // HF file // NOLINT
197
+ };
198
+
199
+ struct common_params_speculative {
200
+ std::vector<lm_ggml_backend_dev_t> devices; // devices to use for offloading
201
+
202
+ int32_t n_ctx = 0; // draft context size
203
+ int32_t n_max = 16; // maximum number of tokens to draft during speculative decoding
204
+ int32_t n_min = 0; // minimum number of draft tokens to use for speculative decoding
205
+ int32_t n_gpu_layers = -1; // number of layers to store in VRAM for the draft model (-1 - use default)
206
+ float p_split = 0.1f; // speculative decoding split probability
207
+ float p_min = 0.75f; // minimum speculative decoding probability (greedy)
208
+ std::vector<std::pair<std::string, std::string>> replacements; // main to speculative model replacements
209
+ std::vector<llama_model_tensor_buft_override> tensor_buft_overrides;
210
+
211
+ lm_ggml_type cache_type_k = LM_GGML_TYPE_F16; // KV cache data type for the K
212
+ lm_ggml_type cache_type_v = LM_GGML_TYPE_F16; // KV cache data type for the V
213
+
214
+ struct cpu_params cpuparams;
215
+ struct cpu_params cpuparams_batch;
216
+
217
+ struct common_params_model model;
218
+ };
219
+
220
+ struct common_params_vocoder {
221
+ struct common_params_model model;
222
+
223
+ std::string speaker_file = ""; // speaker file path // NOLINT
224
+
225
+ bool use_guide_tokens = false; // enable guide tokens to improve TTS accuracy // NOLINT
226
+ };
227
+
228
+ struct common_params_diffusion {
229
+ int32_t steps = 128;
230
+ bool visual_mode = false;
231
+
232
+ float eps = 0; // epsilon for timesteps
233
+ int32_t block_length = 0; // block length for generation
234
+
235
+ int32_t algorithm = 4; // default algorithm: low-confidence
236
+ float alg_temp = 0.0f; // algorithm temperature
237
+
238
+ float cfg_scale = 0; // classifier-free guidance scale
239
+ bool add_gumbel_noise = false; // add gumbel noise to the logits if temp > 0.0
240
+ };
241
+
242
+ // reasoning API response format (not to be confused as chat template's reasoning format)
243
+ enum common_reasoning_format {
244
+ COMMON_REASONING_FORMAT_NONE,
245
+ COMMON_REASONING_FORMAT_AUTO, // Same as deepseek, using `message.reasoning_content`
246
+ COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY, // Extract thinking tag contents and return as `message.reasoning_content`, or leave inline in <think> tags in stream mode
247
+ COMMON_REASONING_FORMAT_DEEPSEEK, // Extract thinking tag contents and return as `message.reasoning_content`, including in streaming deltas.
248
+ // do not extend this enum unless you absolutely have to
249
+ // in most cases, use COMMON_REASONING_FORMAT_AUTO
250
+ // see: https://github.com/ggml-org/llama.cpp/pull/15408
251
+ };
252
+
253
+
254
+ struct lr_opt {
255
+ float lr0 = 1e-5; // learning rate at first epoch
256
+ float lr_min = -1;
257
+ float decay_epochs = -1; // if >0, the learning rate starts at lr0 and decays to lr_min after this many epochs
258
+ float scale_epoch = 0;
259
+ float wd = 0;
260
+ unsigned epochs = 2;
261
+
262
+ unsigned epoch; // set by optimizer outer (epochs) loop
263
+ // learning rate decay - constant LR per epoch only for now
264
+ float get_lr(float e) const;
265
+ float get_lr() const { return get_lr(epoch); }
266
+ // must call after arg parse, before get_lr
267
+ void init();
268
+ };
269
+
270
+ struct lm_ggml_opt_optimizer_params common_opt_lr_pars(void * userdata);
271
+
272
+ struct common_params {
273
+ bool vocab_only = false;
274
+ int32_t n_predict = -1; // new tokens to predict
275
+ int32_t n_ctx = 4096; // context size
276
+ int32_t n_batch = 2048; // logical batch size for prompt processing (must be >=32 to use BLAS)
277
+ int32_t n_ubatch = 512; // physical batch size for prompt processing (must be >=32 to use BLAS)
278
+ int32_t n_keep = 0; // number of tokens to keep from initial prompt
279
+ int32_t n_chunks = -1; // max number of chunks to process (-1 = unlimited)
280
+ int32_t n_parallel = 1; // number of parallel sequences to decode
281
+ int32_t n_sequences = 1; // number of sequences to decode
282
+ int32_t grp_attn_n = 1; // group-attention factor
283
+ int32_t grp_attn_w = 512; // group-attention width
284
+ int32_t n_print = -1; // print token count every n tokens (-1 = disabled)
285
+ float rope_freq_base = 0.0f; // RoPE base frequency
286
+ float rope_freq_scale = 0.0f; // RoPE frequency scaling factor
287
+ float yarn_ext_factor = -1.0f; // YaRN extrapolation mix factor
288
+ float yarn_attn_factor = 1.0f; // YaRN magnitude scaling factor
289
+ float yarn_beta_fast = 32.0f; // YaRN low correction dim
290
+ float yarn_beta_slow = 1.0f; // YaRN high correction dim
291
+ int32_t yarn_orig_ctx = 0; // YaRN original context length
292
+
293
+ // offload params
294
+ std::vector<lm_ggml_backend_dev_t> devices; // devices to use for offloading
295
+
296
+ int32_t n_gpu_layers = -1; // number of layers to store in VRAM (-1 - use default)
297
+ int32_t main_gpu = 0; // the GPU that is used for scratch and small tensors
298
+ float tensor_split[128] = {0}; // how split tensors should be distributed across GPUs
299
+
300
+ enum llama_split_mode split_mode = LLAMA_SPLIT_MODE_LAYER; // how to split the model across GPUs
301
+
302
+ struct cpu_params cpuparams;
303
+ struct cpu_params cpuparams_batch;
304
+
305
+ lm_ggml_backend_sched_eval_callback cb_eval = nullptr;
306
+ void * cb_eval_user_data = nullptr;
307
+
308
+ lm_ggml_numa_strategy numa = LM_GGML_NUMA_STRATEGY_DISABLED;
309
+
310
+ enum llama_rope_scaling_type rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
311
+ enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_UNSPECIFIED; // pooling type for embeddings
312
+ enum llama_attention_type attention_type = LLAMA_ATTENTION_TYPE_UNSPECIFIED; // attention type for embeddings
313
+
314
+ struct common_params_sampling sampling;
315
+ struct common_params_speculative speculative;
316
+ struct common_params_vocoder vocoder;
317
+ struct common_params_diffusion diffusion;
318
+
319
+ struct common_params_model model;
320
+
321
+ std::string model_alias = ""; // model alias // NOLINT
322
+ std::string hf_token = ""; // HF token // NOLINT
323
+ std::string prompt = ""; // NOLINT
324
+ std::string system_prompt = ""; // NOLINT
325
+ std::string prompt_file = ""; // store the external prompt file name // NOLINT
326
+ std::string path_prompt_cache = ""; // path to file for saving/loading prompt eval state // NOLINT
327
+ std::string input_prefix = ""; // string to prefix user inputs with // NOLINT
328
+ std::string input_suffix = ""; // string to suffix user inputs with // NOLINT
329
+ std::string lookup_cache_static = ""; // path of static ngram cache file for lookup decoding // NOLINT
330
+ std::string lookup_cache_dynamic = ""; // path of dynamic ngram cache file for lookup decoding // NOLINT
331
+ std::string logits_file = ""; // file for saving *all* logits // NOLINT
332
+
333
+ std::vector<std::string> in_files; // all input files
334
+ std::vector<std::string> antiprompt; // strings upon which more user input is prompted (a.k.a. reverse prompts)
335
+ std::vector<llama_model_kv_override> kv_overrides;
336
+ std::vector<llama_model_tensor_buft_override> tensor_buft_overrides;
337
+
338
+ bool lora_init_without_apply = false; // only load lora to memory, but do not apply it to ctx (user can manually apply lora later using llama_adapter_lora_apply)
339
+ std::vector<common_adapter_lora_info> lora_adapters; // lora adapter path with user defined scale
340
+
341
+ std::vector<common_control_vector_load_info> control_vectors; // control vector with user defined scale
342
+
343
+ int32_t verbosity = 0;
344
+ int32_t control_vector_layer_start = -1; // layer range for control vector
345
+ int32_t control_vector_layer_end = -1; // layer range for control vector
346
+ bool offline = false;
347
+
348
+ int32_t ppl_stride = 0; // stride for perplexity calculations. If left at 0, the pre-existing approach will be used.
349
+ int32_t ppl_output_type = 0; // = 0 -> ppl output is as usual, = 1 -> ppl output is num_tokens, ppl, one per line
350
+ // (which is more convenient to use for plotting)
351
+ //
352
+ bool hellaswag = false; // compute HellaSwag score over random tasks from datafile supplied in prompt
353
+ size_t hellaswag_tasks = 400; // number of tasks to use when computing the HellaSwag score
354
+
355
+ bool winogrande = false; // compute Winogrande score over random tasks from datafile supplied in prompt
356
+ size_t winogrande_tasks = 0; // number of tasks to use when computing the Winogrande score. If 0, all tasks will be computed
357
+
358
+ bool multiple_choice = false; // compute TruthfulQA score over random tasks from datafile supplied in prompt
359
+ size_t multiple_choice_tasks = 0; // number of tasks to use when computing the TruthfulQA score. If 0, all tasks will be computed
360
+
361
+ bool kl_divergence = false; // compute KL divergence
362
+
363
+ bool usage = false; // print usage
364
+ bool completion = false; // print source-able completion script
365
+ bool use_color = false; // use color to distinguish generations and inputs
366
+ bool special = false; // enable special token output
367
+ bool interactive = false; // interactive mode
368
+ bool interactive_first = false; // wait for user input immediately
369
+ bool prompt_cache_all = false; // save user input and generations to prompt cache
370
+ bool prompt_cache_ro = false; // open the prompt cache read-only and do not update it
371
+
372
+ bool escape = true; // escape "\n", "\r", "\t", "\'", "\"", and "\\"
373
+ bool multiline_input = false; // reverse the usage of `\`
374
+ bool simple_io = false; // improves compatibility with subprocesses and limited consoles
375
+ bool cont_batching = true; // insert new sequences for decoding on-the-fly
376
+ bool flash_attn = false; // flash attention
377
+ bool no_perf = false; // disable performance metrics
378
+ bool ctx_shift = false; // context shift on infinite text generation
379
+ bool swa_full = false; // use full-size SWA cache (https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)
380
+ bool kv_unified = false; // enable unified KV cache
381
+
382
+ bool input_prefix_bos = false; // prefix BOS to user inputs, preceding input_prefix
383
+ bool use_mmap = true; // use mmap for faster loads
384
+ bool use_mlock = false; // use mlock to keep model in memory
385
+ bool verbose_prompt = false; // print prompt tokens before generation
386
+ bool display_prompt = true; // print prompt before generation
387
+ bool no_kv_offload = false; // disable KV offloading
388
+ bool warmup = true; // warmup run
389
+ bool check_tensors = false; // validate tensor data
390
+ bool no_op_offload = false; // globally disable offload host tensor operations to device
391
+ bool no_extra_bufts = false; // disable extra buffer types (used for weight repacking)
392
+
393
+ bool single_turn = false; // single turn chat conversation
394
+
395
+ llama_progress_callback progress_callback = nullptr;
396
+ void * progress_callback_user_data = nullptr;
397
+
398
+ lm_ggml_type cache_type_k = LM_GGML_TYPE_F16; // KV cache data type for the K
399
+ lm_ggml_type cache_type_v = LM_GGML_TYPE_F16; // KV cache data type for the V
400
+
401
+ common_conversation_mode conversation_mode = COMMON_CONVERSATION_MODE_AUTO;
402
+
403
+ // multimodal models (see tools/mtmd)
404
+ struct common_params_model mmproj;
405
+ bool mmproj_use_gpu = true; // use GPU for multimodal model
406
+ bool no_mmproj = false; // explicitly disable multimodal model
407
+ std::vector<std::string> image; // path to image file(s)
408
+
409
+ // finetune
410
+ struct lr_opt lr;
411
+ enum lm_ggml_opt_optimizer_type optimizer = LM_GGML_OPT_OPTIMIZER_TYPE_ADAMW;
412
+ float val_split = 0.05f; // fraction of the data used for the validation set
413
+
414
+ // embedding
415
+ bool embedding = false; // get only sentence embedding
416
+ int32_t embd_normalize = 2; // normalisation for embeddings (-1=none, 0=max absolute int16, 1=taxicab, 2=euclidean, >2=p-norm)
417
+ std::string embd_out = ""; // empty = default, "array" = [[],[]...], "json" = openai style, "json+" = same "json" + cosine similarity matrix
418
+ std::string embd_sep = "\n"; // separator of embeddings
419
+ std::string cls_sep = "\t"; // separator of classification sequences
420
+
421
+ // server params
422
+ int32_t port = 8080; // server listens on this network port
423
+ int32_t timeout_read = 600; // http read timeout in seconds
424
+ int32_t timeout_write = timeout_read; // http write timeout in seconds
425
+ int32_t n_threads_http = -1; // number of threads to process HTTP requests (TODO: support threadpool)
426
+ int32_t n_cache_reuse = 0; // min chunk size to reuse from the cache via KV shifting
427
+ int32_t n_swa_checkpoints = 3; // max number of SWA checkpoints per slot
428
+
429
+ std::string hostname = "127.0.0.1";
430
+ std::string public_path = ""; // NOLINT
431
+ std::string api_prefix = ""; // NOLINT
432
+ std::string chat_template = ""; // NOLINT
433
+ bool use_jinja = false; // NOLINT
434
+ bool enable_chat_template = true;
435
+ common_reasoning_format reasoning_format = COMMON_REASONING_FORMAT_AUTO;
436
+ int reasoning_budget = -1;
437
+ bool prefill_assistant = true; // if true, any trailing assistant message will be prefilled into the response
438
+
439
+ std::vector<std::string> api_keys;
440
+
441
+ std::string ssl_file_key = ""; // NOLINT
442
+ std::string ssl_file_cert = ""; // NOLINT
443
+
444
+ std::map<std::string, std::string> default_template_kwargs;
445
+
446
+ // "advanced" endpoints are disabled by default for better security
447
+ bool webui = true;
448
+ bool endpoint_slots = false;
449
+ bool endpoint_props = false; // only control POST requests, not GET
450
+ bool endpoint_metrics = false;
451
+
452
+ bool log_json = false;
453
+
454
+ std::string slot_save_path;
455
+
456
+ float slot_prompt_similarity = 0.5f;
457
+
458
+ // batched-bench params
459
+ bool is_pp_shared = false;
460
+
461
+ std::vector<int32_t> n_pp;
462
+ std::vector<int32_t> n_tg;
463
+ std::vector<int32_t> n_pl;
464
+
465
+ // retrieval params
466
+ std::vector<std::string> context_files; // context files to embed
467
+
468
+ int32_t chunk_size = 64; // chunk size for context embedding
469
+
470
+ std::string chunk_separator = "\n"; // chunk separator for context embedding
471
+
472
+ // passkey params
473
+ int32_t n_junk = 250; // number of times to repeat the junk text
474
+ int32_t i_pos = -1; // position of the passkey in the junk text
475
+
476
+ // imatrix params
477
+ int32_t n_out_freq = 10; // output the imatrix every n_out_freq iterations
478
+ int32_t n_save_freq = 0; // save the imatrix every n_save_freq iterations
479
+ int32_t i_chunk = 0; // start processing from this chunk
480
+ int8_t imat_dat = 0; // whether the legacy imatrix.dat format should be output (gguf <= 0 < dat)
481
+
482
+ bool process_output = false; // collect data for the output tensor
483
+ bool compute_ppl = true; // whether to compute perplexity
484
+ bool show_statistics = false; // show imatrix statistics per tensor
485
+ bool parse_special = false; // whether to parse special tokens during imatrix tokenization
486
+
487
+ // cvector-generator params
488
+ int n_pca_batch = 100;
489
+ int n_pca_iterations = 1000;
490
+ dimre_method cvector_dimre_method = DIMRE_METHOD_PCA;
491
+ std::string cvector_positive_file = "tools/cvector-generator/positive.txt";
492
+ std::string cvector_negative_file = "tools/cvector-generator/negative.txt";
493
+
494
+ bool spm_infill = false; // suffix/prefix/middle pattern for infill
495
+
496
+ // batched-bench params
497
+ bool batched_bench_output_jsonl = false;
498
+
499
+ // common params
500
+ std::string out_file; // output filename for all example programs
501
+ // optional callback for model loading progress and cancellation:
502
+ // called with a progress value between 0.0 and 1.0.
503
+ // return false from callback to abort model loading or true to continue
504
+ llama_progress_callback load_progress_callback = NULL;
505
+ void * load_progress_callback_user_data = NULL;
506
+ };
507
+
508
+ // call once at the start of a program if it uses libcommon
509
+ // initializes the logging system and prints info about the build
510
+ void common_init();
511
+
512
+ std::string common_params_get_system_info(const common_params & params);
513
+
514
+ bool parse_cpu_range(const std::string & range, bool(&boolmask)[LM_GGML_MAX_N_THREADS]);
515
+ bool parse_cpu_mask(const std::string & mask, bool(&boolmask)[LM_GGML_MAX_N_THREADS]);
516
+ void postprocess_cpu_params(cpu_params & cpuparams, const cpu_params * role_model = nullptr);
517
+ bool set_process_priority(enum lm_ggml_sched_priority prio);
518
+
519
+ //
520
+ // String utils
521
+ //
522
+
523
+ #ifdef __GNUC__
524
+ # if defined(__MINGW32__) && !defined(__clang__)
525
+ # define LLAMA_COMMON_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
526
+ # else
527
+ # define LLAMA_COMMON_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
528
+ # endif
529
+ #else
530
+ # define LLAMA_COMMON_ATTRIBUTE_FORMAT(...)
531
+ #endif
532
+
533
+ LLAMA_COMMON_ATTRIBUTE_FORMAT(1, 2)
534
+ std::string string_format(const char * fmt, ...);
535
+
536
+ std::string string_strip(const std::string & str);
537
+ std::string string_get_sortable_timestamp();
538
+
539
+ std::string string_join(const std::vector<std::string> & values, const std::string & separator);
540
+ std::vector<std::string> string_split(const std::string & str, const std::string & delimiter);
541
+ std::string string_repeat(const std::string & str, size_t n);
542
+
543
+ void string_replace_all(std::string & s, const std::string & search, const std::string & replace);
544
+
545
+ std::string regex_escape(const std::string & s);
546
+
547
+ template<class T>
548
+ static std::vector<T> string_split(const std::string & str, char delim) {
549
+ static_assert(!std::is_same<T, std::string>::value, "Please use the specialized version for std::string");
550
+ std::vector<T> values;
551
+ std::istringstream str_stream(str);
552
+ std::string token;
553
+ while (std::getline(str_stream, token, delim)) {
554
+ T value;
555
+ std::istringstream token_stream(token);
556
+ token_stream >> value;
557
+ values.push_back(value);
558
+ }
559
+ return values;
560
+ }
561
+
562
+ template<>
563
+ std::vector<std::string> string_split<std::string>(const std::string & input, char separator)
564
+ {
565
+ std::vector<std::string> parts;
566
+ size_t begin_pos = 0;
567
+ size_t separator_pos = input.find(separator);
568
+ while (separator_pos != std::string::npos) {
569
+ std::string part = input.substr(begin_pos, separator_pos - begin_pos);
570
+ parts.emplace_back(part);
571
+ begin_pos = separator_pos + 1;
572
+ separator_pos = input.find(separator, begin_pos);
573
+ }
574
+ parts.emplace_back(input.substr(begin_pos, separator_pos - begin_pos));
575
+ return parts;
576
+ }
577
+
578
+ static bool string_starts_with(const std::string & str,
579
+ const std::string & prefix) { // While we wait for C++20's std::string::starts_with...
580
+ return str.rfind(prefix, 0) == 0;
581
+ }
582
+
583
+ // While we wait for C++20's std::string::ends_with...
584
+ bool string_ends_with(const std::string_view & str, const std::string_view & suffix);
585
+ bool string_remove_suffix(std::string & str, const std::string_view & suffix);
586
+ size_t string_find_partial_stop(const std::string_view & str, const std::string_view & stop);
587
+
588
+ bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides);
589
+ void string_process_escapes(std::string & input);
590
+
591
+ std::string string_from(bool value);
592
+ std::string string_from(const std::vector<int> & values);
593
+ std::string string_from(const struct llama_context * ctx, const std::vector<llama_token> & tokens);
594
+ std::string string_from(const struct llama_context * ctx, const struct llama_batch & batch);
595
+
596
+ //
597
+ // Filesystem utils
598
+ //
599
+
600
+ bool fs_validate_filename(const std::string & filename);
601
+ bool fs_create_directory_with_parents(const std::string & path);
602
+
603
+ std::string fs_get_cache_directory();
604
+ std::string fs_get_cache_file(const std::string & filename);
605
+
606
+ //
607
+ // Model utils
608
+ //
609
+
610
+ // note: defines object's lifetime
611
+ struct common_init_result {
612
+ llama_model_ptr model;
613
+ llama_context_ptr context;
614
+
615
+ std::vector<llama_adapter_lora_ptr> lora;
616
+ };
617
+
618
+ struct common_init_result common_init_from_params(common_params & params);
619
+
620
+ struct llama_model_params common_model_params_to_llama ( common_params & params);
621
+ struct llama_context_params common_context_params_to_llama(const common_params & params);
622
+ struct lm_ggml_threadpool_params lm_ggml_threadpool_params_from_cpu_params(const cpu_params & params);
623
+
624
+ // clear LoRA adapters from context, then apply new list of adapters
625
+ void common_set_adapter_lora(struct llama_context * ctx, std::vector<common_adapter_lora_info> & lora);
626
+
627
+ std::string get_model_endpoint();
628
+
629
+ //
630
+ // Batch utils
631
+ //
632
+
633
+ void common_batch_clear(struct llama_batch & batch);
634
+
635
+ void common_batch_add(
636
+ struct llama_batch & batch,
637
+ llama_token id,
638
+ llama_pos pos,
639
+ const std::vector<llama_seq_id> & seq_ids,
640
+ bool logits);
641
+
642
+ //
643
+ // Token utils
644
+ //
645
+
646
+ // longest common prefix
647
+ size_t common_lcp(const llama_tokens & a, const llama_tokens & b);
648
+
649
+ // longet common subsequence
650
+ size_t common_lcs(const llama_tokens & a, const llama_tokens & b);
651
+
652
+ //
653
+ // Vocab utils
654
+ //
655
+
656
+ // tokenizes a string into a vector of tokens
657
+ // should work similar to Python's `tokenizer.encode`
658
+ std::vector<llama_token> common_tokenize(
659
+ const struct llama_context * ctx,
660
+ const std::string & text,
661
+ bool add_special,
662
+ bool parse_special = false);
663
+
664
+ std::vector<llama_token> common_tokenize(
665
+ const struct llama_vocab * vocab,
666
+ const std::string & text,
667
+ bool add_special,
668
+ bool parse_special = false);
669
+
670
+ // tokenizes a token into a piece, optionally renders special/control tokens
671
+ // should work similar to Python's `tokenizer.id_to_piece`
672
+ std::string common_token_to_piece(
673
+ const struct llama_context * ctx,
674
+ llama_token token,
675
+ bool special = true);
676
+
677
+ std::string common_token_to_piece(
678
+ const struct llama_vocab * vocab,
679
+ llama_token token,
680
+ bool special = true);
681
+
682
+ // detokenizes a vector of tokens into a string
683
+ // should work similar to Python's `tokenizer.decode`
684
+ // optionally renders special/control tokens
685
+ std::string common_detokenize(
686
+ const struct llama_context * ctx,
687
+ const std::vector<llama_token> & tokens,
688
+ bool special = true);
689
+
690
+ std::string common_detokenize(
691
+ const struct llama_vocab * vocab,
692
+ const std::vector<llama_token> & tokens,
693
+ bool special = true);
694
+
695
+ //
696
+ // Embedding utils
697
+ //
698
+
699
+ // TODO: repace embd_norm with an enum
700
+ void common_embd_normalize(const float * inp, float * out, int n, int embd_norm);
701
+
702
+ float common_embd_similarity_cos(const float * embd1, const float * embd2, int n);
703
+
704
+ //
705
+ // Control vector utils
706
+ //
707
+
708
+ struct common_control_vector_data {
709
+ int n_embd;
710
+
711
+ // stores data for layers [1, n_layer] where n_layer = data.size() / n_embd
712
+ std::vector<float> data;
713
+ };
714
+
715
+ struct common_control_vector_load_info {
716
+ float strength;
717
+
718
+ std::string fname;
719
+ };
720
+
721
+ // Load control vectors, scale each by strength, and add them together.
722
+ // On error, returns {-1, empty}
723
+ common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos);
724
+
725
+ //
726
+ // Split utils
727
+ //
728
+
729
+ namespace {
730
+
731
+ const char * const LLM_KV_SPLIT_NO = "split.no";
732
+ const char * const LLM_KV_SPLIT_COUNT = "split.count";
733
+ const char * const LLM_KV_SPLIT_TENSORS_COUNT = "split.tensors.count";
734
+
735
+ }
736
+
737
+ //
738
+ // training utils
739
+ //
740
+
741
+ lm_ggml_opt_dataset_t common_opt_dataset_init(struct llama_context * ctx, const std::vector<llama_token> & tokens, int64_t stride);
742
+
743
+ // "adamw" or "sgd" (case insensitive)
744
+ enum lm_ggml_opt_optimizer_type common_opt_get_optimizer(const char *);