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.cpp ADDED
@@ -0,0 +1,1664 @@
1
+ #if defined(_MSC_VER)
2
+ #define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING
3
+ #endif
4
+
5
+ #include "ggml.h"
6
+ #include "gguf.h"
7
+
8
+ #include "common.h"
9
+ #include "log.h"
10
+ #include "llama.h"
11
+
12
+ #include <algorithm>
13
+ #include <cinttypes>
14
+ #include <climits>
15
+ #include <cmath>
16
+ #include <codecvt>
17
+ #include <cstdarg>
18
+ #include <cstring>
19
+ #include <ctime>
20
+ #include <filesystem>
21
+ #include <fstream>
22
+ #include <iostream>
23
+ #include <iterator>
24
+ #include <regex>
25
+ #include <sstream>
26
+ #include <string>
27
+ #include <thread>
28
+ #include <unordered_map>
29
+ #include <unordered_set>
30
+ #include <vector>
31
+
32
+ #if defined(__APPLE__) && defined(__MACH__)
33
+ #include <sys/types.h>
34
+ #include <sys/sysctl.h>
35
+ #endif
36
+
37
+ #if defined(_WIN32)
38
+ #define WIN32_LEAN_AND_MEAN
39
+ #ifndef NOMINMAX
40
+ # define NOMINMAX
41
+ #endif
42
+ #include <locale>
43
+ #include <windows.h>
44
+ #include <string.h>
45
+ #include <fcntl.h>
46
+ #include <io.h>
47
+ #else
48
+ #include <sys/ioctl.h>
49
+ #include <sys/stat.h>
50
+ #include <unistd.h>
51
+ #endif
52
+
53
+ // build info
54
+ int LLAMA_BUILD_NUMBER = 0;
55
+ char const *LLAMA_COMMIT = "unknown";
56
+ char const *LLAMA_COMPILER = "unknown";
57
+ char const *LLAMA_BUILD_TARGET = "unknown";
58
+
59
+
60
+ #if defined(_MSC_VER)
61
+ #pragma warning(disable: 4244 4267) // possible loss of data
62
+ #endif
63
+
64
+ //
65
+ // CPU utils
66
+ //
67
+
68
+ int32_t cpu_get_num_physical_cores() {
69
+ #ifdef __linux__
70
+ // enumerate the set of thread siblings, num entries is num cores
71
+ std::unordered_set<std::string> siblings;
72
+ for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
73
+ std::ifstream thread_siblings("/sys/devices/system/cpu/cpu"
74
+ + std::to_string(cpu) + "/topology/thread_siblings");
75
+ if (!thread_siblings.is_open()) {
76
+ break; // no more cpus
77
+ }
78
+ std::string line;
79
+ if (std::getline(thread_siblings, line)) {
80
+ siblings.insert(line);
81
+ }
82
+ }
83
+ if (!siblings.empty()) {
84
+ return static_cast<int32_t>(siblings.size());
85
+ }
86
+ #elif defined(__APPLE__) && defined(__MACH__)
87
+ int32_t num_physical_cores;
88
+ size_t len = sizeof(num_physical_cores);
89
+ int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
90
+ if (result == 0) {
91
+ return num_physical_cores;
92
+ }
93
+ result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
94
+ if (result == 0) {
95
+ return num_physical_cores;
96
+ }
97
+ #elif defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
98
+ // TODO: windows + arm64 + mingw64
99
+ unsigned int n_threads_win = std::thread::hardware_concurrency();
100
+ unsigned int default_threads = n_threads_win > 0 ? (n_threads_win <= 4 ? n_threads_win : n_threads_win / 2) : 4;
101
+
102
+ DWORD buffer_size = 0;
103
+ if (!GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &buffer_size)) {
104
+ if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
105
+ return default_threads;
106
+ }
107
+ }
108
+
109
+ std::vector<char> buffer(buffer_size);
110
+ if (!GetLogicalProcessorInformationEx(RelationProcessorCore, reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data()), &buffer_size)) {
111
+ return default_threads;
112
+ }
113
+
114
+ int32_t num_physical_cores = 0;
115
+ PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data());
116
+ while (buffer_size > 0) {
117
+ if (info->Relationship == RelationProcessorCore) {
118
+ num_physical_cores += info->Processor.GroupCount;
119
+ }
120
+ buffer_size -= info->Size;
121
+ info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(reinterpret_cast<char*>(info) + info->Size);
122
+ }
123
+
124
+ return num_physical_cores > 0 ? num_physical_cores : default_threads;
125
+ #endif
126
+ unsigned int n_threads = std::thread::hardware_concurrency();
127
+ return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
128
+ }
129
+
130
+ #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
131
+ #include <pthread.h>
132
+
133
+ static void cpuid(unsigned leaf, unsigned subleaf,
134
+ unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) {
135
+ __asm__("movq\t%%rbx,%%rsi\n\t"
136
+ "cpuid\n\t"
137
+ "xchgq\t%%rbx,%%rsi"
138
+ : "=a"(*eax), "=S"(*ebx), "=c"(*ecx), "=d"(*edx)
139
+ : "0"(leaf), "2"(subleaf));
140
+ }
141
+
142
+ static int pin_cpu(int cpu) {
143
+ cpu_set_t mask;
144
+ CPU_ZERO(&mask);
145
+ CPU_SET(cpu, &mask);
146
+ return pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);
147
+ }
148
+
149
+ static bool is_hybrid_cpu(void) {
150
+ unsigned eax, ebx, ecx, edx;
151
+ cpuid(7, 0, &eax, &ebx, &ecx, &edx);
152
+ return !!(edx & (1u << 15));
153
+ }
154
+
155
+ static bool is_running_on_efficiency_core(void) {
156
+ unsigned eax, ebx, ecx, edx;
157
+ cpuid(0x1a, 0, &eax, &ebx, &ecx, &edx);
158
+ int intel_atom = 0x20;
159
+ int core_type = (eax & 0xff000000u) >> 24;
160
+ return core_type == intel_atom;
161
+ }
162
+
163
+ static int cpu_count_math_cpus(int n_cpu) {
164
+ int result = 0;
165
+ for (int cpu = 0; cpu < n_cpu; ++cpu) {
166
+ if (pin_cpu(cpu)) {
167
+ return -1;
168
+ }
169
+ if (is_running_on_efficiency_core()) {
170
+ continue; // efficiency cores harm lockstep threading
171
+ }
172
+ ++cpu; // hyperthreading isn't useful for linear algebra
173
+ ++result;
174
+ }
175
+ return result;
176
+ }
177
+
178
+ #endif // __x86_64__ && __linux__
179
+
180
+ /**
181
+ * Returns number of CPUs on system that are useful for math.
182
+ */
183
+ int32_t cpu_get_num_math() {
184
+ #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
185
+ int n_cpu = sysconf(_SC_NPROCESSORS_ONLN);
186
+ if (n_cpu < 1) {
187
+ return cpu_get_num_physical_cores();
188
+ }
189
+ if (is_hybrid_cpu()) {
190
+ cpu_set_t affinity;
191
+ if (!pthread_getaffinity_np(pthread_self(), sizeof(affinity), &affinity)) {
192
+ int result = cpu_count_math_cpus(n_cpu);
193
+ pthread_setaffinity_np(pthread_self(), sizeof(affinity), &affinity);
194
+ if (result > 0) {
195
+ return result;
196
+ }
197
+ }
198
+ }
199
+ #endif
200
+ return cpu_get_num_physical_cores();
201
+ }
202
+
203
+ // Helper for setting process priority
204
+
205
+ #if defined(_WIN32)
206
+
207
+ bool set_process_priority(enum lm_ggml_sched_priority prio) {
208
+ if (prio == LM_GGML_SCHED_PRIO_NORMAL) {
209
+ return true;
210
+ }
211
+
212
+ DWORD p = NORMAL_PRIORITY_CLASS;
213
+ switch (prio) {
214
+ case LM_GGML_SCHED_PRIO_LOW: p = BELOW_NORMAL_PRIORITY_CLASS; break;
215
+ case LM_GGML_SCHED_PRIO_NORMAL: p = NORMAL_PRIORITY_CLASS; break;
216
+ case LM_GGML_SCHED_PRIO_MEDIUM: p = ABOVE_NORMAL_PRIORITY_CLASS; break;
217
+ case LM_GGML_SCHED_PRIO_HIGH: p = HIGH_PRIORITY_CLASS; break;
218
+ case LM_GGML_SCHED_PRIO_REALTIME: p = REALTIME_PRIORITY_CLASS; break;
219
+ }
220
+
221
+ if (!SetPriorityClass(GetCurrentProcess(), p)) {
222
+ LOG_WRN("failed to set process priority class %d : (%d)\n", prio, (int) GetLastError());
223
+ return false;
224
+ }
225
+
226
+ return true;
227
+ }
228
+
229
+ #else // MacOS and POSIX
230
+ #include <sys/types.h>
231
+ #include <sys/resource.h>
232
+
233
+ bool set_process_priority(enum lm_ggml_sched_priority prio) {
234
+ if (prio == LM_GGML_SCHED_PRIO_NORMAL) {
235
+ return true;
236
+ }
237
+
238
+ int p = 0;
239
+ switch (prio) {
240
+ case LM_GGML_SCHED_PRIO_LOW: p = 5; break;
241
+ case LM_GGML_SCHED_PRIO_NORMAL: p = 0; break;
242
+ case LM_GGML_SCHED_PRIO_MEDIUM: p = -5; break;
243
+ case LM_GGML_SCHED_PRIO_HIGH: p = -10; break;
244
+ case LM_GGML_SCHED_PRIO_REALTIME: p = -20; break;
245
+ }
246
+
247
+ if (!setpriority(PRIO_PROCESS, 0, p)) {
248
+ LOG_WRN("failed to set process priority %d : %s (%d)\n", prio, strerror(errno), errno);
249
+ return false;
250
+ }
251
+ return true;
252
+ }
253
+
254
+ #endif
255
+
256
+ //
257
+ // CLI argument parsing
258
+ //
259
+
260
+
261
+ void postprocess_cpu_params(cpu_params& cpuparams, const cpu_params* role_model) {
262
+ int32_t n_set = 0;
263
+
264
+ if (cpuparams.n_threads < 0) {
265
+ // Assuming everything about cpuparams is invalid
266
+ if (role_model != nullptr) {
267
+ cpuparams = *role_model;
268
+ } else {
269
+ cpuparams.n_threads = cpu_get_num_math();
270
+ }
271
+ }
272
+
273
+ for (int32_t i = 0; i < LM_GGML_MAX_N_THREADS; i++) {
274
+ if (cpuparams.cpumask[i]) {
275
+ n_set++;
276
+ }
277
+ }
278
+
279
+ if (n_set && n_set < cpuparams.n_threads) {
280
+ // Not enough set bits, may experience performance issues.
281
+ LOG_WRN("Not enough set bits in CPU mask (%d) to satisfy requested thread count: %d\n", n_set, cpuparams.n_threads);
282
+ }
283
+ }
284
+
285
+ bool parse_cpu_range(const std::string & range, bool (&boolmask)[LM_GGML_MAX_N_THREADS]) {
286
+ size_t dash_loc = range.find('-');
287
+ if (dash_loc == std::string::npos) {
288
+ LOG_ERR("Format of CPU range is invalid! Expected [<start>]-[<end>].\n");
289
+ return false;
290
+ }
291
+
292
+ size_t start_i;
293
+ size_t end_i;
294
+
295
+ if (dash_loc == 0) {
296
+ start_i = 0;
297
+ } else {
298
+ start_i = std::stoull(range.substr(0, dash_loc));
299
+ if (start_i >= LM_GGML_MAX_N_THREADS) {
300
+ LOG_ERR("Start index out of bounds!\n");
301
+ return false;
302
+ }
303
+ }
304
+
305
+ if (dash_loc == range.length() - 1) {
306
+ end_i = LM_GGML_MAX_N_THREADS - 1;
307
+ } else {
308
+ end_i = std::stoull(range.substr(dash_loc + 1));
309
+ if (end_i >= LM_GGML_MAX_N_THREADS) {
310
+ LOG_ERR("End index out of bounds!\n");
311
+ return false;
312
+ }
313
+ }
314
+
315
+ for (size_t i = start_i; i <= end_i; i++) {
316
+ boolmask[i] = true;
317
+ }
318
+
319
+ return true;
320
+ }
321
+
322
+ bool parse_cpu_mask(const std::string & mask, bool (&boolmask)[LM_GGML_MAX_N_THREADS]) {
323
+ // Discard potential 0x prefix
324
+ size_t start_i = 0;
325
+ if (mask.length() >= 2 && mask.substr(0, 2) == "0x") {
326
+ start_i = 2;
327
+ }
328
+
329
+ size_t num_digits = mask.length() - start_i;
330
+ if (num_digits > 128) num_digits = 128;
331
+
332
+ size_t end_i = num_digits + start_i;
333
+
334
+ for (size_t i = start_i, n = (num_digits*4 - 1); i < end_i; i++, n-=4) {
335
+ char c = mask.at(i);
336
+ int8_t id = c;
337
+
338
+ if ((c >= '0' && c <= '9')) {
339
+ id -= '0';
340
+ } else if (c >= 'a' && c <= 'f') {
341
+ id -= 'a' - 10;
342
+ } else if (c >= 'A' && c <= 'F') {
343
+ id -= 'A' - 10;
344
+ } else {
345
+ LOG_ERR("Invalid hex character '%c' at position %d\n", c, int32_t(i));
346
+ return false;
347
+ }
348
+
349
+ boolmask[ n ] = boolmask[ n ] || ((id & 8) != 0);
350
+ boolmask[n - 1] = boolmask[n - 1] || ((id & 4) != 0);
351
+ boolmask[n - 2] = boolmask[n - 2] || ((id & 2) != 0);
352
+ boolmask[n - 3] = boolmask[n - 3] || ((id & 1) != 0);
353
+ }
354
+
355
+ return true;
356
+ }
357
+
358
+ void common_init() {
359
+ llama_log_set([](lm_ggml_log_level level, const char * text, void * /*user_data*/) {
360
+ if (LOG_DEFAULT_LLAMA <= common_log_verbosity_thold) {
361
+ common_log_add(common_log_main(), level, "%s", text);
362
+ }
363
+ }, NULL);
364
+
365
+ #ifdef NDEBUG
366
+ const char * build_type = "";
367
+ #else
368
+ const char * build_type = " (debug)";
369
+ #endif
370
+
371
+ LOG_INF("build: %d (%s) with %s for %s%s\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT, LLAMA_COMPILER, LLAMA_BUILD_TARGET, build_type);
372
+ }
373
+
374
+ std::string common_params_get_system_info(const common_params & params) {
375
+ std::ostringstream os;
376
+
377
+ os << "system_info: n_threads = " << params.cpuparams.n_threads;
378
+ if (params.cpuparams_batch.n_threads != -1) {
379
+ os << " (n_threads_batch = " << params.cpuparams_batch.n_threads << ")";
380
+ }
381
+ #if defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
382
+ // TODO: windows + arm64 + mingw64
383
+ DWORD logicalProcessorCount = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
384
+ os << " / " << logicalProcessorCount << " | " << llama_print_system_info();
385
+ #else
386
+ os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
387
+ #endif
388
+
389
+ return os.str();
390
+ }
391
+
392
+ //
393
+ // String utils
394
+ //
395
+
396
+ std::string string_format(const char * fmt, ...) {
397
+ va_list ap;
398
+ va_list ap2;
399
+ va_start(ap, fmt);
400
+ va_copy(ap2, ap);
401
+ int size = vsnprintf(NULL, 0, fmt, ap);
402
+ LM_GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
403
+ std::vector<char> buf(size + 1);
404
+ int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
405
+ LM_GGML_ASSERT(size2 == size);
406
+ va_end(ap2);
407
+ va_end(ap);
408
+ return std::string(buf.data(), size);
409
+ }
410
+
411
+ std::string string_strip(const std::string & str) {
412
+ size_t start = 0;
413
+ size_t end = str.size();
414
+ while (start < end && std::isspace(str[start])) {
415
+ start++;
416
+ }
417
+ while (end > start && std::isspace(str[end - 1])) {
418
+ end--;
419
+ }
420
+ return str.substr(start, end - start);
421
+ }
422
+
423
+ std::string string_get_sortable_timestamp() {
424
+ using clock = std::chrono::system_clock;
425
+
426
+ const clock::time_point current_time = clock::now();
427
+ const time_t as_time_t = clock::to_time_t(current_time);
428
+ char timestamp_no_ns[100];
429
+ std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
430
+
431
+ const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
432
+ current_time.time_since_epoch() % 1000000000).count();
433
+ char timestamp_ns[11];
434
+ snprintf(timestamp_ns, 11, "%09" PRId64, ns);
435
+
436
+ return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
437
+ }
438
+
439
+ void string_replace_all(std::string & s, const std::string & search, const std::string & replace) {
440
+ if (search.empty()) {
441
+ return;
442
+ }
443
+ std::string builder;
444
+ builder.reserve(s.length());
445
+ size_t pos = 0;
446
+ size_t last_pos = 0;
447
+ while ((pos = s.find(search, last_pos)) != std::string::npos) {
448
+ builder.append(s, last_pos, pos - last_pos);
449
+ builder.append(replace);
450
+ last_pos = pos + search.length();
451
+ }
452
+ builder.append(s, last_pos, std::string::npos);
453
+ s = std::move(builder);
454
+ }
455
+
456
+ bool string_ends_with(const std::string_view & str, const std::string_view & suffix) {
457
+ return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
458
+ }
459
+
460
+ bool string_remove_suffix(std::string & str, const std::string_view & suffix) {
461
+ bool has_suffix = string_ends_with(str, suffix);
462
+ if (has_suffix) {
463
+ str = str.substr(0, str.size() - suffix.size());
464
+ }
465
+ return has_suffix;
466
+ }
467
+
468
+ size_t string_find_partial_stop(const std::string_view & str, const std::string_view & stop) {
469
+ if (!str.empty() && !stop.empty()) {
470
+ const char text_last_char = str.back();
471
+ for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--) {
472
+ if (stop[char_index] == text_last_char) {
473
+ const auto current_partial = stop.substr(0, char_index + 1);
474
+ if (string_ends_with(str, current_partial)) {
475
+ return str.size() - char_index - 1;
476
+ }
477
+ }
478
+ }
479
+ }
480
+
481
+ return std::string::npos;
482
+ }
483
+
484
+ std::string regex_escape(const std::string & s) {
485
+ static const std::regex special_chars("[.^$|()*+?\\[\\]{}\\\\]");
486
+ return std::regex_replace(s, special_chars, "\\$&");
487
+ }
488
+
489
+ std::string string_join(const std::vector<std::string> & values, const std::string & separator) {
490
+ std::ostringstream result;
491
+ for (size_t i = 0; i < values.size(); ++i) {
492
+ if (i > 0) {
493
+ result << separator;
494
+ }
495
+ result << values[i];
496
+ }
497
+ return result.str();
498
+ }
499
+
500
+ std::vector<std::string> string_split(const std::string & str, const std::string & delimiter) {
501
+ std::vector<std::string> parts;
502
+ size_t start = 0;
503
+ size_t end = str.find(delimiter);
504
+
505
+ while (end != std::string::npos) {
506
+ parts.push_back(str.substr(start, end - start));
507
+ start = end + delimiter.length();
508
+ end = str.find(delimiter, start);
509
+ }
510
+
511
+ parts.push_back(str.substr(start));
512
+
513
+ return parts;
514
+ }
515
+
516
+ std::string string_repeat(const std::string & str, size_t n) {
517
+ if (n == 0) {
518
+ return "";
519
+ }
520
+
521
+ std::string result;
522
+ result.reserve(str.length() * n);
523
+
524
+ for (size_t i = 0; i < n; ++i) {
525
+ result += str;
526
+ }
527
+
528
+ return result;
529
+ }
530
+
531
+ std::string string_from(bool value) {
532
+ return value ? "true" : "false";
533
+ }
534
+
535
+ std::string string_from(const std::vector<int> & values) {
536
+ std::stringstream buf;
537
+
538
+ buf << "[ ";
539
+ bool first = true;
540
+ for (auto e : values) {
541
+ if (first) {
542
+ first = false;
543
+ } else {
544
+ buf << ", ";
545
+ }
546
+ buf << std::to_string(e);
547
+ }
548
+ buf << " ]";
549
+
550
+ return buf.str();
551
+ }
552
+
553
+ std::string string_from(const struct llama_context * ctx, const std::vector<llama_token> & tokens) {
554
+ std::stringstream buf;
555
+
556
+ buf << "[ ";
557
+
558
+ bool first = true;
559
+ for (const auto & token : tokens) {
560
+ if (!first) {
561
+ buf << ", ";
562
+ } else {
563
+ first = false;
564
+ }
565
+
566
+ auto detokenized = common_token_to_piece(ctx, token);
567
+
568
+ buf << "'" << detokenized << "'"
569
+ << ":" << std::to_string(token);
570
+ }
571
+
572
+ buf << " ]";
573
+
574
+ return buf.str();
575
+ }
576
+
577
+ std::string string_from(const struct llama_context * ctx, const struct llama_batch & batch) {
578
+ std::stringstream buf;
579
+
580
+ buf << "[ ";
581
+
582
+ bool first = true;
583
+ for (int i = 0; i < batch.n_tokens; ++i) {
584
+ if (!first) {
585
+ buf << ", ";
586
+ } else {
587
+ first = false;
588
+ }
589
+
590
+ auto detokenized = common_token_to_piece(ctx, batch.token[i]);
591
+
592
+ buf << "\n" << std::to_string(i)
593
+ << ", token '" << detokenized << "'"
594
+ << ", pos " << std::to_string(batch.pos[i])
595
+ << ", n_seq_id " << std::to_string(batch.n_seq_id[i])
596
+ << ", seq_id " << std::to_string(batch.seq_id[i][0])
597
+ << ", logits " << std::to_string(batch.logits[i]);
598
+ }
599
+
600
+ buf << " ]";
601
+
602
+ return buf.str();
603
+ }
604
+
605
+ void string_process_escapes(std::string & input) {
606
+ std::size_t input_len = input.length();
607
+ std::size_t output_idx = 0;
608
+
609
+ for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
610
+ if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
611
+ switch (input[++input_idx]) {
612
+ case 'n': input[output_idx++] = '\n'; break;
613
+ case 'r': input[output_idx++] = '\r'; break;
614
+ case 't': input[output_idx++] = '\t'; break;
615
+ case '\'': input[output_idx++] = '\''; break;
616
+ case '\"': input[output_idx++] = '\"'; break;
617
+ case '\\': input[output_idx++] = '\\'; break;
618
+ case 'x':
619
+ // Handle \x12, etc
620
+ if (input_idx + 2 < input_len) {
621
+ const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
622
+ char *err_p = nullptr;
623
+ const long val = std::strtol(x, &err_p, 16);
624
+ if (err_p == x + 2) {
625
+ input_idx += 2;
626
+ input[output_idx++] = char(val);
627
+ break;
628
+ }
629
+ }
630
+ // fall through
631
+ default: input[output_idx++] = '\\';
632
+ input[output_idx++] = input[input_idx]; break;
633
+ }
634
+ } else {
635
+ input[output_idx++] = input[input_idx];
636
+ }
637
+ }
638
+
639
+ input.resize(output_idx);
640
+ }
641
+
642
+ bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides) {
643
+ const char * sep = strchr(data, '=');
644
+ if (sep == nullptr || sep - data >= 128) {
645
+ LOG_ERR("%s: malformed KV override '%s'\n", __func__, data);
646
+ return false;
647
+ }
648
+ llama_model_kv_override kvo;
649
+ std::strncpy(kvo.key, data, sep - data);
650
+ kvo.key[sep - data] = 0;
651
+ sep++;
652
+ if (strncmp(sep, "int:", 4) == 0) {
653
+ sep += 4;
654
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
655
+ kvo.val_i64 = std::atol(sep);
656
+ } else if (strncmp(sep, "float:", 6) == 0) {
657
+ sep += 6;
658
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
659
+ kvo.val_f64 = std::atof(sep);
660
+ } else if (strncmp(sep, "bool:", 5) == 0) {
661
+ sep += 5;
662
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
663
+ if (std::strcmp(sep, "true") == 0) {
664
+ kvo.val_bool = true;
665
+ } else if (std::strcmp(sep, "false") == 0) {
666
+ kvo.val_bool = false;
667
+ } else {
668
+ LOG_ERR("%s: invalid boolean value for KV override '%s'\n", __func__, data);
669
+ return false;
670
+ }
671
+ } else if (strncmp(sep, "str:", 4) == 0) {
672
+ sep += 4;
673
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
674
+ if (strlen(sep) > 127) {
675
+ LOG_ERR("%s: malformed KV override '%s', value cannot exceed 127 chars\n", __func__, data);
676
+ return false;
677
+ }
678
+ strncpy(kvo.val_str, sep, 127);
679
+ kvo.val_str[127] = '\0';
680
+ } else {
681
+ LOG_ERR("%s: invalid type for KV override '%s'\n", __func__, data);
682
+ return false;
683
+ }
684
+ overrides.emplace_back(std::move(kvo));
685
+ return true;
686
+ }
687
+
688
+ //
689
+ // Filesystem utils
690
+ //
691
+
692
+ // Validate if a filename is safe to use
693
+ // To validate a full path, split the path by the OS-specific path separator, and validate each part with this function
694
+ bool fs_validate_filename(const std::string & filename) {
695
+ if (!filename.length()) {
696
+ // Empty filename invalid
697
+ return false;
698
+ }
699
+ if (filename.length() > 255) {
700
+ // Limit at common largest possible filename on Linux filesystems
701
+ // to avoid unnecessary further validation
702
+ // (On systems with smaller limits it will be caught by the OS)
703
+ return false;
704
+ }
705
+
706
+ std::u32string filename_utf32;
707
+ try {
708
+ #if defined(__clang__)
709
+ // disable C++17 deprecation warning for std::codecvt_utf8
710
+ # pragma clang diagnostic push
711
+ # pragma clang diagnostic ignored "-Wdeprecated-declarations"
712
+ #elif defined(__GNUC__)
713
+ # pragma GCC diagnostic push
714
+ # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
715
+ #endif
716
+
717
+ std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
718
+
719
+ #if defined(__clang__)
720
+ # pragma clang diagnostic pop
721
+ #elif defined(__GNUC__)
722
+ # pragma GCC diagnostic pop
723
+ #endif
724
+
725
+ filename_utf32 = converter.from_bytes(filename);
726
+
727
+ // If the reverse conversion mismatches, it means overlong UTF-8 sequences were used,
728
+ // or invalid encodings were encountered. Reject such attempts
729
+ std::string filename_reencoded = converter.to_bytes(filename_utf32);
730
+ if (filename_reencoded != filename) {
731
+ return false;
732
+ }
733
+ } catch (const std::exception &) {
734
+ return false;
735
+ }
736
+
737
+ // Check for forbidden codepoints:
738
+ // - Control characters
739
+ // - Unicode equivalents of illegal characters
740
+ // - UTF-16 surrogate pairs
741
+ // - UTF-8 replacement character
742
+ // - Byte order mark (BOM)
743
+ // - Illegal characters: / \ : * ? " < > |
744
+ for (char32_t c : filename_utf32) {
745
+ if (c <= 0x1F // Control characters (C0)
746
+ || c == 0x7F // Control characters (DEL)
747
+ || (c >= 0x80 && c <= 0x9F) // Control characters (C1)
748
+ || c == 0xFF0E // Fullwidth Full Stop (period equivalent)
749
+ || c == 0x2215 // Division Slash (forward slash equivalent)
750
+ || c == 0x2216 // Set Minus (backslash equivalent)
751
+ || (c >= 0xD800 && c <= 0xDFFF) // UTF-16 surrogate pairs
752
+ || c == 0xFFFD // Replacement Character (UTF-8)
753
+ || c == 0xFEFF // Byte Order Mark (BOM)
754
+ || c == '/' || c == '\\' || c == ':' || c == '*' // Illegal characters
755
+ || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
756
+ return false;
757
+ }
758
+ }
759
+
760
+ // Reject any leading or trailing ' ', or any trailing '.', these are stripped on Windows and will cause a different filename
761
+ // Unicode and other whitespace is not affected, only 0x20 space
762
+ if (filename.front() == ' ' || filename.back() == ' ' || filename.back() == '.') {
763
+ return false;
764
+ }
765
+
766
+ // Reject any ".." (currently stricter than necessary, it should be fine to just check for == ".." instead)
767
+ if (filename.find("..") != std::string::npos) {
768
+ return false;
769
+ }
770
+
771
+ // Reject "."
772
+ if (filename == ".") {
773
+ return false;
774
+ }
775
+
776
+ return true;
777
+ }
778
+
779
+ #include <iostream>
780
+
781
+
782
+ // returns true if successful, false otherwise
783
+ bool fs_create_directory_with_parents(const std::string & path) {
784
+ #ifdef _WIN32
785
+ std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
786
+ std::wstring wpath = converter.from_bytes(path);
787
+
788
+ // if the path already exists, check whether it's a directory
789
+ const DWORD attributes = GetFileAttributesW(wpath.c_str());
790
+ if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
791
+ return true;
792
+ }
793
+
794
+ size_t pos_slash = 0;
795
+
796
+ // process path from front to back, procedurally creating directories
797
+ while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
798
+ const std::wstring subpath = wpath.substr(0, pos_slash);
799
+
800
+ pos_slash += 1;
801
+
802
+ // skip the drive letter, in some systems it can return an access denied error
803
+ if (subpath.length() == 2 && subpath[1] == ':') {
804
+ continue;
805
+ }
806
+
807
+ const bool success = CreateDirectoryW(subpath.c_str(), NULL);
808
+
809
+ if (!success) {
810
+ const DWORD error = GetLastError();
811
+
812
+ // if the path already exists, ensure that it's a directory
813
+ if (error == ERROR_ALREADY_EXISTS) {
814
+ const DWORD attributes = GetFileAttributesW(subpath.c_str());
815
+ if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
816
+ return false;
817
+ }
818
+ } else {
819
+ return false;
820
+ }
821
+ }
822
+ }
823
+
824
+ return true;
825
+ #else
826
+ // if the path already exists, check whether it's a directory
827
+ struct stat info;
828
+ if (stat(path.c_str(), &info) == 0) {
829
+ return S_ISDIR(info.st_mode);
830
+ }
831
+
832
+ size_t pos_slash = 1; // skip leading slashes for directory creation
833
+
834
+ // process path from front to back, procedurally creating directories
835
+ while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
836
+ const std::string subpath = path.substr(0, pos_slash);
837
+ struct stat info;
838
+
839
+ // if the path already exists, ensure that it's a directory
840
+ if (stat(subpath.c_str(), &info) == 0) {
841
+ if (!S_ISDIR(info.st_mode)) {
842
+ return false;
843
+ }
844
+ } else {
845
+ // create parent directories
846
+ const int ret = mkdir(subpath.c_str(), 0755);
847
+ if (ret != 0) {
848
+ return false;
849
+ }
850
+ }
851
+
852
+ pos_slash += 1;
853
+ }
854
+
855
+ return true;
856
+ #endif // _WIN32
857
+ }
858
+
859
+ std::string fs_get_cache_directory() {
860
+ std::string cache_directory = "";
861
+ auto ensure_trailing_slash = [](std::string p) {
862
+ // Make sure to add trailing slash
863
+ if (p.back() != DIRECTORY_SEPARATOR) {
864
+ p += DIRECTORY_SEPARATOR;
865
+ }
866
+ return p;
867
+ };
868
+ if (getenv("LLAMA_CACHE")) {
869
+ cache_directory = std::getenv("LLAMA_CACHE");
870
+ } else {
871
+ #if defined(__linux__) || defined(__FreeBSD__) || defined(_AIX) || defined(__OpenBSD__)
872
+ if (std::getenv("XDG_CACHE_HOME")) {
873
+ cache_directory = std::getenv("XDG_CACHE_HOME");
874
+ } else {
875
+ cache_directory = std::getenv("HOME") + std::string("/.cache/");
876
+ }
877
+ #elif defined(__APPLE__)
878
+ cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
879
+ #elif defined(_WIN32)
880
+ cache_directory = std::getenv("LOCALAPPDATA");
881
+ #elif defined(__EMSCRIPTEN__)
882
+ cache_directory = "/tmp/";
883
+ #else
884
+ # error Unknown architecture
885
+ #endif
886
+ cache_directory = ensure_trailing_slash(cache_directory);
887
+ cache_directory += "llama.cpp";
888
+ }
889
+ return ensure_trailing_slash(cache_directory);
890
+ }
891
+
892
+ std::string fs_get_cache_file(const std::string & filename) {
893
+ LM_GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos);
894
+ std::string cache_directory = fs_get_cache_directory();
895
+ const bool success = fs_create_directory_with_parents(cache_directory);
896
+ if (!success) {
897
+ throw std::runtime_error("failed to create cache directory: " + cache_directory);
898
+ }
899
+ return cache_directory + filename;
900
+ }
901
+
902
+
903
+ //
904
+ // Model utils
905
+ //
906
+
907
+ struct common_init_result common_init_from_params(common_params & params) {
908
+ common_init_result iparams;
909
+ auto mparams = common_model_params_to_llama(params);
910
+
911
+ llama_model * model = llama_model_load_from_file(params.model.path.c_str(), mparams);
912
+ if (model == NULL) {
913
+ LOG_ERR("%s: failed to load model '%s'\n", __func__, params.model.path.c_str());
914
+ return iparams;
915
+ }
916
+
917
+ const llama_vocab * vocab = llama_model_get_vocab(model);
918
+
919
+ auto cparams = common_context_params_to_llama(params);
920
+
921
+ llama_context * lctx = llama_init_from_model(model, cparams);
922
+ if (lctx == NULL) {
923
+ LOG_ERR("%s: failed to create context with model '%s'\n", __func__, params.model.path.c_str());
924
+ #ifdef __EMSCRIPTEN__
925
+ fprintf(stderr, "@@WASM_LOAD@@ common_init: llama_init_from_model failed (null ctx)\n");
926
+ #endif
927
+ llama_model_free(model);
928
+ return iparams;
929
+ }
930
+
931
+ #ifdef __EMSCRIPTEN__
932
+ fprintf(stderr, "@@WASM_LOAD@@ common_init: llama_init_from_model ok ctx_shift=%d\n", params.ctx_shift ? 1 : 0);
933
+ #endif
934
+
935
+ if (params.ctx_shift && !llama_memory_can_shift(llama_get_memory(lctx))) {
936
+ LOG_WRN("%s: KV cache shifting is not supported for this context, disabling KV cache shifting\n", __func__);
937
+ params.ctx_shift = false;
938
+ }
939
+
940
+ #ifdef __EMSCRIPTEN__
941
+ fprintf(stderr, "@@WASM_LOAD@@ common_init: after ctx_shift\n");
942
+ #endif
943
+
944
+ if (!params.control_vectors.empty()) {
945
+ if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
946
+ if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_model_n_layer(model);
947
+
948
+ const auto cvec = common_control_vector_load(params.control_vectors);
949
+ if (cvec.n_embd == -1) {
950
+ llama_free(lctx);
951
+ llama_model_free(model);
952
+
953
+ return iparams;
954
+ }
955
+
956
+ int err = llama_apply_adapter_cvec(
957
+ lctx,
958
+ cvec.data.data(),
959
+ cvec.data.size(),
960
+ cvec.n_embd,
961
+ params.control_vector_layer_start,
962
+ params.control_vector_layer_end);
963
+ if (err) {
964
+ llama_free(lctx);
965
+ llama_model_free(model);
966
+
967
+ return iparams;
968
+ }
969
+ }
970
+
971
+ if (llama_pooling_type(lctx) == LLAMA_POOLING_TYPE_RANK) {
972
+ bool ok = true;
973
+
974
+ if (llama_vocab_bos(vocab) == LLAMA_TOKEN_NULL) {
975
+ LOG_WRN("%s: warning: vocab does not have a BOS token, reranking will not work\n", __func__);
976
+ ok = false;
977
+ }
978
+
979
+ bool has_eos = llama_vocab_eos(vocab) != LLAMA_TOKEN_NULL;
980
+ bool has_sep = llama_vocab_sep(vocab) != LLAMA_TOKEN_NULL;
981
+
982
+ if (!has_eos && !has_sep) {
983
+ LOG_WRN("%s: warning: vocab does not have an EOS token or SEP token, reranking will not work\n", __func__);
984
+ ok = false;
985
+ } else if (!has_eos) {
986
+ LOG_WRN("%s: warning: vocab does not have an EOS token, using SEP token as fallback\n", __func__);
987
+ } else if (!has_sep) {
988
+ LOG_WRN("%s: warning: vocab does not have a SEP token, reranking will not work\n", __func__);
989
+ ok = false;
990
+ }
991
+
992
+ if (!ok) {
993
+ llama_free(lctx);
994
+ llama_model_free(model);
995
+
996
+ return iparams;
997
+ }
998
+ }
999
+
1000
+ // load and optionally apply lora adapters
1001
+ for (auto & la : params.lora_adapters) {
1002
+ llama_adapter_lora_ptr lora;
1003
+ lora.reset(llama_adapter_lora_init(model, la.path.c_str()));
1004
+ if (lora == nullptr) {
1005
+ LOG_ERR("%s: failed to apply lora adapter '%s'\n", __func__, la.path.c_str());
1006
+ llama_free(lctx);
1007
+ llama_model_free(model);
1008
+ return iparams;
1009
+ }
1010
+
1011
+ la.ptr = lora.get();
1012
+ iparams.lora.emplace_back(std::move(lora)); // copy to list of loaded adapters
1013
+ }
1014
+
1015
+ if (!params.lora_init_without_apply) {
1016
+ common_set_adapter_lora(lctx, params.lora_adapters);
1017
+ }
1018
+
1019
+ #ifdef __EMSCRIPTEN__
1020
+ fprintf(stderr, "@@WASM_LOAD@@ common_init: post-lora, before sampling init\n");
1021
+ #endif
1022
+
1023
+ if (params.sampling.ignore_eos && llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
1024
+ LOG_WRN("%s: warning: vocab does not have an EOS token, ignoring --ignore-eos\n", __func__);
1025
+ params.sampling.ignore_eos = false;
1026
+ }
1027
+
1028
+ #ifndef __EMSCRIPTEN__
1029
+ // initialize once — scans full vocab; skipped on WASM (heap/stack pressure on large vocabs)
1030
+ for (llama_token i = 0; i < llama_vocab_n_tokens(vocab); i++) {
1031
+ if (llama_vocab_is_eog(vocab, i)) {
1032
+ LOG_INF("%s: added %s logit bias = %f\n", __func__, common_token_to_piece(lctx, i).c_str(), -INFINITY);
1033
+ params.sampling.logit_bias_eog.push_back({i, -INFINITY});
1034
+ }
1035
+ }
1036
+ #else
1037
+ fprintf(stderr, "@@WASM_LOAD@@ skip EOG logit-bias vocab scan (n_tokens=%d)\n", llama_vocab_n_tokens(vocab));
1038
+ #endif
1039
+
1040
+ if (params.sampling.ignore_eos) {
1041
+ // add EOG biases to the active set of logit biases
1042
+ params.sampling.logit_bias.insert(
1043
+ params.sampling.logit_bias.end(),
1044
+ params.sampling.logit_bias_eog.begin(), params.sampling.logit_bias_eog.end());
1045
+ }
1046
+
1047
+ if (params.sampling.penalty_last_n == -1) {
1048
+ #ifndef __EMSCRIPTEN__
1049
+ LOG_INF("%s: setting penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
1050
+ #endif
1051
+ params.sampling.penalty_last_n = llama_n_ctx(lctx);
1052
+ }
1053
+
1054
+ if (params.sampling.dry_penalty_last_n == -1) {
1055
+ #ifndef __EMSCRIPTEN__
1056
+ LOG_INF("%s: setting dry_penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
1057
+ #endif
1058
+ params.sampling.dry_penalty_last_n = llama_n_ctx(lctx);
1059
+ }
1060
+
1061
+ if (params.warmup) {
1062
+ LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
1063
+
1064
+ llama_set_warmup(lctx, true);
1065
+
1066
+ std::vector<llama_token> tmp;
1067
+ llama_token bos = llama_vocab_bos(vocab);
1068
+ llama_token eos = llama_vocab_eos(vocab);
1069
+
1070
+ // some models (e.g. T5) don't have a BOS token
1071
+ if (bos != LLAMA_TOKEN_NULL) {
1072
+ tmp.push_back(bos);
1073
+ }
1074
+ if (eos != LLAMA_TOKEN_NULL) {
1075
+ tmp.push_back(eos);
1076
+ }
1077
+ if (tmp.empty()) {
1078
+ tmp.push_back(0);
1079
+ }
1080
+
1081
+ if (llama_model_has_encoder(model)) {
1082
+ llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
1083
+ llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
1084
+ if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
1085
+ decoder_start_token_id = bos;
1086
+ }
1087
+ tmp.clear();
1088
+ tmp.push_back(decoder_start_token_id);
1089
+ }
1090
+ if (llama_model_has_decoder(model)) {
1091
+ llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
1092
+ }
1093
+ llama_memory_clear(llama_get_memory(lctx), true);
1094
+ llama_synchronize(lctx);
1095
+ llama_perf_context_reset(lctx);
1096
+ llama_set_warmup(lctx, false);
1097
+ }
1098
+
1099
+ iparams.model.reset(model);
1100
+ iparams.context.reset(lctx);
1101
+
1102
+ #ifdef __EMSCRIPTEN__
1103
+ fprintf(stderr, "@@WASM_LOAD@@ common_init_from_params done\n");
1104
+ #endif
1105
+
1106
+ return iparams;
1107
+ }
1108
+
1109
+ std::string get_model_endpoint() {
1110
+ const char * model_endpoint_env = getenv("MODEL_ENDPOINT");
1111
+ // We still respect the use of environment-variable "HF_ENDPOINT" for backward-compatibility.
1112
+ const char * hf_endpoint_env = getenv("HF_ENDPOINT");
1113
+ const char * endpoint_env = model_endpoint_env ? model_endpoint_env : hf_endpoint_env;
1114
+ std::string model_endpoint = "https://huggingface.co/";
1115
+ if (endpoint_env) {
1116
+ model_endpoint = endpoint_env;
1117
+ if (model_endpoint.back() != '/') model_endpoint += '/';
1118
+ }
1119
+ return model_endpoint;
1120
+ }
1121
+
1122
+ void common_set_adapter_lora(struct llama_context * ctx, std::vector<common_adapter_lora_info> & lora) {
1123
+ llama_clear_adapter_lora(ctx);
1124
+ for (auto & la : lora) {
1125
+ if (la.scale != 0.0f) {
1126
+ llama_set_adapter_lora(ctx, la.ptr, la.scale);
1127
+ }
1128
+ }
1129
+ }
1130
+
1131
+ struct llama_model_params common_model_params_to_llama(common_params & params) {
1132
+ auto mparams = llama_model_default_params();
1133
+
1134
+ if (!params.devices.empty()) {
1135
+ mparams.devices = params.devices.data();
1136
+ }
1137
+
1138
+ if (params.n_gpu_layers != -1) {
1139
+ mparams.n_gpu_layers = params.n_gpu_layers;
1140
+ }
1141
+
1142
+ mparams.vocab_only = params.vocab_only;
1143
+ mparams.main_gpu = params.main_gpu;
1144
+ mparams.split_mode = params.split_mode;
1145
+ mparams.tensor_split = params.tensor_split;
1146
+ mparams.use_mmap = params.use_mmap;
1147
+ mparams.use_mlock = params.use_mlock;
1148
+ mparams.check_tensors = params.check_tensors;
1149
+ mparams.use_extra_bufts = !params.no_extra_bufts;
1150
+
1151
+ if (params.kv_overrides.empty()) {
1152
+ mparams.kv_overrides = NULL;
1153
+ } else {
1154
+ LM_GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
1155
+ mparams.kv_overrides = params.kv_overrides.data();
1156
+ }
1157
+
1158
+ if (params.tensor_buft_overrides.empty()) {
1159
+ mparams.tensor_buft_overrides = NULL;
1160
+ } else {
1161
+ LM_GGML_ASSERT(params.tensor_buft_overrides.back().pattern == nullptr && "Tensor buffer overrides not terminated with empty pattern");
1162
+ mparams.tensor_buft_overrides = params.tensor_buft_overrides.data();
1163
+ }
1164
+
1165
+ mparams.progress_callback = params.load_progress_callback;
1166
+ mparams.progress_callback_user_data = params.load_progress_callback_user_data;
1167
+
1168
+ if (params.progress_callback != nullptr) {
1169
+ mparams.progress_callback = params.progress_callback;
1170
+ mparams.progress_callback_user_data = params.progress_callback_user_data;
1171
+ }
1172
+
1173
+ return mparams;
1174
+ }
1175
+
1176
+ struct llama_context_params common_context_params_to_llama(const common_params & params) {
1177
+ auto cparams = llama_context_default_params();
1178
+
1179
+ cparams.n_ctx = params.n_ctx;
1180
+ cparams.n_seq_max = params.n_parallel;
1181
+ cparams.n_batch = params.n_batch;
1182
+ cparams.n_ubatch = params.n_ubatch;
1183
+ cparams.n_threads = params.cpuparams.n_threads;
1184
+ cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
1185
+ params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
1186
+ cparams.embeddings = params.embedding;
1187
+ cparams.rope_scaling_type = params.rope_scaling_type;
1188
+ cparams.rope_freq_base = params.rope_freq_base;
1189
+ cparams.rope_freq_scale = params.rope_freq_scale;
1190
+ cparams.yarn_ext_factor = params.yarn_ext_factor;
1191
+ cparams.yarn_attn_factor = params.yarn_attn_factor;
1192
+ cparams.yarn_beta_fast = params.yarn_beta_fast;
1193
+ cparams.yarn_beta_slow = params.yarn_beta_slow;
1194
+ cparams.yarn_orig_ctx = params.yarn_orig_ctx;
1195
+ cparams.pooling_type = params.pooling_type;
1196
+ cparams.attention_type = params.attention_type;
1197
+ cparams.cb_eval = params.cb_eval;
1198
+ cparams.cb_eval_user_data = params.cb_eval_user_data;
1199
+ cparams.offload_kqv = !params.no_kv_offload;
1200
+ cparams.flash_attn = params.flash_attn;
1201
+ cparams.no_perf = params.no_perf;
1202
+ cparams.op_offload = !params.no_op_offload;
1203
+ cparams.swa_full = params.swa_full;
1204
+ cparams.kv_unified = params.kv_unified;
1205
+
1206
+ cparams.type_k = params.cache_type_k;
1207
+ cparams.type_v = params.cache_type_v;
1208
+
1209
+ return cparams;
1210
+ }
1211
+
1212
+ struct lm_ggml_threadpool_params lm_ggml_threadpool_params_from_cpu_params(const cpu_params & params) {
1213
+ struct lm_ggml_threadpool_params tpp;
1214
+
1215
+ lm_ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
1216
+
1217
+ if (params.mask_valid) {
1218
+ std::memcpy(&tpp.cpumask, &params.cpumask, LM_GGML_MAX_N_THREADS);
1219
+ }
1220
+
1221
+ tpp.prio = params.priority;
1222
+ tpp.poll = params.poll;
1223
+ tpp.strict_cpu = params.strict_cpu;
1224
+
1225
+ return tpp;
1226
+ }
1227
+
1228
+ //
1229
+ // Batch utils
1230
+ //
1231
+
1232
+ void common_batch_clear(struct llama_batch & batch) {
1233
+ batch.n_tokens = 0;
1234
+ }
1235
+
1236
+ void common_batch_add(
1237
+ struct llama_batch & batch,
1238
+ llama_token id,
1239
+ llama_pos pos,
1240
+ const std::vector<llama_seq_id> & seq_ids,
1241
+ bool logits) {
1242
+ LM_GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
1243
+
1244
+ batch.token [batch.n_tokens] = id;
1245
+ batch.pos [batch.n_tokens] = pos;
1246
+ batch.n_seq_id[batch.n_tokens] = seq_ids.size();
1247
+ for (size_t i = 0; i < seq_ids.size(); ++i) {
1248
+ batch.seq_id[batch.n_tokens][i] = seq_ids[i];
1249
+ }
1250
+ batch.logits [batch.n_tokens] = logits;
1251
+
1252
+ batch.n_tokens++;
1253
+ }
1254
+
1255
+ //
1256
+ // Token utils
1257
+ //
1258
+
1259
+ size_t common_lcp(const llama_tokens & a, const llama_tokens & b) {
1260
+ size_t i;
1261
+ for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
1262
+
1263
+ return i;
1264
+ }
1265
+
1266
+ size_t common_lcs(const llama_tokens & a, const llama_tokens & b) {
1267
+ // check for empty sequences
1268
+ if (a.empty() || b.empty()) {
1269
+ return 0;
1270
+ }
1271
+
1272
+ // get the lengths of the input sequences
1273
+ size_t a_len = a.size();
1274
+ size_t b_len = b.size();
1275
+
1276
+ // initialize the maximum length of the longest common subsequence (LCS)
1277
+ size_t max_length = 0;
1278
+
1279
+ // use two rows instead of a 2D matrix to optimize space
1280
+ std::vector<size_t> prev_row(b_len + 1, 0);
1281
+ std::vector<size_t> curr_row(b_len + 1, 0);
1282
+
1283
+ // iterate through the elements of a
1284
+ for (size_t i = 1; i <= a_len; i++) {
1285
+ // iterate through the elements of b
1286
+ for (size_t j = 1; j <= b_len; j++) {
1287
+ // if elements at the current positions match
1288
+ if (a[i - 1] == b[j - 1]) {
1289
+ // if it's the first element of either sequences, set LCS length to 1
1290
+ if (i == 1 || j == 1) {
1291
+ curr_row[j] = 1;
1292
+ } else {
1293
+ // increment LCS length by 1 compared to the previous element
1294
+ curr_row[j] = prev_row[j - 1] + 1;
1295
+ }
1296
+
1297
+ // update max_length if necessary
1298
+ if (curr_row[j] > max_length) {
1299
+ max_length = curr_row[j];
1300
+ }
1301
+ } else {
1302
+ // reset LCS length if elements don't match
1303
+ curr_row[j] = 0;
1304
+ }
1305
+ }
1306
+
1307
+ // update the previous row for the next iteration
1308
+ prev_row = curr_row;
1309
+ }
1310
+
1311
+ // return the maximum length of the LCS
1312
+ return max_length;
1313
+ }
1314
+
1315
+ //
1316
+ // Vocab utils
1317
+ //
1318
+
1319
+ std::vector<llama_token> common_tokenize(
1320
+ const struct llama_context * ctx,
1321
+ const std::string & text,
1322
+ bool add_special,
1323
+ bool parse_special) {
1324
+ const llama_model * model = llama_get_model(ctx);
1325
+ const llama_vocab * vocab = llama_model_get_vocab(model);
1326
+ return common_tokenize(vocab, text, add_special, parse_special);
1327
+ }
1328
+
1329
+ std::vector<llama_token> common_tokenize(
1330
+ const struct llama_vocab * vocab,
1331
+ const std::string & text,
1332
+ bool add_special,
1333
+ bool parse_special) {
1334
+ // upper limit for the number of tokens
1335
+ int n_tokens = text.length() + 2 * add_special;
1336
+ std::vector<llama_token> result(n_tokens);
1337
+ n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
1338
+ if (n_tokens == std::numeric_limits<int32_t>::min()) {
1339
+ throw std::runtime_error("Tokenization failed: input text too large, tokenization result exceeds int32_t limit");
1340
+ }
1341
+ if (n_tokens < 0) {
1342
+ result.resize(-n_tokens);
1343
+ int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
1344
+ LM_GGML_ASSERT(check == -n_tokens);
1345
+ } else {
1346
+ result.resize(n_tokens);
1347
+ }
1348
+ return result;
1349
+ }
1350
+
1351
+ std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
1352
+ const llama_model * model = llama_get_model(ctx);
1353
+ const llama_vocab * vocab = llama_model_get_vocab(model);
1354
+ return common_token_to_piece(vocab, token, special);
1355
+ }
1356
+
1357
+ std::string common_token_to_piece(const struct llama_vocab * vocab, llama_token token, bool special) {
1358
+ std::string piece;
1359
+ piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
1360
+ const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
1361
+ if (n_chars < 0) {
1362
+ piece.resize(-n_chars);
1363
+ int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
1364
+ LM_GGML_ASSERT(check == -n_chars);
1365
+ }
1366
+ else {
1367
+ piece.resize(n_chars);
1368
+ }
1369
+
1370
+ return piece;
1371
+ }
1372
+
1373
+ std::string common_detokenize(const struct llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
1374
+ const llama_model * model = llama_get_model(ctx);
1375
+ const llama_vocab * vocab = llama_model_get_vocab(model);
1376
+ return common_detokenize(vocab, tokens, special);
1377
+ }
1378
+
1379
+ std::string common_detokenize(const struct llama_vocab * vocab, const std::vector<llama_token> & tokens, bool special) {
1380
+ std::string text;
1381
+ text.resize(std::max(text.capacity(), tokens.size()));
1382
+ int32_t n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
1383
+ if (n_chars < 0) {
1384
+ text.resize(-n_chars);
1385
+ n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
1386
+ LM_GGML_ASSERT(n_chars <= (int32_t)text.size()); // whitespace trimming is performed after per-token detokenization
1387
+ }
1388
+
1389
+ text.resize(n_chars);
1390
+
1391
+ // NOTE: the original tokenizer decodes bytes after collecting the pieces.
1392
+ return text;
1393
+ }
1394
+
1395
+ //
1396
+ // Embedding utils
1397
+ //
1398
+
1399
+ void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
1400
+ double sum = 0.0;
1401
+
1402
+ switch (embd_norm) {
1403
+ case -1: // no normalisation
1404
+ sum = 1.0;
1405
+ break;
1406
+ case 0: // max absolute
1407
+ for (int i = 0; i < n; i++) {
1408
+ if (sum < std::abs(inp[i])) {
1409
+ sum = std::abs(inp[i]);
1410
+ }
1411
+ }
1412
+ sum /= 32760.0; // make an int16 range
1413
+ break;
1414
+ case 2: // euclidean
1415
+ for (int i = 0; i < n; i++) {
1416
+ sum += inp[i] * inp[i];
1417
+ }
1418
+ sum = std::sqrt(sum);
1419
+ break;
1420
+ default: // p-norm (euclidean is p-norm p=2)
1421
+ for (int i = 0; i < n; i++) {
1422
+ sum += std::pow(std::abs(inp[i]), embd_norm);
1423
+ }
1424
+ sum = std::pow(sum, 1.0 / embd_norm);
1425
+ break;
1426
+ }
1427
+
1428
+ const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
1429
+
1430
+ for (int i = 0; i < n; i++) {
1431
+ out[i] = inp[i] * norm;
1432
+ }
1433
+ }
1434
+
1435
+ float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
1436
+ double sum = 0.0;
1437
+ double sum1 = 0.0;
1438
+ double sum2 = 0.0;
1439
+
1440
+ for (int i = 0; i < n; i++) {
1441
+ sum += embd1[i] * embd2[i];
1442
+ sum1 += embd1[i] * embd1[i];
1443
+ sum2 += embd2[i] * embd2[i];
1444
+ }
1445
+
1446
+ // Handle the case where one or both vectors are zero vectors
1447
+ if (sum1 == 0.0 || sum2 == 0.0) {
1448
+ if (sum1 == 0.0 && sum2 == 0.0) {
1449
+ return 1.0f; // two zero vectors are similar
1450
+ }
1451
+ return 0.0f;
1452
+ }
1453
+
1454
+ return sum / (sqrt(sum1) * sqrt(sum2));
1455
+ }
1456
+
1457
+ //
1458
+ // Control vector utils
1459
+ //
1460
+
1461
+ static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
1462
+ common_control_vector_data result = { -1, {} };
1463
+
1464
+ lm_ggml_context * ctx = nullptr;
1465
+ struct lm_gguf_init_params meta_lm_gguf_params = {
1466
+ /* .no_alloc = */ false,
1467
+ /* .ctx = */ &ctx,
1468
+ };
1469
+ struct lm_gguf_context * ctx_gguf = lm_gguf_init_from_file(load_info.fname.c_str(), meta_lm_gguf_params);
1470
+ if (!ctx_gguf) {
1471
+ LOG_ERR("%s: failed to load control vector file from %s\n", __func__, load_info.fname.c_str());
1472
+ return result;
1473
+ }
1474
+
1475
+ int32_t n_tensors = lm_gguf_get_n_tensors(ctx_gguf);
1476
+ if (n_tensors == 0) {
1477
+ LOG_WRN("%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
1478
+ }
1479
+
1480
+ for (int i = 0; i < n_tensors; i++) {
1481
+ std::string name = lm_gguf_get_tensor_name(ctx_gguf, i);
1482
+
1483
+ int layer_idx = -1;
1484
+
1485
+ // split on '.'
1486
+ size_t dotpos = name.find('.');
1487
+ if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
1488
+ try {
1489
+ layer_idx = std::stoi(name.substr(dotpos + 1));
1490
+ } catch (...) {
1491
+ layer_idx = -1;
1492
+ }
1493
+ }
1494
+ if (layer_idx < 0) {
1495
+ LOG_ERR("%s: invalid/unparsable direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
1496
+ result.n_embd = -1;
1497
+ break;
1498
+ } else if (layer_idx == 0) {
1499
+ LOG_ERR("%s: invalid (zero) direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
1500
+ result.n_embd = -1;
1501
+ break;
1502
+ }
1503
+
1504
+ struct lm_ggml_tensor * tensor = lm_ggml_get_tensor(ctx, name.c_str());
1505
+ if (tensor->type != LM_GGML_TYPE_F32) {
1506
+ LOG_ERR("%s: invalid (non-F32) direction tensor type in %s\n", __func__, load_info.fname.c_str());
1507
+ result.n_embd = -1;
1508
+ break;
1509
+ }
1510
+ if (lm_ggml_n_dims(tensor) != 1) {
1511
+ LOG_ERR("%s: invalid (non-1D) direction tensor shape in %s\n", __func__, load_info.fname.c_str());
1512
+ result.n_embd = -1;
1513
+ break;
1514
+ }
1515
+
1516
+ if (result.n_embd == -1) {
1517
+ result.n_embd = lm_ggml_nelements(tensor);
1518
+ } else if (lm_ggml_nelements(tensor) != result.n_embd) {
1519
+ LOG_ERR("%s: direction tensor in %s does not match previous dimensions\n", __func__, load_info.fname.c_str());
1520
+ result.n_embd = -1;
1521
+ break;
1522
+ }
1523
+
1524
+ // extend if necessary - do not store data for layer 0 (it's not used)
1525
+ result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
1526
+
1527
+ const float * src = (const float *) tensor->data;
1528
+ float * dst = result.data.data() + result.n_embd * (layer_idx - 1); // layer 1 at [0]
1529
+ for (int j = 0; j < result.n_embd; j++) {
1530
+ dst[j] += src[j] * load_info.strength; // allows multiple directions for same layer in same file
1531
+ }
1532
+
1533
+ }
1534
+
1535
+ if (result.n_embd == -1) {
1536
+ LOG_WRN("%s: skipping %s due to invalid direction tensors\n", __func__, load_info.fname.c_str());
1537
+ result.data.clear();
1538
+ }
1539
+
1540
+ lm_gguf_free(ctx_gguf);
1541
+ lm_ggml_free(ctx);
1542
+
1543
+ return result;
1544
+ }
1545
+
1546
+ common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
1547
+ common_control_vector_data result = { -1, {} };
1548
+
1549
+ for (const auto & info : load_infos) {
1550
+ auto cur = common_control_vector_load_one(info);
1551
+
1552
+ if (cur.n_embd == -1) {
1553
+ result.n_embd = -1;
1554
+ break;
1555
+ }
1556
+ if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
1557
+ LOG_ERR("%s: control vectors in %s does not match previous dimensions\n", __func__, info.fname.c_str());
1558
+ result.n_embd = -1;
1559
+ break;
1560
+ }
1561
+
1562
+ if (result.n_embd == -1) {
1563
+ result = std::move(cur);
1564
+ } else {
1565
+ result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f); // extend if necessary
1566
+ for (size_t i = 0; i < cur.data.size(); i++) {
1567
+ result.data[i] += cur.data[i];
1568
+ }
1569
+ }
1570
+ }
1571
+
1572
+ if (result.n_embd == -1) {
1573
+ LOG_ERR("%s: no valid control vector files passed\n", __func__);
1574
+ result.data.clear();
1575
+ }
1576
+
1577
+ return result;
1578
+ }
1579
+
1580
+ lm_ggml_opt_dataset_t common_opt_dataset_init(struct llama_context * ctx, const std::vector<llama_token> & tokens, int64_t stride) {
1581
+ const int64_t ne_datapoint = llama_n_ctx(ctx);
1582
+ const int64_t ndata = (tokens.size() - ne_datapoint - 1) / stride;
1583
+ lm_ggml_opt_dataset_t result = lm_ggml_opt_dataset_init(
1584
+ LM_GGML_TYPE_I32, LM_GGML_TYPE_I32, ne_datapoint, ne_datapoint, ndata, /*ndata_shard =*/ 1);
1585
+
1586
+ llama_token * data = (llama_token *) lm_ggml_opt_dataset_data(result)->data;
1587
+ llama_token * labels = (llama_token *) lm_ggml_opt_dataset_labels(result)->data;
1588
+
1589
+ for (int64_t idata = 0; idata < ndata; ++idata) {
1590
+ memcpy(data + idata*ne_datapoint, tokens.data() + idata*stride + 0, ne_datapoint*sizeof(llama_token));
1591
+ memcpy(labels + idata*ne_datapoint, tokens.data() + idata*stride + 1, ne_datapoint*sizeof(llama_token));
1592
+ }
1593
+
1594
+ return result;
1595
+ }
1596
+
1597
+ lm_ggml_opt_optimizer_params common_opt_lr_pars(void * userdata) {
1598
+ lm_ggml_opt_optimizer_params result = lm_ggml_opt_get_default_optimizer_params(nullptr);
1599
+ const lr_opt & d = *(lr_opt *) userdata;
1600
+ result.adamw.alpha = result.sgd.alpha = d.get_lr(d.epoch);
1601
+ result.sgd.wd = result.adamw.wd = d.wd;
1602
+ return result;
1603
+ }
1604
+
1605
+ // TODO make all command line args case-insensitive
1606
+ static inline bool eq_case_insensitive(char const* a, char const* b) {
1607
+ return !
1608
+ #if defined(_MSC_VER)
1609
+ _stricmp
1610
+ #else
1611
+ strcasecmp
1612
+ #endif // defined(_MSC_VER)
1613
+ (a, b);
1614
+ }
1615
+
1616
+ enum lm_ggml_opt_optimizer_type common_opt_get_optimizer(const char * n) {
1617
+ if (eq_case_insensitive("adamw", n)) {
1618
+ return LM_GGML_OPT_OPTIMIZER_TYPE_ADAMW;
1619
+ }
1620
+ if (eq_case_insensitive("sgd", n)) {
1621
+ return LM_GGML_OPT_OPTIMIZER_TYPE_SGD;
1622
+ }
1623
+ return LM_GGML_OPT_OPTIMIZER_TYPE_COUNT;
1624
+ }
1625
+
1626
+ // TODO simplify to use just log and exp
1627
+ static float const k_log_2 = std::log(2.f);
1628
+
1629
+ void lr_opt::init() {
1630
+ if (lr_min > 0 && lr_min < lr0) {
1631
+ float nhalf = std::log(lr0 / lr_min) / k_log_2;
1632
+ float e = epochs;
1633
+ if (decay_epochs > 0 && decay_epochs < e) {
1634
+ e = decay_epochs;
1635
+ } else {
1636
+ decay_epochs = e;
1637
+ }
1638
+ scale_epoch = nhalf / e;
1639
+ }
1640
+ }
1641
+
1642
+ float lr_opt::get_lr(float epoch) const {
1643
+ float r = lr_min <= 0 ? lr0 :
1644
+ epoch >= decay_epochs ? lr_min :
1645
+ lr0 * std::pow(0.5f, epoch * scale_epoch);
1646
+ LOG_INF("epoch %.2g lr=%.2g\n", epoch, r);
1647
+ return r;
1648
+ }
1649
+
1650
+ #if defined(CAPLLAMA_BUILD_WASM) && defined(__EMSCRIPTEN__)
1651
+ #include <emscripten.h>
1652
+
1653
+ // JSPI dylink stub for _Z23common_init_from_paramsR13common_params must call a wasm
1654
+ // export wired in asyncifyStubs. Must live in this TU so the call is direct (not via
1655
+ // env import), otherwise stub → bridge → import → stub recurses infinitely.
1656
+ extern "C" {
1657
+
1658
+ EMSCRIPTEN_KEEPALIVE
1659
+ struct common_init_result cap_wasm_dylink_common_init_from_params(common_params * params) {
1660
+ return common_init_from_params(*params);
1661
+ }
1662
+
1663
+ } // extern "C"
1664
+ #endif