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
@@ -0,0 +1,1146 @@
1
+ #include "llama-memory-recurrent.h"
2
+
3
+ #include "llama-impl.h"
4
+ #include "llama-io.h"
5
+ #include "llama-batch.h"
6
+ #include "llama-model.h"
7
+
8
+ #include <algorithm>
9
+ #include <cassert>
10
+ #include <limits>
11
+ #include <map>
12
+ #include <stdexcept>
13
+
14
+ //
15
+ // llama_memory_recurrent
16
+ //
17
+
18
+ llama_memory_recurrent::llama_memory_recurrent(
19
+ const llama_model & model,
20
+ lm_ggml_type type_r,
21
+ lm_ggml_type type_s,
22
+ bool offload,
23
+ uint32_t mem_size,
24
+ uint32_t n_seq_max,
25
+ const layer_filter_cb & filter) : hparams(model.hparams), n_seq_max(n_seq_max) {
26
+ const int32_t n_layer = hparams.n_layer;
27
+
28
+ head = 0;
29
+ size = mem_size;
30
+ used = 0;
31
+
32
+ cells.clear();
33
+ cells.resize(mem_size);
34
+
35
+ // create a context for each buffer type
36
+ std::map<lm_ggml_backend_buffer_type_t, lm_ggml_context *> ctx_map;
37
+ auto ctx_for_buft = [&](lm_ggml_backend_buffer_type_t buft) -> lm_ggml_context * {
38
+ auto it = ctx_map.find(buft);
39
+ if (it == ctx_map.end()) {
40
+ lm_ggml_init_params params = {
41
+ /*.mem_size =*/ size_t(2u*n_layer*lm_ggml_tensor_overhead()),
42
+ /*.mem_buffer =*/ NULL,
43
+ /*.no_alloc =*/ true,
44
+ };
45
+
46
+ lm_ggml_context * ctx = lm_ggml_init(params);
47
+ if (!ctx) {
48
+ return nullptr;
49
+ }
50
+
51
+ ctx_map[buft] = ctx;
52
+ ctxs.emplace_back(ctx);
53
+
54
+ return ctx;
55
+ }
56
+
57
+ return it->second;
58
+ };
59
+
60
+ r_l.resize(n_layer);
61
+ s_l.resize(n_layer);
62
+
63
+ for (int i = 0; i < n_layer; i++) {
64
+ if (filter && !filter(i)) {
65
+ LLAMA_LOG_DEBUG("%s: layer %3d: skipped\n", __func__, i);
66
+ continue;
67
+ }
68
+
69
+ const char * dev_name = "CPU";
70
+
71
+ lm_ggml_backend_buffer_type_t buft = lm_ggml_backend_cpu_buffer_type();
72
+
73
+ if (offload) {
74
+ auto * dev = model.dev_layer(i);
75
+ buft = lm_ggml_backend_dev_buffer_type(dev);
76
+
77
+ dev_name = lm_ggml_backend_dev_name(dev);
78
+ }
79
+
80
+ LLAMA_LOG_DEBUG("%s, layer %3d: dev = %s\n", __func__, i, dev_name);
81
+
82
+ lm_ggml_context * ctx = ctx_for_buft(buft);
83
+ if (!ctx) {
84
+ throw std::runtime_error("failed to create ggml context for rs cache");
85
+ }
86
+
87
+ lm_ggml_tensor * r = lm_ggml_new_tensor_1d(ctx, type_r, hparams.n_embd_r()*mem_size);
88
+ lm_ggml_tensor * s = lm_ggml_new_tensor_1d(ctx, type_s, hparams.n_embd_s()*mem_size);
89
+ lm_ggml_format_name(r, "cache_r_l%d", i);
90
+ lm_ggml_format_name(s, "cache_s_l%d", i);
91
+ r_l[i] = r;
92
+ s_l[i] = s;
93
+ }
94
+
95
+ // allocate tensors and initialize the buffers to avoid NaNs in the padding
96
+ for (auto it : ctx_map) {
97
+ auto * buft = it.first;
98
+ auto * ctx = it.second;
99
+
100
+ lm_ggml_backend_buffer_t buf = lm_ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
101
+ if (!buf) {
102
+ throw std::runtime_error("failed to allocate buffer for rs cache");
103
+ }
104
+ lm_ggml_backend_buffer_clear(buf, 0);
105
+ LLAMA_LOG_INFO("%s: %10s RS buffer size = %8.2f MiB\n", __func__, lm_ggml_backend_buffer_name(buf), lm_ggml_backend_buffer_get_size(buf)/1024.0/1024.0);
106
+ bufs.emplace_back(buf);
107
+ }
108
+
109
+ {
110
+ const size_t memory_size_r = size_r_bytes();
111
+ const size_t memory_size_s = size_s_bytes();
112
+
113
+ LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs), R (%s): %7.2f MiB, S (%s): %7.2f MiB\n", __func__,
114
+ (float)(memory_size_r + memory_size_s) / (1024.0f * 1024.0f), mem_size, n_layer, n_seq_max,
115
+ lm_ggml_type_name(type_r), (float)memory_size_r / (1024.0f * 1024.0f),
116
+ lm_ggml_type_name(type_s), (float)memory_size_s / (1024.0f * 1024.0f));
117
+ }
118
+ }
119
+
120
+ void llama_memory_recurrent::clear(bool data) {
121
+ for (int32_t i = 0; i < (int32_t) size; ++i) {
122
+ cells[i].pos = -1;
123
+ cells[i].seq_id.clear();
124
+ cells[i].src = -1;
125
+ cells[i].tail = -1;
126
+ }
127
+
128
+ head = 0;
129
+ used = 0;
130
+
131
+ if (data) {
132
+ for (auto & buf : bufs) {
133
+ lm_ggml_backend_buffer_clear(buf.get(), 0);
134
+ }
135
+ }
136
+ }
137
+
138
+ bool llama_memory_recurrent::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
139
+ uint32_t new_head = size;
140
+
141
+ if (p0 < 0) {
142
+ p0 = 0;
143
+ }
144
+
145
+ if (p1 < 0) {
146
+ p1 = std::numeric_limits<llama_pos>::max();
147
+ }
148
+
149
+ // models like Mamba or RWKV can't have a state partially erased
150
+ if (seq_id >= (int64_t) size) {
151
+ // could be fatal
152
+ return false;
153
+ }
154
+ if (0 <= seq_id) {
155
+ int32_t & tail_id = cells[seq_id].tail;
156
+ if (tail_id >= 0) {
157
+ const auto & cell = cells[tail_id];
158
+ // partial intersection is invalid
159
+ if ((0 < p0 && p0 <= cell.pos) || (0 < p1 && p1 <= cell.pos)) {
160
+ return false;
161
+ }
162
+ // invalidate tails which will be cleared
163
+ if (p0 <= cell.pos && cell.pos < p1) {
164
+ tail_id = -1;
165
+ }
166
+ }
167
+ } else {
168
+ // seq_id is negative, then the range should include everything or nothing
169
+ if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
170
+ return false;
171
+ }
172
+ }
173
+
174
+ for (uint32_t i = 0; i < size; ++i) {
175
+ if (cells[i].pos >= p0 && cells[i].pos < p1) {
176
+ if (seq_id < 0) {
177
+ cells[i].seq_id.clear();
178
+ } else if (cells[i].has_seq_id(seq_id)) {
179
+ cells[i].seq_id.erase(seq_id);
180
+ } else {
181
+ continue;
182
+ }
183
+ if (cells[i].is_empty()) {
184
+ // keep count of the number of used cells
185
+ if (cells[i].pos >= 0) {
186
+ used--;
187
+ }
188
+ cells[i].pos = -1;
189
+ cells[i].src = -1;
190
+ if (new_head == size) {
191
+ new_head = i;
192
+ }
193
+ }
194
+ }
195
+ }
196
+
197
+ // If we freed up a slot, set head to it so searching can start there.
198
+ if (new_head != size && new_head < head) {
199
+ head = new_head;
200
+ }
201
+
202
+ return true;
203
+ }
204
+
205
+ void llama_memory_recurrent::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) {
206
+ if (seq_id_src == seq_id_dst) {
207
+ return;
208
+ }
209
+
210
+ if (p0 < 0) {
211
+ p0 = 0;
212
+ }
213
+
214
+ if (p1 < 0) {
215
+ p1 = std::numeric_limits<llama_pos>::max();
216
+ }
217
+
218
+ if ((uint32_t) seq_id_dst < size && (uint32_t) seq_id_src < size) {
219
+ auto & tail_src = cells[seq_id_src];
220
+ auto & tail_dst = cells[seq_id_dst];
221
+ if (tail_dst.tail >= 0) {
222
+ // clear destination seq_id if it wasn't empty
223
+ auto & cell_dst = cells[tail_dst.tail];
224
+
225
+ cell_dst.seq_id.erase(seq_id_dst);
226
+ tail_dst.tail = -1;
227
+ if (cell_dst.seq_id.empty()) {
228
+ cell_dst.pos = -1;
229
+ cell_dst.src = -1;
230
+ used -= 1;
231
+ }
232
+ }
233
+ if (tail_src.tail >= 0) {
234
+ auto & cell_src = cells[tail_src.tail];
235
+
236
+ cell_src.seq_id.insert(seq_id_dst);
237
+ tail_dst.tail = tail_src.tail;
238
+ }
239
+ }
240
+ }
241
+
242
+ void llama_memory_recurrent::seq_keep(llama_seq_id seq_id) {
243
+ uint32_t new_head = size;
244
+
245
+ for (uint32_t i = 0; i < size; ++i) {
246
+ if ((llama_seq_id) i != seq_id) {
247
+ cells[i].tail = -1;
248
+ }
249
+
250
+ if (!cells[i].has_seq_id(seq_id)) {
251
+ if (cells[i].pos >= 0) {
252
+ used--;
253
+ }
254
+
255
+ cells[i].pos = -1;
256
+ cells[i].src = -1;
257
+ cells[i].seq_id.clear();
258
+
259
+ if (new_head == size){
260
+ new_head = i;
261
+ }
262
+ } else {
263
+ cells[i].seq_id.clear();
264
+ cells[i].seq_id.insert(seq_id);
265
+ }
266
+ }
267
+
268
+ // If we freed up a slot, set head to it so searching can start there.
269
+ if (new_head != size && new_head < head) {
270
+ head = new_head;
271
+ }
272
+ }
273
+
274
+ void llama_memory_recurrent::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) {
275
+ if (shift == 0) {
276
+ return;
277
+ }
278
+
279
+ if (p0 < 0) {
280
+ p0 = 0;
281
+ }
282
+
283
+ if (p1 < 0) {
284
+ p1 = std::numeric_limits<llama_pos>::max();
285
+ }
286
+
287
+ // If there is no range then return early to avoid looping over the
288
+ if (p0 == p1) {
289
+ return;
290
+ }
291
+
292
+ // for Mamba-like or RWKV models, only the pos needs to be shifted
293
+ if (0 <= seq_id && seq_id < (int64_t) size) {
294
+ const int32_t tail_id = cells[seq_id].tail;
295
+ if (tail_id >= 0) {
296
+ auto & cell = cells[tail_id];
297
+ if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
298
+ cell.pos += shift;
299
+ }
300
+ }
301
+ }
302
+ }
303
+
304
+ void llama_memory_recurrent::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
305
+ if (d == 1) {
306
+ return;
307
+ }
308
+
309
+ if (p0 < 0) {
310
+ p0 = 0;
311
+ }
312
+
313
+ if (p1 < 0) {
314
+ p1 = std::numeric_limits<llama_pos>::max();
315
+ }
316
+
317
+ // If there is no range then return early to avoid looping over the cache.
318
+ if (p0 == p1) {
319
+ return;
320
+ }
321
+
322
+ // for Mamba-like or RWKV models, only the pos needs to be changed
323
+ if (0 <= seq_id && seq_id < (int64_t) size) {
324
+ const int32_t tail_id = cells[seq_id].tail;
325
+ if (tail_id >= 0) {
326
+ auto & cell = cells[tail_id];
327
+ if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
328
+ cell.pos /= d;
329
+ }
330
+ }
331
+ }
332
+ }
333
+
334
+ llama_pos llama_memory_recurrent::seq_pos_min(llama_seq_id seq_id) const {
335
+ llama_pos result = std::numeric_limits<llama_pos>::max();
336
+
337
+ for (uint32_t i = 0; i < size; ++i) {
338
+ if (cells[i].has_seq_id(seq_id)) {
339
+ result = std::min(result, cells[i].pos);
340
+ }
341
+ }
342
+
343
+ if (result == std::numeric_limits<llama_pos>::max()) {
344
+ result = -1;
345
+ }
346
+
347
+ return result;
348
+ }
349
+
350
+ llama_pos llama_memory_recurrent::seq_pos_max(llama_seq_id seq_id) const {
351
+ llama_pos result = -1;
352
+
353
+ for (uint32_t i = 0; i < size; ++i) {
354
+ if (cells[i].has_seq_id(seq_id)) {
355
+ result = std::max(result, cells[i].pos);
356
+ }
357
+ }
358
+
359
+ return result;
360
+ }
361
+
362
+ llama_memory_context_ptr llama_memory_recurrent::init_batch(llama_batch_allocr & balloc, uint32_t n_ubatch, bool embd_all) {
363
+ do {
364
+ balloc.split_reset();
365
+
366
+ std::vector<llama_ubatch> ubatches;
367
+ while (true) {
368
+ llama_ubatch ubatch;
369
+
370
+ if (embd_all) {
371
+ // if all tokens are output, split by sequence
372
+ ubatch = balloc.split_seq(n_ubatch);
373
+ } else {
374
+ ubatch = balloc.split_equal(n_ubatch, false);
375
+ }
376
+
377
+ if (ubatch.n_tokens == 0) {
378
+ break;
379
+ }
380
+
381
+ ubatches.push_back(std::move(ubatch)); // NOLINT
382
+ }
383
+
384
+ if (balloc.get_n_used() < balloc.get_n_tokens()) {
385
+ // failed to find a suitable split
386
+ break;
387
+ }
388
+
389
+ if (!prepare(ubatches)) {
390
+ break;
391
+ }
392
+
393
+ return std::make_unique<llama_memory_recurrent_context>(this, std::move(ubatches));
394
+ } while (false);
395
+
396
+ return std::make_unique<llama_memory_recurrent_context>(LLAMA_MEMORY_STATUS_FAILED_PREPARE);
397
+ }
398
+
399
+ llama_memory_context_ptr llama_memory_recurrent::init_full() {
400
+ return std::make_unique<llama_memory_recurrent_context>(this);
401
+ }
402
+
403
+ llama_memory_context_ptr llama_memory_recurrent::init_update(llama_context * lctx, bool optimize) {
404
+ LM_GGML_UNUSED(lctx);
405
+ LM_GGML_UNUSED(optimize);
406
+
407
+ return std::make_unique<llama_memory_recurrent_context>(LLAMA_MEMORY_STATUS_NO_UPDATE);
408
+ }
409
+
410
+ bool llama_memory_recurrent::prepare(const std::vector<llama_ubatch> & ubatches) {
411
+ // simply remember the full state because it is very small for this type of cache
412
+ // TODO: optimize
413
+ auto org_cells = cells;
414
+ auto org_used = used;
415
+ auto org_head = head;
416
+
417
+ bool success = true;
418
+
419
+ for (const auto & ubatch : ubatches) {
420
+ if (!find_slot(ubatch)) {
421
+ success = false;
422
+ break;
423
+ }
424
+ }
425
+
426
+ // restore the original state
427
+ cells = std::move(org_cells);
428
+ used = org_used;
429
+ head = org_head;
430
+
431
+ return success;
432
+ }
433
+
434
+ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) {
435
+ const uint32_t n_seq_tokens = ubatch.n_seq_tokens;
436
+ const uint32_t n_seqs = ubatch.n_seqs;
437
+
438
+ // if we have enough unused cells before the current head ->
439
+ // better to start searching from the beginning of the cache, hoping to fill it
440
+ if (head > used + 2*n_seqs) {
441
+ head = 0;
442
+ }
443
+
444
+ // For recurrent state architectures (like Mamba or RWKV),
445
+ // each cache cell can store the state for a whole sequence.
446
+ // A slot should be always be contiguous.
447
+
448
+ // can only process batches with an equal number of new tokens in each sequence
449
+ LM_GGML_ASSERT(ubatch.equal_seqs());
450
+
451
+ int32_t min = size - 1;
452
+ int32_t max = 0;
453
+
454
+ // everything should fit if all seq_ids are smaller than the max
455
+ for (uint32_t s = 0; s < n_seqs; ++s) {
456
+ const uint32_t i = s*n_seq_tokens; // first token of sequence set s
457
+ const uint32_t n_seq_id = ubatch.n_seq_id[i];
458
+
459
+ for (uint32_t j = 0; j < n_seq_id; ++j) {
460
+ const llama_seq_id seq_id = ubatch.seq_id[i][j];
461
+
462
+ if (seq_id < 0 || (uint32_t) seq_id >= size) {
463
+ // too big seq_id
464
+ // TODO: would it be possible to resize the cache instead?
465
+ LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%u Try using a bigger --parallel value\n", __func__, seq_id, n_seq_max);
466
+ return false;
467
+ }
468
+ if (j > 0) {
469
+ auto & seq = cells[seq_id];
470
+ if (seq.tail >= 0) {
471
+ auto & cell = cells[seq.tail];
472
+ // clear cells from seq_ids that become shared
473
+ // (should not normally happen, but let's handle it anyway)
474
+ cell.seq_id.erase(seq_id);
475
+ seq.tail = -1;
476
+ if (cell.seq_id.empty()) {
477
+ cell.pos = -1;
478
+ cell.src = -1;
479
+ used -= 1;
480
+ }
481
+ }
482
+ }
483
+ }
484
+ }
485
+
486
+ #ifndef NDEBUG
487
+ {
488
+ std::vector<int32_t> tails_verif;
489
+ tails_verif.assign(size, -1);
490
+ for (uint32_t i = 0; i < size; ++i) {
491
+ auto & cell = cells[i];
492
+ for (llama_seq_id seq_id : cell.seq_id) {
493
+ if (tails_verif[seq_id] != -1) {
494
+ LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
495
+ }
496
+ tails_verif[seq_id] = i;
497
+ }
498
+ }
499
+ for (uint32_t i = 0; i < size; ++i) {
500
+ if (tails_verif[i] != cells[i].tail) {
501
+ LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cells[i].tail, tails_verif[i]);
502
+ }
503
+ }
504
+ }
505
+ #endif
506
+
507
+ // find next empty cell
508
+ uint32_t next_empty_cell = head;
509
+
510
+ for (uint32_t i = 0; i < size; ++i) {
511
+ if (next_empty_cell >= size) { next_empty_cell -= size; }
512
+ auto & cell = cells[next_empty_cell];
513
+ if (cell.is_empty()) { break; }
514
+ next_empty_cell += 1;
515
+ }
516
+
517
+ // find usable cell range
518
+ for (uint32_t s = 0; s < n_seqs; ++s) {
519
+ const uint32_t i = s*n_seq_tokens;
520
+ const llama_seq_id seq_id = ubatch.seq_id[i][0];
521
+ auto & seq_meta = cells[seq_id];
522
+ bool has_cell = false;
523
+ if (seq_meta.tail >= 0) {
524
+ auto & cell = cells[seq_meta.tail];
525
+ LM_GGML_ASSERT(cell.has_seq_id(seq_id));
526
+ // does this seq_id "own" the cell?
527
+ if (cell.seq_id.size() == 1) { has_cell = true; }
528
+ }
529
+ if (!has_cell) {
530
+ auto & empty_cell = cells[next_empty_cell];
531
+ LM_GGML_ASSERT(empty_cell.is_empty());
532
+ // copy old tail into the empty cell
533
+ if (seq_meta.tail >= 0) {
534
+ auto & orig_cell = cells[seq_meta.tail];
535
+ empty_cell.pos = orig_cell.pos;
536
+ empty_cell.src = orig_cell.src;
537
+ orig_cell.seq_id.erase(seq_id);
538
+ empty_cell.seq_id.insert(seq_id); // will be overwritten
539
+ LM_GGML_ASSERT(!orig_cell.is_empty()); // has at least one remaining seq_id
540
+ }
541
+ seq_meta.tail = next_empty_cell;
542
+ // find next empty cell
543
+ if (s + 1 < n_seqs) {
544
+ for (uint32_t j = 0; j < size; ++j) {
545
+ next_empty_cell += 1;
546
+ if (next_empty_cell >= size) { next_empty_cell -= size; }
547
+ auto & cell = cells[next_empty_cell];
548
+ if (cell.is_empty()) { break; }
549
+ }
550
+ }
551
+ }
552
+ if (min > seq_meta.tail) { min = seq_meta.tail; }
553
+ if (max < seq_meta.tail) { max = seq_meta.tail; }
554
+ }
555
+
556
+ // gather and re-order
557
+ for (uint32_t s = 0; s < n_seqs; ++s) {
558
+ const uint32_t i = s*n_seq_tokens;
559
+ const int32_t dst_id = s + min;
560
+ const int32_t src_id = cells[ubatch.seq_id[i][0]].tail;
561
+ if (dst_id != src_id) {
562
+ auto & dst_cell = cells[dst_id];
563
+ auto & src_cell = cells[src_id];
564
+
565
+ std::swap(dst_cell.pos, src_cell.pos);
566
+ std::swap(dst_cell.src, src_cell.src);
567
+ std::swap(dst_cell.seq_id, src_cell.seq_id);
568
+
569
+ // swap tails
570
+ for (uint32_t j = 0; j < size; ++j) {
571
+ int32_t & tail = cells[j].tail;
572
+ if (tail == src_id) {
573
+ tail = dst_id;
574
+ } else if (tail == dst_id) {
575
+ tail = src_id;
576
+ }
577
+ }
578
+ }
579
+ }
580
+
581
+ // update the pos of the used seqs
582
+ for (uint32_t s = 0; s < n_seqs; ++s) {
583
+ const uint32_t i = s*n_seq_tokens;
584
+ const llama_pos last_pos = ubatch.pos[i + n_seq_tokens - 1];
585
+ const int32_t cell_id = s + min;
586
+ auto & cell = cells[cell_id];
587
+
588
+ if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
589
+ // What should happen when the pos backtracks or skips a value?
590
+ // Clearing the state mid-batch would require special-casing which isn't done.
591
+ LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
592
+ __func__, last_pos, cell.pos, ubatch.seq_id[i][0], n_seq_tokens);
593
+ }
594
+ cell.pos = last_pos;
595
+ cell.seq_id.clear();
596
+ for (int32_t j = 0; j < ubatch.n_seq_id[i]; ++j) {
597
+ const llama_seq_id seq_id = ubatch.seq_id[i][j];
598
+ cell.seq_id.insert(seq_id);
599
+ cells[seq_id].tail = cell_id;
600
+ }
601
+ }
602
+
603
+ // Find first cell without src refs, to use as the zero-ed state
604
+ {
605
+ // TODO: bake-in src refcounts in the cell metadata
606
+ std::vector<int32_t> refcounts(size, 0);
607
+ for (size_t i = 0; i < size; ++i) {
608
+ const int32_t src = cells[i].src;
609
+ if (src >= 0) {
610
+ refcounts[src] += 1;
611
+ }
612
+ }
613
+
614
+ rs_z = -1;
615
+ for (int i = min; i <= max; ++i) {
616
+ if (refcounts[i] == 0) {
617
+ rs_z = i;
618
+ break;
619
+ }
620
+ }
621
+
622
+ for (int i = min; i <= max; ++i) {
623
+ if (cells[i].src < 0) {
624
+ LM_GGML_ASSERT(rs_z >= 0);
625
+ cells[i].src0 = rs_z;
626
+ } else {
627
+ // Stage the source ids for all used cells to allow correct seq_* behavior
628
+ // and still make these values available when setting the inputs
629
+ cells[i].src0 = cells[i].src;
630
+ }
631
+ cells[i].src = i; // avoid moving or clearing twice
632
+ }
633
+ }
634
+
635
+ // allow getting the range of used cells, from head to head + n
636
+ head = min;
637
+ n = max - min + 1;
638
+ used = std::count_if(cells.begin(), cells.end(),
639
+ [](const mem_cell & cell){ return !cell.is_empty(); });
640
+
641
+ // sanity check
642
+ return n >= n_seqs;
643
+ }
644
+
645
+ bool llama_memory_recurrent::get_can_shift() const {
646
+ // shifting the pos is trivial for recurrent models
647
+ return true;
648
+ }
649
+
650
+ size_t llama_memory_recurrent::total_size() const {
651
+ size_t size = 0;
652
+ for (const auto & buf : bufs) {
653
+ size += lm_ggml_backend_buffer_get_size(buf.get());
654
+ }
655
+
656
+ return size;
657
+ }
658
+
659
+ size_t llama_memory_recurrent::size_r_bytes() const {
660
+ size_t size_r_bytes = 0;
661
+
662
+ for (const auto & r : r_l) {
663
+ if (r != nullptr) {
664
+ size_r_bytes += lm_ggml_nbytes(r);
665
+ }
666
+ }
667
+
668
+ return size_r_bytes;
669
+ }
670
+
671
+ size_t llama_memory_recurrent::size_s_bytes() const {
672
+ size_t size_s_bytes = 0;
673
+
674
+ for (const auto & s : s_l) {
675
+ if (s != nullptr) {
676
+ size_s_bytes += lm_ggml_nbytes(s);
677
+ }
678
+ }
679
+
680
+ return size_s_bytes;
681
+ }
682
+
683
+ void llama_memory_recurrent::state_write(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) const {
684
+ LM_GGML_UNUSED(flags);
685
+
686
+ std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
687
+ uint32_t cell_count = 0;
688
+
689
+ // Count the number of cells with the specified seq_id
690
+ // Find all the ranges of cells with this seq id (or all, when -1)
691
+ uint32_t cell_range_begin = size;
692
+ for (uint32_t i = 0; i < size; ++i) {
693
+ const auto & cell = cells[i];
694
+ if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
695
+ ++cell_count;
696
+ if (cell_range_begin == size) {
697
+ cell_range_begin = i;
698
+ }
699
+ } else {
700
+ if (cell_range_begin != size) {
701
+ cell_ranges.emplace_back(cell_range_begin, i);
702
+ cell_range_begin = size;
703
+ }
704
+ }
705
+ }
706
+ if (cell_range_begin != size) {
707
+ cell_ranges.emplace_back(cell_range_begin, size);
708
+ }
709
+
710
+ // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
711
+ uint32_t cell_count_check = 0;
712
+ for (const auto & range : cell_ranges) {
713
+ cell_count_check += range.second - range.first;
714
+ }
715
+ LM_GGML_ASSERT(cell_count == cell_count_check);
716
+
717
+ io.write(&cell_count, sizeof(cell_count));
718
+
719
+ state_write_meta(io, cell_ranges, seq_id);
720
+ state_write_data(io, cell_ranges);
721
+ }
722
+
723
+ void llama_memory_recurrent::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
724
+ LM_GGML_UNUSED(flags);
725
+
726
+ uint32_t cell_count;
727
+ io.read_to(&cell_count, sizeof(cell_count));
728
+
729
+ bool res = true;
730
+
731
+ res = res && state_read_meta(io, cell_count, seq_id);
732
+ res = res && state_read_data(io, cell_count);
733
+
734
+ if (!res) {
735
+ if (seq_id == -1) {
736
+ clear(true);
737
+ } else {
738
+ seq_rm(seq_id, -1, -1);
739
+ }
740
+ throw std::runtime_error("failed to restore kv cache");
741
+ }
742
+ }
743
+
744
+ void llama_memory_recurrent::state_write_meta(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges, llama_seq_id seq_id) const {
745
+ for (const auto & range : cell_ranges) {
746
+ for (uint32_t i = range.first; i < range.second; ++i) {
747
+ const auto & cell = cells[i];
748
+ const llama_pos pos = cell.pos;
749
+ const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
750
+
751
+ io.write(&pos, sizeof(pos));
752
+ io.write(&n_seq_id, sizeof(n_seq_id));
753
+
754
+ if (n_seq_id) {
755
+ for (auto seq_id : cell.seq_id) {
756
+ io.write(&seq_id, sizeof(seq_id));
757
+ }
758
+ }
759
+ }
760
+ }
761
+ }
762
+
763
+ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) const {
764
+ const uint32_t s_trans = 0;
765
+ const uint32_t n_layer = hparams.n_layer;
766
+
767
+ io.write(&s_trans, sizeof(s_trans));
768
+ io.write(&n_layer, sizeof(n_layer));
769
+
770
+ std::vector<uint8_t> tmp_buf;
771
+
772
+ // Iterate and write all the keys first, each row is a cell
773
+ // Get whole range at a time
774
+ for (uint32_t il = 0; il < n_layer; ++il) {
775
+ // skip null layers (read_data will handle this by checking "r_l" and "s_l" for null)
776
+ if (r_l[il] == nullptr) continue;
777
+
778
+ // Write key type
779
+ const int32_t r_type_i = (int32_t)r_l[il]->type;
780
+ io.write(&r_type_i, sizeof(r_type_i));
781
+
782
+ // Write row size of key
783
+ const uint64_t r_size_row = lm_ggml_row_size(r_l[il]->type, hparams.n_embd_r());
784
+ io.write(&r_size_row, sizeof(r_size_row));
785
+
786
+ // Read each range of cells of k_size length each into tmp_buf and write out
787
+ for (const auto & range : cell_ranges) {
788
+ const size_t range_size = range.second - range.first;
789
+ const size_t buf_size = range_size * r_size_row;
790
+ io.write_tensor(r_l[il], range.first * r_size_row, buf_size);
791
+ }
792
+ }
793
+
794
+ if (!s_trans) {
795
+ for (uint32_t il = 0; il < n_layer; ++il) {
796
+ // skip null layers (read_data will handle this by checking "r_l" and "s_l" for null)
797
+ if (s_l[il] == nullptr) continue;
798
+
799
+ // Write value type
800
+ const int32_t s_type_i = (int32_t)s_l[il]->type;
801
+ io.write(&s_type_i, sizeof(s_type_i));
802
+
803
+ // Write row size of value
804
+ const uint64_t s_size_row = lm_ggml_row_size(s_l[il]->type, hparams.n_embd_s());
805
+ io.write(&s_size_row, sizeof(s_size_row));
806
+
807
+ // Read each range of cells of s_size length each into tmp_buf and write out
808
+ for (const auto & range : cell_ranges) {
809
+ const size_t range_size = range.second - range.first;
810
+ const size_t buf_size = range_size * s_size_row;
811
+ io.write_tensor(s_l[il], range.first * s_size_row, buf_size);
812
+ }
813
+ }
814
+ } else {
815
+ // When v is transposed, we also need the element size and get the element ranges from each row
816
+ const uint32_t mem_size = size;
817
+ for (uint32_t il = 0; il < n_layer; ++il) {
818
+ // skip null layers (read_data will handle this by checking "r_l" and "s_l" for null)
819
+ if (s_l[il] == nullptr) continue;
820
+
821
+ const uint32_t n_embd_s = hparams.n_embd_s();
822
+
823
+ // Write value type
824
+ const int32_t s_type_i = (int32_t)s_l[il]->type;
825
+ io.write(&s_type_i, sizeof(s_type_i));
826
+
827
+ // Write element size
828
+ const uint32_t s_size_el = lm_ggml_type_size(s_l[il]->type);
829
+ io.write(&s_size_el, sizeof(s_size_el));
830
+
831
+ // Write GQA embedding size
832
+ io.write(&n_embd_s, sizeof(n_embd_s));
833
+
834
+ // For each row, we get the element values of each cell
835
+ for (uint32_t j = 0; j < n_embd_s; ++j) {
836
+ // Read each range of cells of v_size_el length each into tmp_buf and write out
837
+ for (const auto & range : cell_ranges) {
838
+ const size_t range_size = range.second - range.first;
839
+ const size_t src_offset = (range.first + j * mem_size) * s_size_el;
840
+ const size_t buf_size = range_size * s_size_el;
841
+ io.write_tensor(s_l[il], src_offset, buf_size);
842
+ }
843
+ }
844
+ }
845
+ }
846
+ }
847
+
848
+ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) {
849
+ if (dest_seq_id != -1) {
850
+ // single sequence
851
+
852
+ seq_rm(dest_seq_id, -1, -1);
853
+
854
+ llama_batch_allocr balloc(hparams.n_pos_per_embd());
855
+
856
+ llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1);
857
+
858
+ for (uint32_t i = 0; i < cell_count; ++i) {
859
+ llama_pos pos;
860
+ uint32_t n_seq_id;
861
+
862
+ io.read_to(&pos, sizeof(pos));
863
+ io.read_to(&n_seq_id, sizeof(n_seq_id));
864
+
865
+ if (n_seq_id != 0) {
866
+ LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
867
+ return false;
868
+ }
869
+
870
+ ubatch.pos[i] = pos;
871
+ }
872
+ ubatch.n_seq_id[0] = 1;
873
+ ubatch.seq_id[0] = &dest_seq_id;
874
+
875
+ if (!find_slot(ubatch)) {
876
+ LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
877
+ return false;
878
+ }
879
+
880
+ // DEBUG CHECK: kv.head should be our first cell, kv.head + cell_count - 1 should be our last cell (verify seq_id and pos values)
881
+ // Assume that this is one contiguous block of cells
882
+ LM_GGML_ASSERT(head + cell_count <= size);
883
+ LM_GGML_ASSERT(cells[head].pos == ubatch.pos[0]);
884
+ LM_GGML_ASSERT(cells[head + cell_count - 1].pos == ubatch.pos[cell_count - 1]);
885
+ LM_GGML_ASSERT(cells[head].has_seq_id(dest_seq_id));
886
+ LM_GGML_ASSERT(cells[head + cell_count - 1].has_seq_id(dest_seq_id));
887
+ } else {
888
+ // whole KV cache restore
889
+
890
+ if (cell_count > size) {
891
+ LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
892
+ return false;
893
+ }
894
+
895
+ clear(true);
896
+
897
+ for (uint32_t i = 0; i < cell_count; ++i) {
898
+ auto & cell = cells[i];
899
+
900
+ llama_pos pos;
901
+ uint32_t n_seq_id;
902
+
903
+ io.read_to(&pos, sizeof(pos));
904
+ io.read_to(&n_seq_id, sizeof(n_seq_id));
905
+
906
+ cell.pos = pos;
907
+
908
+ for (uint32_t j = 0; j < n_seq_id; ++j) {
909
+ llama_seq_id seq_id;
910
+ io.read_to(&seq_id, sizeof(seq_id));
911
+
912
+ // TODO: llama_memory_recurrent should have a notion of max sequences
913
+ //if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
914
+ if (seq_id < 0) {
915
+ //LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
916
+ LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, inf)\n", __func__, seq_id);
917
+ return false;
918
+ }
919
+
920
+ cell.seq_id.insert(seq_id);
921
+
922
+ int32_t & tail = cells[seq_id].tail;
923
+ if (tail != -1) {
924
+ LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
925
+ return false;
926
+ }
927
+ tail = i;
928
+ }
929
+ }
930
+
931
+ head = 0;
932
+ used = cell_count;
933
+ }
934
+
935
+ for (uint32_t i = 0; i < cell_count; ++i) {
936
+ uint32_t cell_id = head + i;
937
+ // make sure the recurrent states will keep their restored state
938
+ cells[cell_id].src = cell_id;
939
+ }
940
+
941
+ return true;
942
+ }
943
+
944
+ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell_count) {
945
+ uint32_t s_trans;
946
+ uint32_t n_layer;
947
+ io.read_to(&s_trans, sizeof(s_trans));
948
+ io.read_to(&n_layer, sizeof(n_layer));
949
+
950
+ if (n_layer != hparams.n_layer) {
951
+ LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
952
+ return false;
953
+ }
954
+ if (cell_count > size) {
955
+ LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, size);
956
+ return false;
957
+ }
958
+ if (false != (bool) s_trans) {
959
+ LLAMA_LOG_ERROR("%s: incompatible s transposition\n", __func__);
960
+ return false;
961
+ }
962
+
963
+ // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
964
+ for (uint32_t il = 0; il < n_layer; ++il) {
965
+ // skip null layers
966
+ if (r_l[il] == nullptr) continue;
967
+
968
+ // Read type of key
969
+ int32_t r_type_i_ref;
970
+ io.read_to(&r_type_i_ref, sizeof(r_type_i_ref));
971
+ const int32_t r_type_i = (int32_t) r_l[il]->type;
972
+ if (r_type_i != r_type_i_ref) {
973
+ LLAMA_LOG_ERROR("%s: mismatched r type (%d != %d, layer %d)\n", __func__, r_type_i, r_type_i_ref, il);
974
+ return false;
975
+ }
976
+
977
+ // Read row size of key
978
+ uint64_t r_size_row_ref;
979
+ io.read_to(&r_size_row_ref, sizeof(r_size_row_ref));
980
+ const size_t r_size_row = lm_ggml_row_size(r_l[il]->type, hparams.n_embd_r());
981
+ if (r_size_row != r_size_row_ref) {
982
+ LLAMA_LOG_ERROR("%s: mismatched r row size (%zu != %zu, layer %d)\n", __func__, r_size_row, (size_t) r_size_row_ref, il);
983
+ return false;
984
+ }
985
+
986
+ if (cell_count) {
987
+ // Read and set the keys for the whole cell range
988
+ lm_ggml_backend_tensor_set(r_l[il], io.read(cell_count * r_size_row), head * r_size_row, cell_count * r_size_row);
989
+ }
990
+ }
991
+
992
+ if (!s_trans) {
993
+ for (uint32_t il = 0; il < n_layer; ++il) {
994
+ // skip null layers
995
+ if (s_l[il] == nullptr) continue;
996
+
997
+ // Read type of value
998
+ int32_t s_type_i_ref;
999
+ io.read_to(&s_type_i_ref, sizeof(s_type_i_ref));
1000
+ const int32_t s_type_i = (int32_t)s_l[il]->type;
1001
+
1002
+ if (s_type_i != s_type_i_ref) {
1003
+ LLAMA_LOG_ERROR("%s: mismatched s type (%d != %d, layer %d)\n", __func__, s_type_i, s_type_i_ref, il);
1004
+ return false;
1005
+ }
1006
+
1007
+ // Read row size of value
1008
+ uint64_t s_size_row_ref;
1009
+ io.read_to(&s_size_row_ref, sizeof(s_size_row_ref));
1010
+ const size_t s_size_row = lm_ggml_row_size(s_l[il]->type, hparams.n_embd_s());
1011
+ if (s_size_row != s_size_row_ref) {
1012
+ LLAMA_LOG_ERROR("%s: mismatched s row size (%zu != %zu, layer %d)\n", __func__, s_size_row, (size_t) s_size_row_ref, il);
1013
+ return false;
1014
+ }
1015
+
1016
+ if (cell_count) {
1017
+ // Read and set the values for the whole cell range
1018
+ lm_ggml_backend_tensor_set(s_l[il], io.read(cell_count * s_size_row), head * s_size_row, cell_count * s_size_row);
1019
+ }
1020
+ }
1021
+ } else {
1022
+ // For each layer, read the values for each cell (transposed)
1023
+ for (uint32_t il = 0; il < n_layer; ++il) {
1024
+ // skip null layers
1025
+ if (s_l[il] == nullptr) continue;
1026
+
1027
+ const uint32_t n_embd_s = hparams.n_embd_s();
1028
+
1029
+ // Read type of value
1030
+ int32_t s_type_i_ref;
1031
+ io.read_to(&s_type_i_ref, sizeof(s_type_i_ref));
1032
+ const int32_t s_type_i = (int32_t)s_l[il]->type;
1033
+ if (s_type_i != s_type_i_ref) {
1034
+ LLAMA_LOG_ERROR("%s: mismatched s type (%d != %d, layer %d)\n", __func__, s_type_i, s_type_i_ref, il);
1035
+ return false;
1036
+ }
1037
+
1038
+ // Read element size of value
1039
+ uint32_t s_size_el_ref;
1040
+ io.read_to(&s_size_el_ref, sizeof(s_size_el_ref));
1041
+ const size_t s_size_el = lm_ggml_type_size(s_l[il]->type);
1042
+ if (s_size_el != s_size_el_ref) {
1043
+ LLAMA_LOG_ERROR("%s: mismatched s element size (%zu != %zu, layer %d)\n", __func__, s_size_el, (size_t) s_size_el_ref, il);
1044
+ return false;
1045
+ }
1046
+
1047
+ // Read state embedding size
1048
+ uint32_t n_embd_s_ref;
1049
+ io.read_to(&n_embd_s_ref, sizeof(n_embd_s_ref));
1050
+ if (n_embd_s != n_embd_s_ref) {
1051
+ LLAMA_LOG_ERROR("%s: mismatched s embedding size (%u != %u, layer %d)\n", __func__, n_embd_s, n_embd_s_ref, il);
1052
+ return false;
1053
+ }
1054
+
1055
+ if (cell_count) {
1056
+ // For each row in the transposed matrix, read the values for the whole cell range
1057
+ for (uint32_t j = 0; j < n_embd_s; ++j) {
1058
+ const size_t dst_offset = (head + j * size) * s_size_el;
1059
+ lm_ggml_backend_tensor_set(s_l[il], io.read(cell_count * s_size_el), dst_offset, cell_count * s_size_el);
1060
+ }
1061
+ }
1062
+ }
1063
+ }
1064
+
1065
+ return true;
1066
+ }
1067
+
1068
+ //
1069
+ // llama_memory_recurrent_context
1070
+ //
1071
+
1072
+ llama_memory_recurrent_context::llama_memory_recurrent_context(llama_memory_status status) : status(status) {}
1073
+
1074
+ llama_memory_recurrent_context::llama_memory_recurrent_context(
1075
+ llama_memory_recurrent * mem) : status(LLAMA_MEMORY_STATUS_SUCCESS), mem(mem), is_full(true) {
1076
+ }
1077
+
1078
+ llama_memory_recurrent_context::llama_memory_recurrent_context(
1079
+ llama_memory_recurrent * mem,
1080
+ std::vector<llama_ubatch> ubatches) : status(LLAMA_MEMORY_STATUS_SUCCESS), mem(mem), ubatches(std::move(ubatches)) {}
1081
+
1082
+ llama_memory_recurrent_context::~llama_memory_recurrent_context() = default;
1083
+
1084
+ bool llama_memory_recurrent_context::next() {
1085
+ assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
1086
+
1087
+ if (++i_next >= ubatches.size()) {
1088
+ return false;
1089
+ }
1090
+
1091
+ return true;
1092
+ }
1093
+
1094
+ bool llama_memory_recurrent_context::apply() {
1095
+ assert(!llama_memory_status_is_fail(status));
1096
+
1097
+ // no ubatches -> this is an update
1098
+ if (ubatches.empty()) {
1099
+ // recurrent cache never performs updates
1100
+ assert(status == LLAMA_MEMORY_STATUS_NO_UPDATE);
1101
+
1102
+ return true;
1103
+ }
1104
+
1105
+ mem->find_slot(ubatches[i_next]);
1106
+
1107
+ return true;
1108
+ }
1109
+
1110
+ llama_memory_status llama_memory_recurrent_context::get_status() const {
1111
+ return status;
1112
+ }
1113
+
1114
+ const llama_ubatch & llama_memory_recurrent_context::get_ubatch() const {
1115
+ assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
1116
+
1117
+ return ubatches[i_next];
1118
+ }
1119
+
1120
+ uint32_t llama_memory_recurrent_context::get_n_rs() const {
1121
+ return is_full ? mem->size : mem->n;
1122
+ }
1123
+
1124
+ uint32_t llama_memory_recurrent_context::get_head() const {
1125
+ return is_full ? 0 : mem->head;
1126
+ }
1127
+
1128
+ int32_t llama_memory_recurrent_context::get_rs_z() const {
1129
+ return is_full ? 0 : mem->rs_z;
1130
+ }
1131
+
1132
+ uint32_t llama_memory_recurrent_context::get_size() const {
1133
+ return mem->size;
1134
+ }
1135
+
1136
+ lm_ggml_tensor * llama_memory_recurrent_context::get_r_l(int32_t il) const {
1137
+ return mem->r_l[il];
1138
+ }
1139
+
1140
+ lm_ggml_tensor * llama_memory_recurrent_context::get_s_l(int32_t il) const {
1141
+ return mem->s_l[il];
1142
+ }
1143
+
1144
+ int32_t llama_memory_recurrent_context::s_copy(int i) const {
1145
+ return mem->cells[i + mem->head].src0;
1146
+ }