local-llm-rn 1.0.0

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 (626) hide show
  1. package/cpp/CMakeLists.txt +285 -0
  2. package/cpp/common/CMakeLists.txt +149 -0
  3. package/cpp/common/arg.cpp +3799 -0
  4. package/cpp/common/arg.h +131 -0
  5. package/cpp/common/base64.hpp +392 -0
  6. package/cpp/common/build-info.cpp.in +4 -0
  7. package/cpp/common/chat-parser-xml-toolcall.cpp +879 -0
  8. package/cpp/common/chat-parser-xml-toolcall.h +45 -0
  9. package/cpp/common/chat-parser.cpp +1649 -0
  10. package/cpp/common/chat-parser.h +133 -0
  11. package/cpp/common/chat-peg-parser.cpp +124 -0
  12. package/cpp/common/chat-peg-parser.h +105 -0
  13. package/cpp/common/chat.cpp +3355 -0
  14. package/cpp/common/chat.h +252 -0
  15. package/cpp/common/common.cpp +1824 -0
  16. package/cpp/common/common.h +930 -0
  17. package/cpp/common/console.cpp +1137 -0
  18. package/cpp/common/console.h +41 -0
  19. package/cpp/common/debug.cpp +167 -0
  20. package/cpp/common/debug.h +43 -0
  21. package/cpp/common/download.cpp +792 -0
  22. package/cpp/common/download.h +84 -0
  23. package/cpp/common/http.h +84 -0
  24. package/cpp/common/jinja/README.md +88 -0
  25. package/cpp/common/jinja/caps.cpp +285 -0
  26. package/cpp/common/jinja/caps.h +30 -0
  27. package/cpp/common/jinja/lexer.cpp +341 -0
  28. package/cpp/common/jinja/lexer.h +157 -0
  29. package/cpp/common/jinja/parser.cpp +591 -0
  30. package/cpp/common/jinja/parser.h +21 -0
  31. package/cpp/common/jinja/runtime.cpp +867 -0
  32. package/cpp/common/jinja/runtime.h +638 -0
  33. package/cpp/common/jinja/string.cpp +213 -0
  34. package/cpp/common/jinja/string.h +61 -0
  35. package/cpp/common/jinja/utils.h +149 -0
  36. package/cpp/common/jinja/value.cpp +1393 -0
  37. package/cpp/common/jinja/value.h +756 -0
  38. package/cpp/common/json-partial.cpp +324 -0
  39. package/cpp/common/json-partial.h +39 -0
  40. package/cpp/common/json-schema-to-grammar.cpp +1153 -0
  41. package/cpp/common/json-schema-to-grammar.h +43 -0
  42. package/cpp/common/llguidance.cpp +258 -0
  43. package/cpp/common/log.cpp +446 -0
  44. package/cpp/common/log.h +119 -0
  45. package/cpp/common/ngram-cache.cpp +285 -0
  46. package/cpp/common/ngram-cache.h +101 -0
  47. package/cpp/common/ngram-map.cpp +530 -0
  48. package/cpp/common/ngram-map.h +115 -0
  49. package/cpp/common/ngram-mod.cpp +60 -0
  50. package/cpp/common/ngram-mod.h +38 -0
  51. package/cpp/common/peg-parser.cpp +1712 -0
  52. package/cpp/common/peg-parser.h +459 -0
  53. package/cpp/common/preset.cpp +483 -0
  54. package/cpp/common/preset.h +83 -0
  55. package/cpp/common/regex-partial.cpp +204 -0
  56. package/cpp/common/regex-partial.h +56 -0
  57. package/cpp/common/sampling.cpp +745 -0
  58. package/cpp/common/sampling.h +119 -0
  59. package/cpp/common/speculative.cpp +1074 -0
  60. package/cpp/common/speculative.h +41 -0
  61. package/cpp/common/unicode.cpp +64 -0
  62. package/cpp/common/unicode.h +22 -0
  63. package/cpp/ggml/CMakeLists.txt +494 -0
  64. package/cpp/ggml/cmake/GitVars.cmake +22 -0
  65. package/cpp/ggml/cmake/common.cmake +50 -0
  66. package/cpp/ggml/cmake/ggml-config.cmake.in +191 -0
  67. package/cpp/ggml/include/ggml-alloc.h +85 -0
  68. package/cpp/ggml/include/ggml-backend.h +373 -0
  69. package/cpp/ggml/include/ggml-blas.h +25 -0
  70. package/cpp/ggml/include/ggml-cann.h +123 -0
  71. package/cpp/ggml/include/ggml-cpp.h +39 -0
  72. package/cpp/ggml/include/ggml-cpu.h +151 -0
  73. package/cpp/ggml/include/ggml-cuda.h +47 -0
  74. package/cpp/ggml/include/ggml-hexagon.h +19 -0
  75. package/cpp/ggml/include/ggml-metal.h +61 -0
  76. package/cpp/ggml/include/ggml-opencl.h +26 -0
  77. package/cpp/ggml/include/ggml-opt.h +256 -0
  78. package/cpp/ggml/include/ggml-rpc.h +30 -0
  79. package/cpp/ggml/include/ggml-sycl.h +49 -0
  80. package/cpp/ggml/include/ggml-virtgpu.h +14 -0
  81. package/cpp/ggml/include/ggml-vulkan.h +29 -0
  82. package/cpp/ggml/include/ggml-webgpu.h +19 -0
  83. package/cpp/ggml/include/ggml-zdnn.h +17 -0
  84. package/cpp/ggml/include/ggml-zendnn.h +22 -0
  85. package/cpp/ggml/include/ggml.h +2753 -0
  86. package/cpp/ggml/include/gguf.h +204 -0
  87. package/cpp/ggml/src/CMakeLists.txt +492 -0
  88. package/cpp/ggml/src/ggml-alloc.c +1244 -0
  89. package/cpp/ggml/src/ggml-backend-dl.cpp +48 -0
  90. package/cpp/ggml/src/ggml-backend-dl.h +45 -0
  91. package/cpp/ggml/src/ggml-backend-impl.h +255 -0
  92. package/cpp/ggml/src/ggml-backend-reg.cpp +566 -0
  93. package/cpp/ggml/src/ggml-backend.cpp +2270 -0
  94. package/cpp/ggml/src/ggml-blas/CMakeLists.txt +101 -0
  95. package/cpp/ggml/src/ggml-blas/ggml-blas.cpp +518 -0
  96. package/cpp/ggml/src/ggml-common.h +1878 -0
  97. package/cpp/ggml/src/ggml-cpu/CMakeLists.txt +691 -0
  98. package/cpp/ggml/src/ggml-cpu/amx/amx.cpp +247 -0
  99. package/cpp/ggml/src/ggml-cpu/amx/amx.h +8 -0
  100. package/cpp/ggml/src/ggml-cpu/amx/common.h +91 -0
  101. package/cpp/ggml/src/ggml-cpu/amx/mmq.cpp +2512 -0
  102. package/cpp/ggml/src/ggml-cpu/amx/mmq.h +10 -0
  103. package/cpp/ggml/src/ggml-cpu/arch/arm/cpu-feats.cpp +98 -0
  104. package/cpp/ggml/src/ggml-cpu/arch/arm/quants.c +4052 -0
  105. package/cpp/ggml/src/ggml-cpu/arch/arm/repack.cpp +4935 -0
  106. package/cpp/ggml/src/ggml-cpu/arch/loongarch/quants.c +2159 -0
  107. package/cpp/ggml/src/ggml-cpu/arch/powerpc/cpu-feats.cpp +82 -0
  108. package/cpp/ggml/src/ggml-cpu/arch/powerpc/quants.c +2305 -0
  109. package/cpp/ggml/src/ggml-cpu/arch/riscv/cpu-feats.cpp +38 -0
  110. package/cpp/ggml/src/ggml-cpu/arch/riscv/quants.c +2726 -0
  111. package/cpp/ggml/src/ggml-cpu/arch/riscv/repack.cpp +342 -0
  112. package/cpp/ggml/src/ggml-cpu/arch/s390/cpu-feats.cpp +50 -0
  113. package/cpp/ggml/src/ggml-cpu/arch/s390/quants.c +1468 -0
  114. package/cpp/ggml/src/ggml-cpu/arch/wasm/quants.c +1221 -0
  115. package/cpp/ggml/src/ggml-cpu/arch/x86/cpu-feats.cpp +327 -0
  116. package/cpp/ggml/src/ggml-cpu/arch/x86/quants.c +3820 -0
  117. package/cpp/ggml/src/ggml-cpu/arch/x86/repack.cpp +6307 -0
  118. package/cpp/ggml/src/ggml-cpu/arch-fallback.h +313 -0
  119. package/cpp/ggml/src/ggml-cpu/binary-ops.cpp +154 -0
  120. package/cpp/ggml/src/ggml-cpu/binary-ops.h +16 -0
  121. package/cpp/ggml/src/ggml-cpu/cmake/FindSIMD.cmake +100 -0
  122. package/cpp/ggml/src/ggml-cpu/common.h +95 -0
  123. package/cpp/ggml/src/ggml-cpu/ggml-cpu-impl.h +529 -0
  124. package/cpp/ggml/src/ggml-cpu/ggml-cpu.c +3734 -0
  125. package/cpp/ggml/src/ggml-cpu/ggml-cpu.cpp +701 -0
  126. package/cpp/ggml/src/ggml-cpu/hbm.cpp +55 -0
  127. package/cpp/ggml/src/ggml-cpu/hbm.h +8 -0
  128. package/cpp/ggml/src/ggml-cpu/kleidiai/kernels.cpp +938 -0
  129. package/cpp/ggml/src/ggml-cpu/kleidiai/kernels.h +90 -0
  130. package/cpp/ggml/src/ggml-cpu/kleidiai/kleidiai.cpp +798 -0
  131. package/cpp/ggml/src/ggml-cpu/kleidiai/kleidiai.h +17 -0
  132. package/cpp/ggml/src/ggml-cpu/llamafile/sgemm.cpp +4033 -0
  133. package/cpp/ggml/src/ggml-cpu/llamafile/sgemm.h +25 -0
  134. package/cpp/ggml/src/ggml-cpu/ops.cpp +10978 -0
  135. package/cpp/ggml/src/ggml-cpu/ops.h +116 -0
  136. package/cpp/ggml/src/ggml-cpu/quants.c +1193 -0
  137. package/cpp/ggml/src/ggml-cpu/quants.h +97 -0
  138. package/cpp/ggml/src/ggml-cpu/repack.cpp +3316 -0
  139. package/cpp/ggml/src/ggml-cpu/repack.h +173 -0
  140. package/cpp/ggml/src/ggml-cpu/simd-gemm.h +136 -0
  141. package/cpp/ggml/src/ggml-cpu/simd-mappings.h +1279 -0
  142. package/cpp/ggml/src/ggml-cpu/spacemit/ime.cpp +1025 -0
  143. package/cpp/ggml/src/ggml-cpu/spacemit/ime.h +13 -0
  144. package/cpp/ggml/src/ggml-cpu/spacemit/ime1_kernels.cpp +3196 -0
  145. package/cpp/ggml/src/ggml-cpu/spacemit/ime_kernels.h +26 -0
  146. package/cpp/ggml/src/ggml-cpu/traits.cpp +36 -0
  147. package/cpp/ggml/src/ggml-cpu/traits.h +38 -0
  148. package/cpp/ggml/src/ggml-cpu/unary-ops.cpp +337 -0
  149. package/cpp/ggml/src/ggml-cpu/unary-ops.h +35 -0
  150. package/cpp/ggml/src/ggml-cpu/vec.cpp +629 -0
  151. package/cpp/ggml/src/ggml-cpu/vec.h +1585 -0
  152. package/cpp/ggml/src/ggml-hexagon/CMakeLists.txt +117 -0
  153. package/cpp/ggml/src/ggml-hexagon/ggml-hexagon.cpp +3232 -0
  154. package/cpp/ggml/src/ggml-hexagon/htp/CMakeLists.txt +45 -0
  155. package/cpp/ggml/src/ggml-hexagon/htp/act-ops.c +815 -0
  156. package/cpp/ggml/src/ggml-hexagon/htp/argsort-ops.c +281 -0
  157. package/cpp/ggml/src/ggml-hexagon/htp/binary-ops.c +827 -0
  158. package/cpp/ggml/src/ggml-hexagon/htp/cmake-toolchain.cmake +157 -0
  159. package/cpp/ggml/src/ggml-hexagon/htp/cpy-ops.c +251 -0
  160. package/cpp/ggml/src/ggml-hexagon/htp/flash-attn-ops.c +666 -0
  161. package/cpp/ggml/src/ggml-hexagon/htp/get-rows-ops.c +111 -0
  162. package/cpp/ggml/src/ggml-hexagon/htp/hex-dma.c +63 -0
  163. package/cpp/ggml/src/ggml-hexagon/htp/hex-dma.h +182 -0
  164. package/cpp/ggml/src/ggml-hexagon/htp/hex-dump.h +77 -0
  165. package/cpp/ggml/src/ggml-hexagon/htp/hex-fastdiv.h +37 -0
  166. package/cpp/ggml/src/ggml-hexagon/htp/hex-utils.h +51 -0
  167. package/cpp/ggml/src/ggml-hexagon/htp/htp-ctx.h +35 -0
  168. package/cpp/ggml/src/ggml-hexagon/htp/htp-msg.h +154 -0
  169. package/cpp/ggml/src/ggml-hexagon/htp/htp-ops.h +65 -0
  170. package/cpp/ggml/src/ggml-hexagon/htp/htp_iface.idl +16 -0
  171. package/cpp/ggml/src/ggml-hexagon/htp/hvx-arith.h +470 -0
  172. package/cpp/ggml/src/ggml-hexagon/htp/hvx-base.h +173 -0
  173. package/cpp/ggml/src/ggml-hexagon/htp/hvx-copy.h +245 -0
  174. package/cpp/ggml/src/ggml-hexagon/htp/hvx-div.h +116 -0
  175. package/cpp/ggml/src/ggml-hexagon/htp/hvx-dump.h +129 -0
  176. package/cpp/ggml/src/ggml-hexagon/htp/hvx-exp.h +215 -0
  177. package/cpp/ggml/src/ggml-hexagon/htp/hvx-floor.h +100 -0
  178. package/cpp/ggml/src/ggml-hexagon/htp/hvx-inverse.h +176 -0
  179. package/cpp/ggml/src/ggml-hexagon/htp/hvx-reduce.h +266 -0
  180. package/cpp/ggml/src/ggml-hexagon/htp/hvx-scale.h +133 -0
  181. package/cpp/ggml/src/ggml-hexagon/htp/hvx-sigmoid.h +141 -0
  182. package/cpp/ggml/src/ggml-hexagon/htp/hvx-sqrt.h +126 -0
  183. package/cpp/ggml/src/ggml-hexagon/htp/hvx-types.h +36 -0
  184. package/cpp/ggml/src/ggml-hexagon/htp/hvx-utils.h +18 -0
  185. package/cpp/ggml/src/ggml-hexagon/htp/main.c +1150 -0
  186. package/cpp/ggml/src/ggml-hexagon/htp/matmul-ops.c +2595 -0
  187. package/cpp/ggml/src/ggml-hexagon/htp/rope-ops.c +498 -0
  188. package/cpp/ggml/src/ggml-hexagon/htp/set-rows-ops.c +167 -0
  189. package/cpp/ggml/src/ggml-hexagon/htp/softmax-ops.c +421 -0
  190. package/cpp/ggml/src/ggml-hexagon/htp/sum-rows-ops.c +130 -0
  191. package/cpp/ggml/src/ggml-hexagon/htp/unary-ops.c +384 -0
  192. package/cpp/ggml/src/ggml-hexagon/htp/worker-pool.c +293 -0
  193. package/cpp/ggml/src/ggml-hexagon/htp/worker-pool.h +57 -0
  194. package/cpp/ggml/src/ggml-hexagon/htp-drv.cpp +418 -0
  195. package/cpp/ggml/src/ggml-hexagon/htp-drv.h +121 -0
  196. package/cpp/ggml/src/ggml-hexagon/libdl.h +79 -0
  197. package/cpp/ggml/src/ggml-hexagon/libggml-htp.inf +38 -0
  198. package/cpp/ggml/src/ggml-hexagon/op-desc.h +153 -0
  199. package/cpp/ggml/src/ggml-impl.h +724 -0
  200. package/cpp/ggml/src/ggml-metal/CMakeLists.txt +124 -0
  201. package/cpp/ggml/src/ggml-metal/ggml-metal-common.cpp +457 -0
  202. package/cpp/ggml/src/ggml-metal/ggml-metal-common.h +52 -0
  203. package/cpp/ggml/src/ggml-metal/ggml-metal-context.h +41 -0
  204. package/cpp/ggml/src/ggml-metal/ggml-metal-context.m +702 -0
  205. package/cpp/ggml/src/ggml-metal/ggml-metal-device.cpp +1890 -0
  206. package/cpp/ggml/src/ggml-metal/ggml-metal-device.h +290 -0
  207. package/cpp/ggml/src/ggml-metal/ggml-metal-device.m +1749 -0
  208. package/cpp/ggml/src/ggml-metal/ggml-metal-impl.h +1054 -0
  209. package/cpp/ggml/src/ggml-metal/ggml-metal-ops.cpp +4370 -0
  210. package/cpp/ggml/src/ggml-metal/ggml-metal-ops.h +94 -0
  211. package/cpp/ggml/src/ggml-metal/ggml-metal.cpp +937 -0
  212. package/cpp/ggml/src/ggml-metal/ggml-metal.metal +9819 -0
  213. package/cpp/ggml/src/ggml-musa/CMakeLists.txt +125 -0
  214. package/cpp/ggml/src/ggml-musa/mudnn.cu +112 -0
  215. package/cpp/ggml/src/ggml-musa/mudnn.cuh +12 -0
  216. package/cpp/ggml/src/ggml-opencl/CMakeLists.txt +150 -0
  217. package/cpp/ggml/src/ggml-opencl/ggml-opencl.cpp +11553 -0
  218. package/cpp/ggml/src/ggml-opencl/kernels/add.cl +190 -0
  219. package/cpp/ggml/src/ggml-opencl/kernels/add_id.cl +42 -0
  220. package/cpp/ggml/src/ggml-opencl/kernels/argsort.cl +86 -0
  221. package/cpp/ggml/src/ggml-opencl/kernels/clamp.cl +20 -0
  222. package/cpp/ggml/src/ggml-opencl/kernels/concat.cl +51 -0
  223. package/cpp/ggml/src/ggml-opencl/kernels/conv2d.cl +185 -0
  224. package/cpp/ggml/src/ggml-opencl/kernels/conv2d_f16_f32.cl +176 -0
  225. package/cpp/ggml/src/ggml-opencl/kernels/cpy.cl +184 -0
  226. package/cpp/ggml/src/ggml-opencl/kernels/cvt.cl +417 -0
  227. package/cpp/ggml/src/ggml-opencl/kernels/diag_mask_inf.cl +58 -0
  228. package/cpp/ggml/src/ggml-opencl/kernels/div.cl +138 -0
  229. package/cpp/ggml/src/ggml-opencl/kernels/embed_kernel.py +26 -0
  230. package/cpp/ggml/src/ggml-opencl/kernels/expm1.cl +113 -0
  231. package/cpp/ggml/src/ggml-opencl/kernels/fill.cl +17 -0
  232. package/cpp/ggml/src/ggml-opencl/kernels/flash_attn_f16.cl +370 -0
  233. package/cpp/ggml/src/ggml-opencl/kernels/flash_attn_f32.cl +371 -0
  234. package/cpp/ggml/src/ggml-opencl/kernels/flash_attn_f32_f16.cl +373 -0
  235. package/cpp/ggml/src/ggml-opencl/kernels/gelu.cl +89 -0
  236. package/cpp/ggml/src/ggml-opencl/kernels/gemm_moe_mxfp4_f32.cl +162 -0
  237. package/cpp/ggml/src/ggml-opencl/kernels/gemv_moe_mxfp4_f32.cl +156 -0
  238. package/cpp/ggml/src/ggml-opencl/kernels/gemv_noshuffle.cl +268 -0
  239. package/cpp/ggml/src/ggml-opencl/kernels/gemv_noshuffle_general.cl +274 -0
  240. package/cpp/ggml/src/ggml-opencl/kernels/gemv_noshuffle_general_q8_0_f32.cl +195 -0
  241. package/cpp/ggml/src/ggml-opencl/kernels/get_rows.cl +187 -0
  242. package/cpp/ggml/src/ggml-opencl/kernels/glu.cl +378 -0
  243. package/cpp/ggml/src/ggml-opencl/kernels/group_norm.cl +121 -0
  244. package/cpp/ggml/src/ggml-opencl/kernels/im2col_f16.cl +57 -0
  245. package/cpp/ggml/src/ggml-opencl/kernels/im2col_f32.cl +57 -0
  246. package/cpp/ggml/src/ggml-opencl/kernels/mean.cl +140 -0
  247. package/cpp/ggml/src/ggml-opencl/kernels/mul.cl +152 -0
  248. package/cpp/ggml/src/ggml-opencl/kernels/mul_mat_Ab_Bi_8x4.cl +139 -0
  249. package/cpp/ggml/src/ggml-opencl/kernels/mul_mat_f16_f32.cl +130 -0
  250. package/cpp/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_kqv.cl +273 -0
  251. package/cpp/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_l4_lm.cl +146 -0
  252. package/cpp/ggml/src/ggml-opencl/kernels/mul_mm_f32_f32_l4_lm.cl +147 -0
  253. package/cpp/ggml/src/ggml-opencl/kernels/mul_mm_q4_0_f32_l4_lm.cl +163 -0
  254. package/cpp/ggml/src/ggml-opencl/kernels/mul_mm_q4_1_f32_l4_lm.cl +165 -0
  255. package/cpp/ggml/src/ggml-opencl/kernels/mul_mm_q6_k_f32_l4_lm.cl +158 -0
  256. package/cpp/ggml/src/ggml-opencl/kernels/mul_mm_q8_0_f32_8x4.cl +129 -0
  257. package/cpp/ggml/src/ggml-opencl/kernels/mul_mm_q8_0_f32_l4_lm.cl +154 -0
  258. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_f16_f16.cl +118 -0
  259. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_f16_f32.cl +118 -0
  260. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_f16_f32_1row.cl +94 -0
  261. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_f16_f32_l4.cl +84 -0
  262. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_f32_f32.cl +118 -0
  263. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_id_mxfp4_f32.cl +189 -0
  264. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_id_mxfp4_f32_flat.cl +176 -0
  265. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_id_q4_0_f32_8x_flat.cl +283 -0
  266. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_id_q8_0_f32.cl +140 -0
  267. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_id_q8_0_f32_flat.cl +222 -0
  268. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_mxfp4_f32.cl +144 -0
  269. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_mxfp4_f32_flat.cl +167 -0
  270. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_q4_0_f32.cl +192 -0
  271. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_q4_0_f32_1d_16x_flat.cl +307 -0
  272. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_q4_0_f32_1d_8x_flat.cl +265 -0
  273. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_q4_0_f32_8x_flat.cl +272 -0
  274. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_q4_0_f32_v.cl +254 -0
  275. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_q4_1_f32.cl +219 -0
  276. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_q4_1_f32_flat.cl +229 -0
  277. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_q4_k_f32.cl +180 -0
  278. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_q6_k_f32.cl +194 -0
  279. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_q6_k_f32_flat.cl +194 -0
  280. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_q8_0_f32.cl +125 -0
  281. package/cpp/ggml/src/ggml-opencl/kernels/mul_mv_q8_0_f32_flat.cl +202 -0
  282. package/cpp/ggml/src/ggml-opencl/kernels/norm.cl +161 -0
  283. package/cpp/ggml/src/ggml-opencl/kernels/pad.cl +39 -0
  284. package/cpp/ggml/src/ggml-opencl/kernels/relu.cl +16 -0
  285. package/cpp/ggml/src/ggml-opencl/kernels/repeat.cl +38 -0
  286. package/cpp/ggml/src/ggml-opencl/kernels/rms_norm.cl +190 -0
  287. package/cpp/ggml/src/ggml-opencl/kernels/rope.cl +747 -0
  288. package/cpp/ggml/src/ggml-opencl/kernels/scale.cl +27 -0
  289. package/cpp/ggml/src/ggml-opencl/kernels/set_rows.cl +208 -0
  290. package/cpp/ggml/src/ggml-opencl/kernels/sigmoid.cl +29 -0
  291. package/cpp/ggml/src/ggml-opencl/kernels/silu.cl +30 -0
  292. package/cpp/ggml/src/ggml-opencl/kernels/softmax_4_f16.cl +108 -0
  293. package/cpp/ggml/src/ggml-opencl/kernels/softmax_4_f32.cl +108 -0
  294. package/cpp/ggml/src/ggml-opencl/kernels/softmax_f16.cl +107 -0
  295. package/cpp/ggml/src/ggml-opencl/kernels/softmax_f32.cl +107 -0
  296. package/cpp/ggml/src/ggml-opencl/kernels/softplus.cl +116 -0
  297. package/cpp/ggml/src/ggml-opencl/kernels/solve_tri.cl +51 -0
  298. package/cpp/ggml/src/ggml-opencl/kernels/sqr.cl +53 -0
  299. package/cpp/ggml/src/ggml-opencl/kernels/sqrt.cl +53 -0
  300. package/cpp/ggml/src/ggml-opencl/kernels/ssm_conv.cl +77 -0
  301. package/cpp/ggml/src/ggml-opencl/kernels/sub.cl +138 -0
  302. package/cpp/ggml/src/ggml-opencl/kernels/sum_rows.cl +140 -0
  303. package/cpp/ggml/src/ggml-opencl/kernels/tanh.cl +109 -0
  304. package/cpp/ggml/src/ggml-opencl/kernels/transpose.cl +117 -0
  305. package/cpp/ggml/src/ggml-opencl/kernels/tri.cl +32 -0
  306. package/cpp/ggml/src/ggml-opencl/kernels/tsembd.cl +48 -0
  307. package/cpp/ggml/src/ggml-opencl/kernels/upscale.cl +120 -0
  308. package/cpp/ggml/src/ggml-opt.cpp +1093 -0
  309. package/cpp/ggml/src/ggml-quants.c +5325 -0
  310. package/cpp/ggml/src/ggml-quants.h +106 -0
  311. package/cpp/ggml/src/ggml-rpc/CMakeLists.txt +9 -0
  312. package/cpp/ggml/src/ggml-rpc/ggml-rpc.cpp +2118 -0
  313. package/cpp/ggml/src/ggml-threading.cpp +12 -0
  314. package/cpp/ggml/src/ggml-threading.h +14 -0
  315. package/cpp/ggml/src/ggml-virtgpu/CMakeLists.txt +70 -0
  316. package/cpp/ggml/src/ggml-virtgpu/apir_cs_ggml-rpc-front.cpp +87 -0
  317. package/cpp/ggml/src/ggml-virtgpu/backend/CMakeLists.txt +21 -0
  318. package/cpp/ggml/src/ggml-virtgpu/backend/apir_cs_ggml-rpc-back.cpp +115 -0
  319. package/cpp/ggml/src/ggml-virtgpu/backend/backend-convert.h +13 -0
  320. package/cpp/ggml/src/ggml-virtgpu/backend/backend-dispatched-backend.cpp +102 -0
  321. package/cpp/ggml/src/ggml-virtgpu/backend/backend-dispatched-buffer-type.cpp +105 -0
  322. package/cpp/ggml/src/ggml-virtgpu/backend/backend-dispatched-buffer.cpp +179 -0
  323. package/cpp/ggml/src/ggml-virtgpu/backend/backend-dispatched-device.cpp +148 -0
  324. package/cpp/ggml/src/ggml-virtgpu/backend/backend-dispatched.cpp +51 -0
  325. package/cpp/ggml/src/ggml-virtgpu/backend/backend-dispatched.gen.h +73 -0
  326. package/cpp/ggml/src/ggml-virtgpu/backend/backend-dispatched.h +27 -0
  327. package/cpp/ggml/src/ggml-virtgpu/backend/backend-virgl-apir.h +32 -0
  328. package/cpp/ggml/src/ggml-virtgpu/backend/backend.cpp +144 -0
  329. package/cpp/ggml/src/ggml-virtgpu/backend/shared/api_remoting.h +95 -0
  330. package/cpp/ggml/src/ggml-virtgpu/backend/shared/apir_backend.gen.h +94 -0
  331. package/cpp/ggml/src/ggml-virtgpu/backend/shared/apir_backend.h +50 -0
  332. package/cpp/ggml/src/ggml-virtgpu/backend/shared/apir_cs.h +378 -0
  333. package/cpp/ggml/src/ggml-virtgpu/backend/shared/apir_cs_ggml.h +232 -0
  334. package/cpp/ggml/src/ggml-virtgpu/backend/shared/apir_cs_rpc.h +58 -0
  335. package/cpp/ggml/src/ggml-virtgpu/ggml-backend-buffer-type.cpp +81 -0
  336. package/cpp/ggml/src/ggml-virtgpu/ggml-backend-buffer.cpp +119 -0
  337. package/cpp/ggml/src/ggml-virtgpu/ggml-backend-device.cpp +158 -0
  338. package/cpp/ggml/src/ggml-virtgpu/ggml-backend-reg.cpp +213 -0
  339. package/cpp/ggml/src/ggml-virtgpu/ggml-backend.cpp +69 -0
  340. package/cpp/ggml/src/ggml-virtgpu/ggml-remoting.h +71 -0
  341. package/cpp/ggml/src/ggml-virtgpu/ggmlremoting_functions.yaml +166 -0
  342. package/cpp/ggml/src/ggml-virtgpu/include/apir_hw.h +9 -0
  343. package/cpp/ggml/src/ggml-virtgpu/regenerate_remoting.py +333 -0
  344. package/cpp/ggml/src/ggml-virtgpu/virtgpu-apir.h +15 -0
  345. package/cpp/ggml/src/ggml-virtgpu/virtgpu-forward-backend.cpp +58 -0
  346. package/cpp/ggml/src/ggml-virtgpu/virtgpu-forward-buffer-type.cpp +110 -0
  347. package/cpp/ggml/src/ggml-virtgpu/virtgpu-forward-buffer.cpp +173 -0
  348. package/cpp/ggml/src/ggml-virtgpu/virtgpu-forward-device.cpp +192 -0
  349. package/cpp/ggml/src/ggml-virtgpu/virtgpu-forward-impl.h +36 -0
  350. package/cpp/ggml/src/ggml-virtgpu/virtgpu-forward.gen.h +53 -0
  351. package/cpp/ggml/src/ggml-virtgpu/virtgpu-shm.cpp +98 -0
  352. package/cpp/ggml/src/ggml-virtgpu/virtgpu-shm.h +23 -0
  353. package/cpp/ggml/src/ggml-virtgpu/virtgpu-utils.cpp +179 -0
  354. package/cpp/ggml/src/ggml-virtgpu/virtgpu-utils.h +86 -0
  355. package/cpp/ggml/src/ggml-virtgpu/virtgpu.cpp +544 -0
  356. package/cpp/ggml/src/ggml-virtgpu/virtgpu.h +117 -0
  357. package/cpp/ggml/src/ggml-webgpu/CMakeLists.txt +80 -0
  358. package/cpp/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp +1231 -0
  359. package/cpp/ggml/src/ggml-webgpu/ggml-webgpu.cpp +3150 -0
  360. package/cpp/ggml/src/ggml-webgpu/pre_wgsl.hpp +778 -0
  361. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/argmax.wgsl +72 -0
  362. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/argsort.wgsl +106 -0
  363. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/argsort_merge.wgsl +134 -0
  364. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/binary.wgsl +107 -0
  365. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/common_decls.tmpl +923 -0
  366. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/cpy.tmpl.wgsl +107 -0
  367. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/cumsum.wgsl +66 -0
  368. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/embed_wgsl.py +182 -0
  369. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/flash_attn.wgsl +636 -0
  370. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/get_rows.wgsl +668 -0
  371. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/glu.tmpl.wgsl +323 -0
  372. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/memset.wgsl +40 -0
  373. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat.wgsl +713 -0
  374. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_decls.tmpl +103 -0
  375. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_reg_tile.wgsl +138 -0
  376. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_subgroup_matrix.wgsl +188 -0
  377. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_vec.wgsl +194 -0
  378. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/pad.wgsl +86 -0
  379. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/rms_norm.wgsl +123 -0
  380. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/rope.tmpl.wgsl +295 -0
  381. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/scale.wgsl +63 -0
  382. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/set_rows.wgsl +109 -0
  383. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/soft_max.tmpl.wgsl +345 -0
  384. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/sum_rows.wgsl +55 -0
  385. package/cpp/ggml/src/ggml-webgpu/wgsl-shaders/unary.wgsl +193 -0
  386. package/cpp/ggml/src/ggml-zdnn/CMakeLists.txt +36 -0
  387. package/cpp/ggml/src/ggml-zdnn/common.hpp +59 -0
  388. package/cpp/ggml/src/ggml-zdnn/ggml-zdnn.cpp +633 -0
  389. package/cpp/ggml/src/ggml-zdnn/mmf.cpp +80 -0
  390. package/cpp/ggml/src/ggml-zdnn/mmf.hpp +12 -0
  391. package/cpp/ggml/src/ggml-zdnn/utils.cpp +79 -0
  392. package/cpp/ggml/src/ggml-zdnn/utils.hpp +19 -0
  393. package/cpp/ggml/src/ggml-zendnn/CMakeLists.txt +92 -0
  394. package/cpp/ggml/src/ggml-zendnn/ggml-zendnn.cpp +469 -0
  395. package/cpp/ggml/src/ggml.c +7669 -0
  396. package/cpp/ggml/src/ggml.cpp +26 -0
  397. package/cpp/ggml/src/gguf.cpp +1699 -0
  398. package/cpp/include/llama-cpp.h +32 -0
  399. package/cpp/include/llama.h +1568 -0
  400. package/cpp/mtmd/CMakeLists.txt +98 -0
  401. package/cpp/mtmd/README.md +63 -0
  402. package/cpp/mtmd/clip-graph.h +117 -0
  403. package/cpp/mtmd/clip-impl.h +586 -0
  404. package/cpp/mtmd/clip-model.h +390 -0
  405. package/cpp/mtmd/clip.cpp +4154 -0
  406. package/cpp/mtmd/clip.h +121 -0
  407. package/cpp/mtmd/deprecation-warning.cpp +22 -0
  408. package/cpp/mtmd/legacy-models/convert_image_encoder_to_gguf.py +412 -0
  409. package/cpp/mtmd/legacy-models/glmedge-convert-image-encoder-to-gguf.py +280 -0
  410. package/cpp/mtmd/legacy-models/glmedge-surgery.py +33 -0
  411. package/cpp/mtmd/legacy-models/llava_surgery.py +38 -0
  412. package/cpp/mtmd/legacy-models/llava_surgery_v2.py +180 -0
  413. package/cpp/mtmd/legacy-models/minicpmv-convert-image-encoder-to-gguf.py +892 -0
  414. package/cpp/mtmd/legacy-models/minicpmv-surgery.py +47 -0
  415. package/cpp/mtmd/models/cogvlm.cpp +98 -0
  416. package/cpp/mtmd/models/conformer.cpp +216 -0
  417. package/cpp/mtmd/models/glm4v.cpp +122 -0
  418. package/cpp/mtmd/models/internvl.cpp +69 -0
  419. package/cpp/mtmd/models/kimik25.cpp +101 -0
  420. package/cpp/mtmd/models/kimivl.cpp +63 -0
  421. package/cpp/mtmd/models/llama4.cpp +96 -0
  422. package/cpp/mtmd/models/llava.cpp +374 -0
  423. package/cpp/mtmd/models/minicpmv.cpp +114 -0
  424. package/cpp/mtmd/models/mobilenetv5.cpp +451 -0
  425. package/cpp/mtmd/models/models.h +128 -0
  426. package/cpp/mtmd/models/nemotron-v2-vl.cpp +35 -0
  427. package/cpp/mtmd/models/paddleocr.cpp +52 -0
  428. package/cpp/mtmd/models/pixtral.cpp +86 -0
  429. package/cpp/mtmd/models/qwen2vl.cpp +183 -0
  430. package/cpp/mtmd/models/qwen3vl.cpp +193 -0
  431. package/cpp/mtmd/models/siglip.cpp +86 -0
  432. package/cpp/mtmd/models/whisper-enc.cpp +115 -0
  433. package/cpp/mtmd/models/youtuvl.cpp +179 -0
  434. package/cpp/mtmd/mtmd-audio.cpp +730 -0
  435. package/cpp/mtmd/mtmd-audio.h +113 -0
  436. package/cpp/mtmd/mtmd-cli.cpp +437 -0
  437. package/cpp/mtmd/mtmd-helper.cpp +521 -0
  438. package/cpp/mtmd/mtmd-helper.h +96 -0
  439. package/cpp/mtmd/mtmd.cpp +1156 -0
  440. package/cpp/mtmd/mtmd.h +319 -0
  441. package/cpp/mtmd/requirements.txt +5 -0
  442. package/cpp/mtmd/test-1.jpeg +0 -0
  443. package/cpp/mtmd/test-2.mp3 +0 -0
  444. package/cpp/mtmd/tests.sh +192 -0
  445. package/cpp/src/CMakeLists.txt +169 -0
  446. package/cpp/src/llama-adapter.cpp +488 -0
  447. package/cpp/src/llama-adapter.h +89 -0
  448. package/cpp/src/llama-arch.cpp +2855 -0
  449. package/cpp/src/llama-arch.h +619 -0
  450. package/cpp/src/llama-batch.cpp +917 -0
  451. package/cpp/src/llama-batch.h +173 -0
  452. package/cpp/src/llama-chat.cpp +896 -0
  453. package/cpp/src/llama-chat.h +71 -0
  454. package/cpp/src/llama-context.cpp +3512 -0
  455. package/cpp/src/llama-context.h +359 -0
  456. package/cpp/src/llama-cparams.cpp +5 -0
  457. package/cpp/src/llama-cparams.h +44 -0
  458. package/cpp/src/llama-grammar.cpp +1464 -0
  459. package/cpp/src/llama-grammar.h +194 -0
  460. package/cpp/src/llama-graph.cpp +2685 -0
  461. package/cpp/src/llama-graph.h +1026 -0
  462. package/cpp/src/llama-hparams.cpp +234 -0
  463. package/cpp/src/llama-hparams.h +339 -0
  464. package/cpp/src/llama-impl.cpp +171 -0
  465. package/cpp/src/llama-impl.h +73 -0
  466. package/cpp/src/llama-io.cpp +15 -0
  467. package/cpp/src/llama-io.h +35 -0
  468. package/cpp/src/llama-kv-cache-iswa.cpp +330 -0
  469. package/cpp/src/llama-kv-cache-iswa.h +137 -0
  470. package/cpp/src/llama-kv-cache.cpp +2271 -0
  471. package/cpp/src/llama-kv-cache.h +388 -0
  472. package/cpp/src/llama-kv-cells.h +533 -0
  473. package/cpp/src/llama-memory-hybrid-iswa.cpp +275 -0
  474. package/cpp/src/llama-memory-hybrid-iswa.h +140 -0
  475. package/cpp/src/llama-memory-hybrid.cpp +268 -0
  476. package/cpp/src/llama-memory-hybrid.h +139 -0
  477. package/cpp/src/llama-memory-recurrent.cpp +1165 -0
  478. package/cpp/src/llama-memory-recurrent.h +182 -0
  479. package/cpp/src/llama-memory.cpp +59 -0
  480. package/cpp/src/llama-memory.h +122 -0
  481. package/cpp/src/llama-mmap.cpp +785 -0
  482. package/cpp/src/llama-mmap.h +92 -0
  483. package/cpp/src/llama-model-loader.cpp +1414 -0
  484. package/cpp/src/llama-model-loader.h +203 -0
  485. package/cpp/src/llama-model-saver.cpp +286 -0
  486. package/cpp/src/llama-model-saver.h +37 -0
  487. package/cpp/src/llama-model.cpp +9253 -0
  488. package/cpp/src/llama-model.h +576 -0
  489. package/cpp/src/llama-quant.cpp +1119 -0
  490. package/cpp/src/llama-quant.h +1 -0
  491. package/cpp/src/llama-sampler.cpp +3885 -0
  492. package/cpp/src/llama-sampler.h +42 -0
  493. package/cpp/src/llama-vocab.cpp +3970 -0
  494. package/cpp/src/llama-vocab.h +187 -0
  495. package/cpp/src/llama.cpp +1313 -0
  496. package/cpp/src/models/afmoe.cpp +191 -0
  497. package/cpp/src/models/apertus.cpp +125 -0
  498. package/cpp/src/models/arcee.cpp +135 -0
  499. package/cpp/src/models/arctic.cpp +138 -0
  500. package/cpp/src/models/arwkv7.cpp +86 -0
  501. package/cpp/src/models/baichuan.cpp +122 -0
  502. package/cpp/src/models/bailingmoe.cpp +144 -0
  503. package/cpp/src/models/bailingmoe2.cpp +135 -0
  504. package/cpp/src/models/bert.cpp +178 -0
  505. package/cpp/src/models/bitnet.cpp +160 -0
  506. package/cpp/src/models/bloom.cpp +101 -0
  507. package/cpp/src/models/chameleon.cpp +178 -0
  508. package/cpp/src/models/chatglm.cpp +132 -0
  509. package/cpp/src/models/codeshell.cpp +111 -0
  510. package/cpp/src/models/cogvlm.cpp +102 -0
  511. package/cpp/src/models/cohere2-iswa.cpp +134 -0
  512. package/cpp/src/models/command-r.cpp +122 -0
  513. package/cpp/src/models/dbrx.cpp +123 -0
  514. package/cpp/src/models/deci.cpp +135 -0
  515. package/cpp/src/models/deepseek.cpp +144 -0
  516. package/cpp/src/models/deepseek2.cpp +262 -0
  517. package/cpp/src/models/delta-net-base.cpp +376 -0
  518. package/cpp/src/models/dots1.cpp +134 -0
  519. package/cpp/src/models/dream.cpp +105 -0
  520. package/cpp/src/models/ernie4-5-moe.cpp +150 -0
  521. package/cpp/src/models/ernie4-5.cpp +110 -0
  522. package/cpp/src/models/eurobert.cpp +97 -0
  523. package/cpp/src/models/exaone-moe.cpp +146 -0
  524. package/cpp/src/models/exaone.cpp +114 -0
  525. package/cpp/src/models/exaone4.cpp +123 -0
  526. package/cpp/src/models/falcon-h1.cpp +111 -0
  527. package/cpp/src/models/falcon.cpp +120 -0
  528. package/cpp/src/models/gemma-embedding.cpp +116 -0
  529. package/cpp/src/models/gemma.cpp +112 -0
  530. package/cpp/src/models/gemma2-iswa.cpp +128 -0
  531. package/cpp/src/models/gemma3.cpp +155 -0
  532. package/cpp/src/models/gemma3n-iswa.cpp +384 -0
  533. package/cpp/src/models/glm4-moe.cpp +170 -0
  534. package/cpp/src/models/glm4.cpp +157 -0
  535. package/cpp/src/models/gpt2.cpp +105 -0
  536. package/cpp/src/models/gptneox.cpp +144 -0
  537. package/cpp/src/models/granite-hybrid.cpp +196 -0
  538. package/cpp/src/models/granite.cpp +211 -0
  539. package/cpp/src/models/grok.cpp +159 -0
  540. package/cpp/src/models/grovemoe.cpp +141 -0
  541. package/cpp/src/models/hunyuan-dense.cpp +132 -0
  542. package/cpp/src/models/hunyuan-moe.cpp +154 -0
  543. package/cpp/src/models/internlm2.cpp +120 -0
  544. package/cpp/src/models/jais.cpp +86 -0
  545. package/cpp/src/models/jais2.cpp +123 -0
  546. package/cpp/src/models/jamba.cpp +106 -0
  547. package/cpp/src/models/kimi-linear.cpp +392 -0
  548. package/cpp/src/models/lfm2.cpp +190 -0
  549. package/cpp/src/models/llada-moe.cpp +122 -0
  550. package/cpp/src/models/llada.cpp +99 -0
  551. package/cpp/src/models/llama-iswa.cpp +178 -0
  552. package/cpp/src/models/llama.cpp +168 -0
  553. package/cpp/src/models/maincoder.cpp +117 -0
  554. package/cpp/src/models/mamba-base.cpp +285 -0
  555. package/cpp/src/models/mamba.cpp +54 -0
  556. package/cpp/src/models/mimo2-iswa.cpp +123 -0
  557. package/cpp/src/models/minicpm3.cpp +200 -0
  558. package/cpp/src/models/minimax-m2.cpp +124 -0
  559. package/cpp/src/models/mistral3.cpp +160 -0
  560. package/cpp/src/models/models.h +684 -0
  561. package/cpp/src/models/modern-bert.cpp +109 -0
  562. package/cpp/src/models/mpt.cpp +126 -0
  563. package/cpp/src/models/nemotron-h.cpp +148 -0
  564. package/cpp/src/models/nemotron.cpp +122 -0
  565. package/cpp/src/models/neo-bert.cpp +104 -0
  566. package/cpp/src/models/olmo.cpp +121 -0
  567. package/cpp/src/models/olmo2.cpp +150 -0
  568. package/cpp/src/models/olmoe.cpp +124 -0
  569. package/cpp/src/models/openai-moe-iswa.cpp +127 -0
  570. package/cpp/src/models/openelm.cpp +124 -0
  571. package/cpp/src/models/orion.cpp +123 -0
  572. package/cpp/src/models/paddleocr.cpp +122 -0
  573. package/cpp/src/models/pangu-embedded.cpp +121 -0
  574. package/cpp/src/models/phi2.cpp +121 -0
  575. package/cpp/src/models/phi3.cpp +152 -0
  576. package/cpp/src/models/plamo.cpp +110 -0
  577. package/cpp/src/models/plamo2.cpp +318 -0
  578. package/cpp/src/models/plamo3.cpp +128 -0
  579. package/cpp/src/models/plm.cpp +169 -0
  580. package/cpp/src/models/qwen.cpp +108 -0
  581. package/cpp/src/models/qwen2.cpp +126 -0
  582. package/cpp/src/models/qwen2moe.cpp +151 -0
  583. package/cpp/src/models/qwen2vl.cpp +117 -0
  584. package/cpp/src/models/qwen3.cpp +117 -0
  585. package/cpp/src/models/qwen35.cpp +386 -0
  586. package/cpp/src/models/qwen35moe.cpp +420 -0
  587. package/cpp/src/models/qwen3moe.cpp +124 -0
  588. package/cpp/src/models/qwen3next.cpp +525 -0
  589. package/cpp/src/models/qwen3vl-moe.cpp +140 -0
  590. package/cpp/src/models/qwen3vl.cpp +132 -0
  591. package/cpp/src/models/refact.cpp +94 -0
  592. package/cpp/src/models/rnd1.cpp +126 -0
  593. package/cpp/src/models/rwkv6-base.cpp +164 -0
  594. package/cpp/src/models/rwkv6.cpp +94 -0
  595. package/cpp/src/models/rwkv6qwen2.cpp +86 -0
  596. package/cpp/src/models/rwkv7-base.cpp +137 -0
  597. package/cpp/src/models/rwkv7.cpp +90 -0
  598. package/cpp/src/models/seed-oss.cpp +124 -0
  599. package/cpp/src/models/smallthinker.cpp +126 -0
  600. package/cpp/src/models/smollm3.cpp +128 -0
  601. package/cpp/src/models/stablelm.cpp +146 -0
  602. package/cpp/src/models/starcoder.cpp +100 -0
  603. package/cpp/src/models/starcoder2.cpp +121 -0
  604. package/cpp/src/models/step35-iswa.cpp +168 -0
  605. package/cpp/src/models/t5-dec.cpp +166 -0
  606. package/cpp/src/models/t5-enc.cpp +96 -0
  607. package/cpp/src/models/wavtokenizer-dec.cpp +149 -0
  608. package/cpp/src/models/xverse.cpp +108 -0
  609. package/cpp/src/unicode-data.cpp +7034 -0
  610. package/cpp/src/unicode-data.h +20 -0
  611. package/cpp/src/unicode.cpp +1103 -0
  612. package/cpp/src/unicode.h +111 -0
  613. package/cpp/vendor/nlohmann/json.hpp +25526 -0
  614. package/cpp/vendor/nlohmann/json_fwd.hpp +187 -0
  615. package/cpp/vendor/stb/stb_image.h +7988 -0
  616. package/ios/LocalLLM-Bridging-Header.h +2 -0
  617. package/ios/LocalLLM.h +5 -0
  618. package/ios/LocalLLM.mm +1267 -0
  619. package/local-llm-rn.podspec +60 -0
  620. package/package.json +35 -0
  621. package/src/NativeLocalLLM.ts +73 -0
  622. package/src/device.ts +50 -0
  623. package/src/download-adapter.ts +17 -0
  624. package/src/index.ts +21 -0
  625. package/src/native-bridge.ts +142 -0
  626. package/src/rn-downloader.ts +37 -0
@@ -0,0 +1,1824 @@
1
+ #include "ggml.h"
2
+ #include "gguf.h"
3
+
4
+ #include "common.h"
5
+ #include "log.h"
6
+ #include "llama.h"
7
+ #include "sampling.h"
8
+ #include "unicode.h"
9
+
10
+ #include <algorithm>
11
+ #include <cinttypes>
12
+ #include <climits>
13
+ #include <cmath>
14
+ #include <chrono>
15
+ #include <cstdarg>
16
+ #include <cstring>
17
+ #include <ctime>
18
+ #include <filesystem>
19
+ #include <fstream>
20
+ #include <iostream>
21
+ #include <iterator>
22
+ #include <regex>
23
+ #include <sstream>
24
+ #include <string>
25
+ #include <thread>
26
+ #include <unordered_set>
27
+ #include <vector>
28
+
29
+ #if defined(__APPLE__) && defined(__MACH__)
30
+ #include <sys/types.h>
31
+ #include <sys/sysctl.h>
32
+ #endif
33
+
34
+ #if defined(_WIN32)
35
+ #define WIN32_LEAN_AND_MEAN
36
+ #ifndef NOMINMAX
37
+ # define NOMINMAX
38
+ #endif
39
+ #include <locale>
40
+ #include <windows.h>
41
+ #include <string.h>
42
+ #include <fcntl.h>
43
+ #include <io.h>
44
+ #else
45
+ #include <sys/ioctl.h>
46
+ #include <sys/stat.h>
47
+ #include <unistd.h>
48
+ #endif
49
+
50
+ #if defined(__linux__)
51
+ #include <sys/types.h>
52
+ #include <pwd.h>
53
+ #endif
54
+
55
+ #if defined(_MSC_VER)
56
+ #pragma warning(disable: 4244 4267) // possible loss of data
57
+ #endif
58
+
59
+ common_time_meas::common_time_meas(int64_t & t_acc, bool disable) : t_start_us(disable ? -1 : ggml_time_us()), t_acc(t_acc) {}
60
+
61
+ common_time_meas::~common_time_meas() {
62
+ if (t_start_us >= 0) {
63
+ t_acc += ggml_time_us() - t_start_us;
64
+ }
65
+ }
66
+
67
+ //
68
+ // CPU utils
69
+ //
70
+
71
+ int32_t cpu_get_num_physical_cores() {
72
+ #ifdef __linux__
73
+ // enumerate the set of thread siblings, num entries is num cores
74
+ std::unordered_set<std::string> siblings;
75
+ for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
76
+ std::ifstream thread_siblings("/sys/devices/system/cpu/cpu"
77
+ + std::to_string(cpu) + "/topology/thread_siblings");
78
+ if (!thread_siblings.is_open()) {
79
+ break; // no more cpus
80
+ }
81
+ std::string line;
82
+ if (std::getline(thread_siblings, line)) {
83
+ siblings.insert(line);
84
+ }
85
+ }
86
+ if (!siblings.empty()) {
87
+ return static_cast<int32_t>(siblings.size());
88
+ }
89
+ #elif defined(__APPLE__) && defined(__MACH__)
90
+ int32_t num_physical_cores;
91
+ size_t len = sizeof(num_physical_cores);
92
+ int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
93
+ if (result == 0) {
94
+ return num_physical_cores;
95
+ }
96
+ result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
97
+ if (result == 0) {
98
+ return num_physical_cores;
99
+ }
100
+ #elif defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
101
+ // TODO: windows + arm64 + mingw64
102
+ unsigned int n_threads_win = std::thread::hardware_concurrency();
103
+ unsigned int default_threads = n_threads_win > 0 ? (n_threads_win <= 4 ? n_threads_win : n_threads_win / 2) : 4;
104
+
105
+ DWORD buffer_size = 0;
106
+ if (!GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &buffer_size)) {
107
+ if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
108
+ return default_threads;
109
+ }
110
+ }
111
+
112
+ std::vector<char> buffer(buffer_size);
113
+ if (!GetLogicalProcessorInformationEx(RelationProcessorCore, reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data()), &buffer_size)) {
114
+ return default_threads;
115
+ }
116
+
117
+ int32_t num_physical_cores = 0;
118
+ PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data());
119
+ while (buffer_size > 0) {
120
+ if (info->Relationship == RelationProcessorCore) {
121
+ num_physical_cores += info->Processor.GroupCount;
122
+ }
123
+ buffer_size -= info->Size;
124
+ info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(reinterpret_cast<char*>(info) + info->Size);
125
+ }
126
+
127
+ return num_physical_cores > 0 ? num_physical_cores : default_threads;
128
+ #endif
129
+ unsigned int n_threads = std::thread::hardware_concurrency();
130
+ return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
131
+ }
132
+
133
+ #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
134
+ #include <pthread.h>
135
+
136
+ static void cpuid(unsigned leaf, unsigned subleaf,
137
+ unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) {
138
+ __asm__("movq\t%%rbx,%%rsi\n\t"
139
+ "cpuid\n\t"
140
+ "xchgq\t%%rbx,%%rsi"
141
+ : "=a"(*eax), "=S"(*ebx), "=c"(*ecx), "=d"(*edx)
142
+ : "0"(leaf), "2"(subleaf));
143
+ }
144
+
145
+ static int pin_cpu(int cpu) {
146
+ cpu_set_t mask;
147
+ CPU_ZERO(&mask);
148
+ CPU_SET(cpu, &mask);
149
+ return pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);
150
+ }
151
+
152
+ static bool is_hybrid_cpu(void) {
153
+ unsigned eax, ebx, ecx, edx;
154
+ cpuid(7, 0, &eax, &ebx, &ecx, &edx);
155
+ return !!(edx & (1u << 15));
156
+ }
157
+
158
+ static bool is_running_on_efficiency_core(void) {
159
+ unsigned eax, ebx, ecx, edx;
160
+ cpuid(0x1a, 0, &eax, &ebx, &ecx, &edx);
161
+ int intel_atom = 0x20;
162
+ int core_type = (eax & 0xff000000u) >> 24;
163
+ return core_type == intel_atom;
164
+ }
165
+
166
+ static int cpu_count_math_cpus(int n_cpu) {
167
+ int result = 0;
168
+ for (int cpu = 0; cpu < n_cpu; ++cpu) {
169
+ if (pin_cpu(cpu)) {
170
+ return -1;
171
+ }
172
+ if (is_running_on_efficiency_core()) {
173
+ continue; // efficiency cores harm lockstep threading
174
+ }
175
+ ++cpu; // hyperthreading isn't useful for linear algebra
176
+ ++result;
177
+ }
178
+ return result;
179
+ }
180
+
181
+ #endif // __x86_64__ && __linux__
182
+
183
+ /**
184
+ * Returns number of CPUs on system that are useful for math.
185
+ */
186
+ int32_t cpu_get_num_math() {
187
+ #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
188
+ int n_cpu = sysconf(_SC_NPROCESSORS_ONLN);
189
+ if (n_cpu < 1) {
190
+ return cpu_get_num_physical_cores();
191
+ }
192
+ if (is_hybrid_cpu()) {
193
+ cpu_set_t affinity;
194
+ if (!pthread_getaffinity_np(pthread_self(), sizeof(affinity), &affinity)) {
195
+ int result = cpu_count_math_cpus(n_cpu);
196
+ pthread_setaffinity_np(pthread_self(), sizeof(affinity), &affinity);
197
+ if (result > 0) {
198
+ return result;
199
+ }
200
+ }
201
+ }
202
+ #endif
203
+ return cpu_get_num_physical_cores();
204
+ }
205
+
206
+ // Helper for setting process priority
207
+
208
+ #if defined(_WIN32)
209
+
210
+ bool set_process_priority(enum ggml_sched_priority prio) {
211
+ if (prio == GGML_SCHED_PRIO_NORMAL) {
212
+ return true;
213
+ }
214
+
215
+ DWORD p = NORMAL_PRIORITY_CLASS;
216
+ switch (prio) {
217
+ case GGML_SCHED_PRIO_LOW: p = BELOW_NORMAL_PRIORITY_CLASS; break;
218
+ case GGML_SCHED_PRIO_NORMAL: p = NORMAL_PRIORITY_CLASS; break;
219
+ case GGML_SCHED_PRIO_MEDIUM: p = ABOVE_NORMAL_PRIORITY_CLASS; break;
220
+ case GGML_SCHED_PRIO_HIGH: p = HIGH_PRIORITY_CLASS; break;
221
+ case GGML_SCHED_PRIO_REALTIME: p = REALTIME_PRIORITY_CLASS; break;
222
+ }
223
+
224
+ if (!SetPriorityClass(GetCurrentProcess(), p)) {
225
+ LOG_WRN("failed to set process priority class %d : (%d)\n", prio, (int) GetLastError());
226
+ return false;
227
+ }
228
+
229
+ return true;
230
+ }
231
+
232
+ #else // MacOS and POSIX
233
+ #include <sys/types.h>
234
+ #include <sys/resource.h>
235
+
236
+ bool set_process_priority(enum ggml_sched_priority prio) {
237
+ if (prio == GGML_SCHED_PRIO_NORMAL) {
238
+ return true;
239
+ }
240
+
241
+ int p = 0;
242
+ switch (prio) {
243
+ case GGML_SCHED_PRIO_LOW: p = 5; break;
244
+ case GGML_SCHED_PRIO_NORMAL: p = 0; break;
245
+ case GGML_SCHED_PRIO_MEDIUM: p = -5; break;
246
+ case GGML_SCHED_PRIO_HIGH: p = -10; break;
247
+ case GGML_SCHED_PRIO_REALTIME: p = -20; break;
248
+ }
249
+
250
+ if (setpriority(PRIO_PROCESS, 0, p) != 0) {
251
+ LOG_WRN("failed to set process priority %d : %s (%d)\n", prio, strerror(errno), errno);
252
+ return false;
253
+ }
254
+ return true;
255
+ }
256
+
257
+ #endif
258
+
259
+ //
260
+ // CLI argument parsing
261
+ //
262
+
263
+
264
+ void postprocess_cpu_params(cpu_params& cpuparams, const cpu_params* role_model) {
265
+ int32_t n_set = 0;
266
+
267
+ if (cpuparams.n_threads < 0) {
268
+ // Assuming everything about cpuparams is invalid
269
+ if (role_model != nullptr) {
270
+ cpuparams = *role_model;
271
+ } else {
272
+ cpuparams.n_threads = cpu_get_num_math();
273
+ }
274
+ }
275
+
276
+ for (int32_t i = 0; i < GGML_MAX_N_THREADS; i++) {
277
+ if (cpuparams.cpumask[i]) {
278
+ n_set++;
279
+ }
280
+ }
281
+
282
+ if (n_set && n_set < cpuparams.n_threads) {
283
+ // Not enough set bits, may experience performance issues.
284
+ LOG_WRN("Not enough set bits in CPU mask (%d) to satisfy requested thread count: %d\n", n_set, cpuparams.n_threads);
285
+ }
286
+ }
287
+
288
+ bool parse_cpu_range(const std::string & range, bool (&boolmask)[GGML_MAX_N_THREADS]) {
289
+ size_t dash_loc = range.find('-');
290
+ if (dash_loc == std::string::npos) {
291
+ LOG_ERR("Format of CPU range is invalid! Expected [<start>]-[<end>].\n");
292
+ return false;
293
+ }
294
+
295
+ size_t start_i;
296
+ size_t end_i;
297
+
298
+ if (dash_loc == 0) {
299
+ start_i = 0;
300
+ } else {
301
+ start_i = std::stoull(range.substr(0, dash_loc));
302
+ if (start_i >= GGML_MAX_N_THREADS) {
303
+ LOG_ERR("Start index out of bounds!\n");
304
+ return false;
305
+ }
306
+ }
307
+
308
+ if (dash_loc == range.length() - 1) {
309
+ end_i = GGML_MAX_N_THREADS - 1;
310
+ } else {
311
+ end_i = std::stoull(range.substr(dash_loc + 1));
312
+ if (end_i >= GGML_MAX_N_THREADS) {
313
+ LOG_ERR("End index out of bounds!\n");
314
+ return false;
315
+ }
316
+ }
317
+
318
+ for (size_t i = start_i; i <= end_i; i++) {
319
+ boolmask[i] = true;
320
+ }
321
+
322
+ return true;
323
+ }
324
+
325
+ bool parse_cpu_mask(const std::string & mask, bool (&boolmask)[GGML_MAX_N_THREADS]) {
326
+ // Discard potential 0x prefix
327
+ size_t start_i = 0;
328
+ if (mask.length() >= 2 && mask.substr(0, 2) == "0x") {
329
+ start_i = 2;
330
+ }
331
+
332
+ size_t num_digits = mask.length() - start_i;
333
+ if (num_digits > 128) num_digits = 128;
334
+
335
+ size_t end_i = num_digits + start_i;
336
+
337
+ for (size_t i = start_i, n = (num_digits*4 - 1); i < end_i; i++, n-=4) {
338
+ char c = mask.at(i);
339
+ int8_t id = c;
340
+
341
+ if ((c >= '0' && c <= '9')) {
342
+ id -= '0';
343
+ } else if (c >= 'a' && c <= 'f') {
344
+ id -= 'a' - 10;
345
+ } else if (c >= 'A' && c <= 'F') {
346
+ id -= 'A' - 10;
347
+ } else {
348
+ LOG_ERR("Invalid hex character '%c' at position %d\n", c, int32_t(i));
349
+ return false;
350
+ }
351
+
352
+ boolmask[ n ] = boolmask[ n ] || ((id & 8) != 0);
353
+ boolmask[n - 1] = boolmask[n - 1] || ((id & 4) != 0);
354
+ boolmask[n - 2] = boolmask[n - 2] || ((id & 2) != 0);
355
+ boolmask[n - 3] = boolmask[n - 3] || ((id & 1) != 0);
356
+ }
357
+
358
+ return true;
359
+ }
360
+
361
+ void common_init() {
362
+ llama_log_set(common_log_default_callback, NULL);
363
+
364
+ #ifdef NDEBUG
365
+ const char * build_type = "";
366
+ #else
367
+ const char * build_type = " (debug)";
368
+ #endif
369
+
370
+ LOG_INF("build: %d (%s) with %s for %s%s\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT, LLAMA_COMPILER, LLAMA_BUILD_TARGET, build_type);
371
+ }
372
+
373
+ std::string common_params_get_system_info(const common_params & params) {
374
+ std::ostringstream os;
375
+
376
+ os << "system_info: n_threads = " << params.cpuparams.n_threads;
377
+ if (params.cpuparams_batch.n_threads != -1) {
378
+ os << " (n_threads_batch = " << params.cpuparams_batch.n_threads << ")";
379
+ }
380
+ #if defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
381
+ // TODO: windows + arm64 + mingw64
382
+ DWORD logicalProcessorCount = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
383
+ os << " / " << logicalProcessorCount << " | " << llama_print_system_info();
384
+ #else
385
+ os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
386
+ #endif
387
+
388
+ return os.str();
389
+ }
390
+
391
+ //
392
+ // String utils
393
+ //
394
+
395
+ std::string string_format(const char * fmt, ...) {
396
+ va_list ap;
397
+ va_list ap2;
398
+ va_start(ap, fmt);
399
+ va_copy(ap2, ap);
400
+ int size = vsnprintf(NULL, 0, fmt, ap);
401
+ GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
402
+ std::vector<char> buf(size + 1);
403
+ int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
404
+ GGML_ASSERT(size2 == size);
405
+ va_end(ap2);
406
+ va_end(ap);
407
+ return std::string(buf.data(), size);
408
+ }
409
+
410
+ std::string string_strip(const std::string & str) {
411
+ size_t start = 0;
412
+ size_t end = str.size();
413
+ while (start < end && std::isspace(str[start])) {
414
+ start++;
415
+ }
416
+ while (end > start && std::isspace(str[end - 1])) {
417
+ end--;
418
+ }
419
+ return str.substr(start, end - start);
420
+ }
421
+
422
+ std::string string_get_sortable_timestamp() {
423
+ using clock = std::chrono::system_clock;
424
+
425
+ const clock::time_point current_time = clock::now();
426
+ const time_t as_time_t = clock::to_time_t(current_time);
427
+ char timestamp_no_ns[100];
428
+ std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
429
+
430
+ const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
431
+ current_time.time_since_epoch() % 1000000000).count();
432
+ char timestamp_ns[11];
433
+ snprintf(timestamp_ns, 11, "%09" PRId64, ns);
434
+
435
+ return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
436
+ }
437
+
438
+ void string_replace_all(std::string & s, const std::string & search, const std::string & replace) {
439
+ if (search.empty()) {
440
+ return;
441
+ }
442
+ std::string builder;
443
+ builder.reserve(s.length());
444
+ size_t pos = 0;
445
+ size_t last_pos = 0;
446
+ while ((pos = s.find(search, last_pos)) != std::string::npos) {
447
+ builder.append(s, last_pos, pos - last_pos);
448
+ builder.append(replace);
449
+ last_pos = pos + search.length();
450
+ }
451
+ builder.append(s, last_pos, std::string::npos);
452
+ s = std::move(builder);
453
+ }
454
+
455
+ std::string regex_escape(const std::string & s) {
456
+ static const std::regex special_chars("[.^$|()*+?\\[\\]{}\\\\]");
457
+ return std::regex_replace(s, special_chars, "\\$&");
458
+ }
459
+
460
+ std::string string_join(const std::vector<std::string> & values, const std::string & separator) {
461
+ std::ostringstream result;
462
+ for (size_t i = 0; i < values.size(); ++i) {
463
+ if (i > 0) {
464
+ result << separator;
465
+ }
466
+ result << values[i];
467
+ }
468
+ return result.str();
469
+ }
470
+
471
+ std::vector<std::string> string_split(const std::string & str, const std::string & delimiter) {
472
+ std::vector<std::string> parts;
473
+ size_t start = 0;
474
+ size_t end = str.find(delimiter);
475
+
476
+ while (end != std::string::npos) {
477
+ parts.push_back(str.substr(start, end - start));
478
+ start = end + delimiter.length();
479
+ end = str.find(delimiter, start);
480
+ }
481
+
482
+ parts.push_back(str.substr(start));
483
+
484
+ return parts;
485
+ }
486
+
487
+ std::string string_repeat(const std::string & str, size_t n) {
488
+ if (n == 0) {
489
+ return "";
490
+ }
491
+
492
+ std::string result;
493
+ result.reserve(str.length() * n);
494
+
495
+ for (size_t i = 0; i < n; ++i) {
496
+ result += str;
497
+ }
498
+
499
+ return result;
500
+ }
501
+
502
+ std::string string_from(bool value) {
503
+ return value ? "true" : "false";
504
+ }
505
+
506
+ std::string string_from(const std::vector<int> & values) {
507
+ std::stringstream buf;
508
+
509
+ buf << "[ ";
510
+ bool first = true;
511
+ for (auto e : values) {
512
+ if (first) {
513
+ first = false;
514
+ } else {
515
+ buf << ", ";
516
+ }
517
+ buf << std::to_string(e);
518
+ }
519
+ buf << " ]";
520
+
521
+ return buf.str();
522
+ }
523
+
524
+ std::string string_from(const struct llama_context * ctx, const std::vector<llama_token> & tokens) {
525
+ std::stringstream buf;
526
+
527
+ buf << "[ ";
528
+
529
+ bool first = true;
530
+ for (const auto & token : tokens) {
531
+ if (!first) {
532
+ buf << ", ";
533
+ } else {
534
+ first = false;
535
+ }
536
+
537
+ auto detokenized = common_token_to_piece(ctx, token);
538
+
539
+ buf << "'" << detokenized << "'"
540
+ << ":" << std::to_string(token);
541
+ }
542
+
543
+ buf << " ]";
544
+
545
+ return buf.str();
546
+ }
547
+
548
+ std::string string_from(const struct llama_context * ctx, const struct llama_batch & batch) {
549
+ std::stringstream buf;
550
+
551
+ buf << "[ ";
552
+
553
+ bool first = true;
554
+ for (int i = 0; i < batch.n_tokens; ++i) {
555
+ if (!first) {
556
+ buf << ", ";
557
+ } else {
558
+ first = false;
559
+ }
560
+
561
+ auto detokenized = common_token_to_piece(ctx, batch.token[i]);
562
+
563
+ buf << "\n" << std::to_string(i)
564
+ << ", token '" << detokenized << "'"
565
+ << ", pos " << std::to_string(batch.pos[i])
566
+ << ", n_seq_id " << std::to_string(batch.n_seq_id[i])
567
+ << ", seq_id " << std::to_string(batch.seq_id[i][0])
568
+ << ", logits " << std::to_string(batch.logits[i]);
569
+ }
570
+
571
+ buf << " ]";
572
+
573
+ return buf.str();
574
+ }
575
+
576
+ void string_process_escapes(std::string & input) {
577
+ std::size_t input_len = input.length();
578
+ std::size_t output_idx = 0;
579
+
580
+ for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
581
+ if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
582
+ switch (input[++input_idx]) {
583
+ case 'n': input[output_idx++] = '\n'; break;
584
+ case 'r': input[output_idx++] = '\r'; break;
585
+ case 't': input[output_idx++] = '\t'; break;
586
+ case '\'': input[output_idx++] = '\''; break;
587
+ case '\"': input[output_idx++] = '\"'; break;
588
+ case '\\': input[output_idx++] = '\\'; break;
589
+ case 'x':
590
+ // Handle \x12, etc
591
+ if (input_idx + 2 < input_len) {
592
+ const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
593
+ char *err_p = nullptr;
594
+ const long val = std::strtol(x, &err_p, 16);
595
+ if (err_p == x + 2) {
596
+ input_idx += 2;
597
+ input[output_idx++] = char(val);
598
+ break;
599
+ }
600
+ }
601
+ // fall through
602
+ default: input[output_idx++] = '\\';
603
+ input[output_idx++] = input[input_idx]; break;
604
+ }
605
+ } else {
606
+ input[output_idx++] = input[input_idx];
607
+ }
608
+ }
609
+
610
+ input.resize(output_idx);
611
+ }
612
+
613
+ bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides) {
614
+ const char * sep = strchr(data, '=');
615
+ if (sep == nullptr || sep - data >= 128) {
616
+ LOG_ERR("%s: malformed KV override '%s'\n", __func__, data);
617
+ return false;
618
+ }
619
+ llama_model_kv_override kvo;
620
+ std::strncpy(kvo.key, data, sep - data);
621
+ kvo.key[sep - data] = 0;
622
+ sep++;
623
+ if (strncmp(sep, "int:", 4) == 0) {
624
+ sep += 4;
625
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
626
+ kvo.val_i64 = std::atol(sep);
627
+ } else if (strncmp(sep, "float:", 6) == 0) {
628
+ sep += 6;
629
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
630
+ kvo.val_f64 = std::atof(sep);
631
+ } else if (strncmp(sep, "bool:", 5) == 0) {
632
+ sep += 5;
633
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
634
+ if (std::strcmp(sep, "true") == 0) {
635
+ kvo.val_bool = true;
636
+ } else if (std::strcmp(sep, "false") == 0) {
637
+ kvo.val_bool = false;
638
+ } else {
639
+ LOG_ERR("%s: invalid boolean value for KV override '%s'\n", __func__, data);
640
+ return false;
641
+ }
642
+ } else if (strncmp(sep, "str:", 4) == 0) {
643
+ sep += 4;
644
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
645
+ if (strlen(sep) > 127) {
646
+ LOG_ERR("%s: malformed KV override '%s', value cannot exceed 127 chars\n", __func__, data);
647
+ return false;
648
+ }
649
+ strncpy(kvo.val_str, sep, 127);
650
+ kvo.val_str[127] = '\0';
651
+ } else {
652
+ LOG_ERR("%s: invalid type for KV override '%s'\n", __func__, data);
653
+ return false;
654
+ }
655
+ overrides.emplace_back(std::move(kvo));
656
+ return true;
657
+ }
658
+
659
+ //
660
+ // Filesystem utils
661
+ //
662
+
663
+ // Validate if a filename is safe to use
664
+ // To validate a full path, split the path by the OS-specific path separator, and validate each part with this function
665
+ bool fs_validate_filename(const std::string & filename, bool allow_subdirs) {
666
+ if (!filename.length()) {
667
+ // Empty filename invalid
668
+ return false;
669
+ }
670
+ if (filename.length() > 255) {
671
+ // Limit at common largest possible filename on Linux filesystems
672
+ // to avoid unnecessary further validation
673
+ // (On systems with smaller limits it will be caught by the OS)
674
+ return false;
675
+ }
676
+
677
+ size_t offset = 0;
678
+ while (offset < filename.size()) {
679
+ utf8_parse_result result = parse_utf8_codepoint(filename, offset);
680
+
681
+ if (result.status != utf8_parse_result::SUCCESS) {
682
+ return false;
683
+ }
684
+ uint32_t c = result.codepoint;
685
+
686
+ if ((result.bytes_consumed == 2 && c < 0x80) ||
687
+ (result.bytes_consumed == 3 && c < 0x800) ||
688
+ (result.bytes_consumed == 4 && c < 0x10000)) {
689
+ return false;
690
+ }
691
+
692
+ // Check for forbidden codepoints:
693
+ // - Control characters
694
+ // - Unicode equivalents of illegal characters
695
+ // - UTF-16 surrogate pairs
696
+ // - UTF-8 replacement character
697
+ // - Byte order mark (BOM)
698
+ // - Illegal characters: / \ : * ? " < > |
699
+ if (c <= 0x1F // Control characters (C0)
700
+ || c == 0x7F // Control characters (DEL)
701
+ || (c >= 0x80 && c <= 0x9F) // Control characters (C1)
702
+ || c == 0xFF0E // Fullwidth Full Stop (period equivalent)
703
+ || c == 0x2215 // Division Slash (forward slash equivalent)
704
+ || c == 0x2216 // Set Minus (backslash equivalent)
705
+ || (c >= 0xD800 && c <= 0xDFFF) // UTF-16 surrogate pairs
706
+ || c > 0x10FFFF // Max Unicode limit
707
+ || c == 0xFFFD // Replacement Character (UTF-8)
708
+ || c == 0xFEFF // Byte Order Mark (BOM)
709
+ || c == ':' || c == '*' // Illegal characters
710
+ || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
711
+ return false;
712
+ }
713
+ if (!allow_subdirs && (c == '/' || c == '\\')) {
714
+ // Subdirectories not allowed, reject path separators
715
+ return false;
716
+ }
717
+ offset += result.bytes_consumed;
718
+ }
719
+
720
+ // Reject any leading or trailing ' ', or any trailing '.', these are stripped on Windows and will cause a different filename
721
+ // Unicode and other whitespace is not affected, only 0x20 space
722
+ if (filename.front() == ' ' || filename.back() == ' ' || filename.back() == '.') {
723
+ return false;
724
+ }
725
+
726
+ // Reject any ".." (currently stricter than necessary, it should be fine to just check for == ".." instead)
727
+ if (filename.find("..") != std::string::npos) {
728
+ return false;
729
+ }
730
+
731
+ // Reject "."
732
+ if (filename == ".") {
733
+ return false;
734
+ }
735
+
736
+ return true;
737
+ }
738
+
739
+ #include <iostream>
740
+
741
+
742
+ #ifdef _WIN32
743
+ static std::wstring utf8_to_wstring(const std::string & str) {
744
+ if (str.empty()) {
745
+ return std::wstring();
746
+ }
747
+
748
+ int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), NULL, 0);
749
+
750
+ if (size <= 0) {
751
+ return std::wstring();
752
+ }
753
+
754
+ std::wstring wstr(size, 0);
755
+ MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), &wstr[0], size);
756
+
757
+ return wstr;
758
+ }
759
+ #endif
760
+
761
+ // returns true if successful, false otherwise
762
+ bool fs_create_directory_with_parents(const std::string & path) {
763
+ #ifdef _WIN32
764
+ std::wstring wpath = utf8_to_wstring(path);
765
+
766
+ // if the path already exists, check whether it's a directory
767
+ const DWORD attributes = GetFileAttributesW(wpath.c_str());
768
+ if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
769
+ return true;
770
+ }
771
+
772
+ size_t pos_slash = 0;
773
+
774
+ // process path from front to back, procedurally creating directories
775
+ while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
776
+ const std::wstring subpath = wpath.substr(0, pos_slash);
777
+
778
+ pos_slash += 1;
779
+
780
+ // skip the drive letter, in some systems it can return an access denied error
781
+ if (subpath.length() == 2 && subpath[1] == ':') {
782
+ continue;
783
+ }
784
+
785
+ const bool success = CreateDirectoryW(subpath.c_str(), NULL);
786
+
787
+ if (!success) {
788
+ const DWORD error = GetLastError();
789
+
790
+ // if the path already exists, ensure that it's a directory
791
+ if (error == ERROR_ALREADY_EXISTS) {
792
+ const DWORD attributes = GetFileAttributesW(subpath.c_str());
793
+ if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
794
+ return false;
795
+ }
796
+ } else {
797
+ return false;
798
+ }
799
+ }
800
+ }
801
+
802
+ return true;
803
+ #else
804
+ // if the path already exists, check whether it's a directory
805
+ struct stat info;
806
+ if (stat(path.c_str(), &info) == 0) {
807
+ return S_ISDIR(info.st_mode);
808
+ }
809
+
810
+ size_t pos_slash = 1; // skip leading slashes for directory creation
811
+
812
+ // process path from front to back, procedurally creating directories
813
+ while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
814
+ const std::string subpath = path.substr(0, pos_slash);
815
+ struct stat info;
816
+
817
+ // if the path already exists, ensure that it's a directory
818
+ if (stat(subpath.c_str(), &info) == 0) {
819
+ if (!S_ISDIR(info.st_mode)) {
820
+ return false;
821
+ }
822
+ } else {
823
+ // create parent directories
824
+ const int ret = mkdir(subpath.c_str(), 0755);
825
+ if (ret != 0) {
826
+ return false;
827
+ }
828
+ }
829
+
830
+ pos_slash += 1;
831
+ }
832
+
833
+ return true;
834
+ #endif // _WIN32
835
+ }
836
+
837
+ bool fs_is_directory(const std::string & path) {
838
+ std::filesystem::path dir(path);
839
+ return std::filesystem::exists(dir) && std::filesystem::is_directory(dir);
840
+ }
841
+
842
+ std::string fs_get_cache_directory() {
843
+ std::string cache_directory = "";
844
+ auto ensure_trailing_slash = [](std::string p) {
845
+ // Make sure to add trailing slash
846
+ if (p.back() != DIRECTORY_SEPARATOR) {
847
+ p += DIRECTORY_SEPARATOR;
848
+ }
849
+ return p;
850
+ };
851
+ if (getenv("LLAMA_CACHE")) {
852
+ cache_directory = std::getenv("LLAMA_CACHE");
853
+ } else {
854
+ #if defined(__linux__) || defined(__FreeBSD__) || defined(_AIX) || \
855
+ defined(__OpenBSD__) || defined(__NetBSD__)
856
+ if (std::getenv("XDG_CACHE_HOME")) {
857
+ cache_directory = std::getenv("XDG_CACHE_HOME");
858
+ } else if (std::getenv("HOME")) {
859
+ cache_directory = std::getenv("HOME") + std::string("/.cache/");
860
+ } else {
861
+ #if defined(__linux__)
862
+ /* no $HOME is defined, fallback to getpwuid */
863
+ struct passwd *pw = getpwuid(getuid());
864
+ if ((!pw) || (!pw->pw_dir)) {
865
+ throw std::runtime_error("Failed to find $HOME directory");
866
+ }
867
+
868
+ cache_directory = std::string(pw->pw_dir) + std::string("/.cache/");
869
+ #else /* defined(__linux__) */
870
+ throw std::runtime_error("Failed to find $HOME directory");
871
+ #endif /* defined(__linux__) */
872
+ }
873
+ #elif defined(__APPLE__)
874
+ cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
875
+ #elif defined(_WIN32)
876
+ cache_directory = std::getenv("LOCALAPPDATA");
877
+ #elif defined(__EMSCRIPTEN__)
878
+ GGML_ABORT("not implemented on this platform");
879
+ #else
880
+ # error Unknown architecture
881
+ #endif
882
+ cache_directory = ensure_trailing_slash(cache_directory);
883
+ cache_directory += "llama.cpp";
884
+ }
885
+ return ensure_trailing_slash(cache_directory);
886
+ }
887
+
888
+ std::string fs_get_cache_file(const std::string & filename) {
889
+ GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos);
890
+ std::string cache_directory = fs_get_cache_directory();
891
+ const bool success = fs_create_directory_with_parents(cache_directory);
892
+ if (!success) {
893
+ throw std::runtime_error("failed to create cache directory: " + cache_directory);
894
+ }
895
+ return cache_directory + filename;
896
+ }
897
+
898
+ std::vector<common_file_info> fs_list(const std::string & path, bool include_directories) {
899
+ std::vector<common_file_info> files;
900
+ if (path.empty()) return files;
901
+
902
+ std::filesystem::path dir(path);
903
+ if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) {
904
+ return files;
905
+ }
906
+
907
+ for (const auto & entry : std::filesystem::directory_iterator(dir)) {
908
+ try {
909
+ // Only include regular files (skip directories)
910
+ const auto & p = entry.path();
911
+ if (std::filesystem::is_regular_file(p)) {
912
+ common_file_info info;
913
+ info.path = p.string();
914
+ info.name = p.filename().string();
915
+ info.is_dir = false;
916
+ try {
917
+ info.size = static_cast<size_t>(std::filesystem::file_size(p));
918
+ } catch (const std::filesystem::filesystem_error &) {
919
+ info.size = 0;
920
+ }
921
+ files.push_back(std::move(info));
922
+ } else if (include_directories && std::filesystem::is_directory(p)) {
923
+ common_file_info info;
924
+ info.path = p.string();
925
+ info.name = p.filename().string();
926
+ info.size = 0; // Directories have no size
927
+ info.is_dir = true;
928
+ files.push_back(std::move(info));
929
+ }
930
+ } catch (const std::filesystem::filesystem_error &) {
931
+ // skip entries we cannot inspect
932
+ continue;
933
+ }
934
+ }
935
+
936
+ return files;
937
+ }
938
+
939
+ //
940
+ // TTY utils
941
+ //
942
+
943
+ bool tty_can_use_colors() {
944
+ // Check NO_COLOR environment variable (https://no-color.org/)
945
+ if (const char * no_color = std::getenv("NO_COLOR")) {
946
+ if (no_color[0] != '\0') {
947
+ return false;
948
+ }
949
+ }
950
+
951
+ // Check TERM environment variable
952
+ if (const char * term = std::getenv("TERM")) {
953
+ if (std::strcmp(term, "dumb") == 0) {
954
+ return false;
955
+ }
956
+ }
957
+
958
+ // Check if stdout and stderr are connected to a terminal
959
+ // We check both because log messages can go to either
960
+ bool stdout_is_tty = isatty(fileno(stdout));
961
+ bool stderr_is_tty = isatty(fileno(stderr));
962
+
963
+ return stdout_is_tty || stderr_is_tty;
964
+ }
965
+
966
+ //
967
+ // Model utils
968
+ //
969
+
970
+ // TODO: move to common/sampling
971
+ static void common_init_sampler_from_model(
972
+ const llama_model * model,
973
+ common_params_sampling & sparams) {
974
+
975
+ const uint64_t config = sparams.user_sampling_config;
976
+
977
+ auto get_int32 = [&](const char * key, int32_t & dst, uint64_t user_config) {
978
+ if (config & user_config) {
979
+ return;
980
+ }
981
+
982
+ char buf[64] = {0};
983
+ if (llama_model_meta_val_str(model, key, buf, sizeof(buf)) > 0) {
984
+ char * end = nullptr;
985
+ int32_t v = strtol(buf, &end, 10);
986
+ if (end && end != buf) {
987
+ dst = v;
988
+ }
989
+ }
990
+ };
991
+
992
+ auto get_float = [&](const char * key, float & dst, uint64_t user_config) {
993
+ if (config & user_config) {
994
+ return;
995
+ }
996
+
997
+ char buf[128] = {0};
998
+ if (llama_model_meta_val_str(model, key, buf, sizeof(buf)) > 0) {
999
+ char * end = nullptr;
1000
+ float v = strtof(buf, &end);
1001
+ if (end && end != buf) {
1002
+ dst = v;
1003
+ }
1004
+ }
1005
+ };
1006
+
1007
+ // Sampling sequence
1008
+ if (!(config & common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_SAMPLERS)) {
1009
+ char buf[512] = {0};
1010
+ if (llama_model_meta_val_str(model, llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_SEQUENCE), buf, sizeof(buf)) > 0) {
1011
+ const std::vector<std::string> sampler_names = string_split<std::string>(std::string(buf), ';');
1012
+ if (!sampler_names.empty()) {
1013
+ sparams.samplers = common_sampler_types_from_names(sampler_names, true);
1014
+ }
1015
+ }
1016
+ }
1017
+
1018
+ get_int32(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_TOP_K), sparams.top_k, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_TOP_K);
1019
+ get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_TOP_P), sparams.top_p, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_TOP_P);
1020
+ get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIN_P), sparams.min_p, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIN_P);
1021
+ get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_XTC_PROBABILITY), sparams.xtc_probability, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_XTC_PROBABILITY);
1022
+ get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_XTC_THRESHOLD), sparams.xtc_threshold, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_XTC_THRESHOLD);
1023
+ get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_TEMP), sparams.temp, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_TEMP);
1024
+ get_int32(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_PENALTY_LAST_N), sparams.penalty_last_n, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_PENALTY_LAST_N);
1025
+ get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_PENALTY_REPEAT), sparams.penalty_repeat, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_PENALTY_REPEAT);
1026
+ get_int32(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT), sparams.mirostat, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT);
1027
+ get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT_TAU), sparams.mirostat_tau, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT_TAU);
1028
+ get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT_ETA), sparams.mirostat_eta, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT_ETA);
1029
+ }
1030
+
1031
+ struct common_init_result::impl {
1032
+ impl() = default;
1033
+ ~impl() = default;
1034
+
1035
+ // note: the order in which model, context, etc. are declared matters because their destructors will be called bottom-to-top
1036
+
1037
+ llama_model_ptr model;
1038
+ llama_context_ptr context;
1039
+
1040
+ std::vector<llama_adapter_lora_ptr> lora;
1041
+
1042
+ std::vector<common_sampler_ptr> samplers;
1043
+ std::vector<llama_sampler_seq_config> samplers_seq_config;
1044
+ };
1045
+
1046
+ common_init_result::common_init_result(common_params & params) :
1047
+ pimpl(new impl{}) {
1048
+ auto mparams = common_model_params_to_llama(params);
1049
+ auto cparams = common_context_params_to_llama(params);
1050
+
1051
+ if (params.fit_params) {
1052
+ LOG_INF("%s: fitting params to device memory, for bugs during this step try to reproduce them with -fit off, or provide --verbose logs if the bug only occurs with -fit on\n", __func__);
1053
+ llama_params_fit(params.model.path.c_str(), &mparams, &cparams,
1054
+ params.tensor_split,
1055
+ params.tensor_buft_overrides.data(),
1056
+ params.fit_params_target.data(),
1057
+ params.fit_params_min_ctx,
1058
+ params.verbosity >= 4 ? GGML_LOG_LEVEL_DEBUG : GGML_LOG_LEVEL_ERROR);
1059
+ }
1060
+
1061
+ llama_model * model = llama_model_load_from_file(params.model.path.c_str(), mparams);
1062
+ if (model == NULL) {
1063
+ return;
1064
+ }
1065
+
1066
+ pimpl->model.reset(model);
1067
+
1068
+ const llama_vocab * vocab = llama_model_get_vocab(model);
1069
+
1070
+ // load and optionally apply lora adapters (must be loaded before context creation)
1071
+ for (auto & la : params.lora_adapters) {
1072
+ llama_adapter_lora_ptr lora;
1073
+ lora.reset(llama_adapter_lora_init(model, la.path.c_str()));
1074
+ if (lora == nullptr) {
1075
+ LOG_ERR("%s: failed to load lora adapter '%s'\n", __func__, la.path.c_str());
1076
+ pimpl->model.reset(model);
1077
+ return;
1078
+ }
1079
+
1080
+ char buf[1024];
1081
+ la.ptr = lora.get();
1082
+ llama_adapter_meta_val_str(la.ptr, "adapter.lora.task_name", buf, sizeof(buf));
1083
+ la.task_name = buf;
1084
+ llama_adapter_meta_val_str(la.ptr, "adapter.lora.prompt_prefix", buf, sizeof(buf));
1085
+ la.prompt_prefix = buf;
1086
+ pimpl->lora.emplace_back(std::move(lora)); // copy to list of loaded adapters
1087
+ }
1088
+
1089
+ // updates params.sampling
1090
+ // TODO: fix naming
1091
+ common_init_sampler_from_model(model, params.sampling);
1092
+
1093
+ if (params.sampling.ignore_eos && llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
1094
+ LOG_WRN("%s: warning: vocab does not have an EOS token, ignoring --ignore-eos\n", __func__);
1095
+ params.sampling.ignore_eos = false;
1096
+ }
1097
+
1098
+ // initialize once
1099
+ for (llama_token i = 0; i < llama_vocab_n_tokens(vocab); i++) {
1100
+ if (llama_vocab_is_eog(vocab, i)) {
1101
+ LOG_INF("%s: added %s logit bias = %f\n", __func__, common_token_to_piece(vocab, i).c_str(), -INFINITY);
1102
+ params.sampling.logit_bias_eog.push_back({i, -INFINITY});
1103
+ }
1104
+ }
1105
+
1106
+ if (params.sampling.ignore_eos) {
1107
+ // add EOG biases to the active set of logit biases
1108
+ params.sampling.logit_bias.insert(
1109
+ params.sampling.logit_bias.end(),
1110
+ params.sampling.logit_bias_eog.begin(), params.sampling.logit_bias_eog.end());
1111
+ }
1112
+
1113
+ //if (params.sampling.penalty_last_n == -1) {
1114
+ // LOG_INF("%s: setting penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
1115
+ // params.sampling.penalty_last_n = llama_n_ctx(lctx);
1116
+ //}
1117
+
1118
+ //if (params.sampling.dry_penalty_last_n == -1) {
1119
+ // LOG_INF("%s: setting dry_penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
1120
+ // params.sampling.dry_penalty_last_n = llama_n_ctx(lctx);
1121
+ //}
1122
+
1123
+ // init the backend samplers as part of the context creation
1124
+ pimpl->samplers.resize(cparams.n_seq_max);
1125
+ pimpl->samplers_seq_config.resize(cparams.n_seq_max);
1126
+
1127
+ for (int i = 0; i < (int) cparams.n_seq_max; ++i) {
1128
+ pimpl->samplers[i].reset(common_sampler_init(model, params.sampling));
1129
+ pimpl->samplers_seq_config[i] = { i, common_sampler_get(pimpl->samplers[i].get()) };
1130
+ }
1131
+
1132
+ if (params.sampling.backend_sampling) {
1133
+ cparams.samplers = pimpl->samplers_seq_config.data();
1134
+ cparams.n_samplers = pimpl->samplers_seq_config.size();
1135
+ }
1136
+
1137
+ llama_context * lctx = llama_init_from_model(model, cparams);
1138
+ if (lctx == NULL) {
1139
+ LOG_ERR("%s: failed to create context with model '%s'\n", __func__, params.model.path.c_str());
1140
+ return;
1141
+ }
1142
+
1143
+ pimpl->context.reset(lctx);
1144
+ }
1145
+
1146
+ llama_model * common_init_result::model() {
1147
+ return pimpl->model.get();
1148
+ }
1149
+
1150
+ llama_context * common_init_result::context() {
1151
+ return pimpl->context.get();
1152
+ }
1153
+
1154
+ common_sampler * common_init_result::sampler(llama_seq_id seq_id) {
1155
+ return pimpl->samplers[seq_id].get();
1156
+ }
1157
+
1158
+ void common_init_result::reset_samplers() {
1159
+ for (int i = 0; i < (int) pimpl->samplers.size(); ++i) {
1160
+ llama_sampler_reset(common_sampler_get(pimpl->samplers[i].get()));
1161
+ }
1162
+ }
1163
+
1164
+ std::vector<llama_adapter_lora_ptr> & common_init_result::lora() {
1165
+ return pimpl->lora;
1166
+ }
1167
+
1168
+ common_init_result_ptr common_init_from_params(common_params & params) {
1169
+ common_init_result_ptr res(new common_init_result(params));
1170
+
1171
+ llama_model * model = res->model();
1172
+ if (model == NULL) {
1173
+ LOG_ERR("%s: failed to load model '%s'\n", __func__, params.model.path.c_str());
1174
+ return res;
1175
+ }
1176
+
1177
+ llama_context * lctx = res->context();
1178
+ if (lctx == NULL) {
1179
+ LOG_ERR("%s: failed to create context with model '%s'\n", __func__, params.model.path.c_str());
1180
+ return res;
1181
+ }
1182
+
1183
+ const llama_vocab * vocab = llama_model_get_vocab(model);
1184
+
1185
+ if (params.ctx_shift && !llama_memory_can_shift(llama_get_memory(lctx))) {
1186
+ LOG_WRN("%s: KV cache shifting is not supported for this context, disabling KV cache shifting\n", __func__);
1187
+ params.ctx_shift = false;
1188
+ }
1189
+
1190
+ if (!params.control_vectors.empty()) {
1191
+ if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
1192
+ if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_model_n_layer(model);
1193
+
1194
+ const auto cvec = common_control_vector_load(params.control_vectors);
1195
+ if (cvec.n_embd == -1) {
1196
+ return res;
1197
+ }
1198
+
1199
+ int err = llama_set_adapter_cvec(
1200
+ lctx,
1201
+ cvec.data.data(),
1202
+ cvec.data.size(),
1203
+ cvec.n_embd,
1204
+ params.control_vector_layer_start,
1205
+ params.control_vector_layer_end);
1206
+ if (err) {
1207
+ return res;
1208
+ }
1209
+ }
1210
+
1211
+ if (llama_pooling_type(lctx) == LLAMA_POOLING_TYPE_RANK) {
1212
+ bool ok = true;
1213
+
1214
+ if (llama_vocab_bos(vocab) == LLAMA_TOKEN_NULL) {
1215
+ LOG_WRN("%s: warning: vocab does not have a BOS token, reranking will not work\n", __func__);
1216
+ ok = false;
1217
+ }
1218
+
1219
+ bool has_eos = llama_vocab_eos(vocab) != LLAMA_TOKEN_NULL;
1220
+ bool has_sep = llama_vocab_sep(vocab) != LLAMA_TOKEN_NULL;
1221
+ bool has_rerank_prompt = llama_model_chat_template(model, "rerank") != NULL;
1222
+
1223
+ if (!has_eos && !has_sep && !has_rerank_prompt) {
1224
+ LOG_WRN("%s: warning: vocab does not have an EOS token, SEP token, or rerank prompt. Reranking will not work\n", __func__);
1225
+ ok = false;
1226
+ } else if (!has_eos) {
1227
+ LOG_WRN("%s: warning: vocab does not have an EOS token, using SEP token as fallback\n", __func__);
1228
+ }
1229
+
1230
+ if (!ok) {
1231
+ return res;
1232
+ }
1233
+ }
1234
+
1235
+ if (!params.lora_init_without_apply) {
1236
+ common_set_adapter_lora(lctx, params.lora_adapters);
1237
+ }
1238
+
1239
+ if (params.warmup) {
1240
+ LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
1241
+
1242
+ llama_set_warmup(lctx, true);
1243
+
1244
+ std::vector<llama_token> tmp;
1245
+ llama_token bos = llama_vocab_bos(vocab);
1246
+ llama_token eos = llama_vocab_eos(vocab);
1247
+
1248
+ // some models (e.g. T5) don't have a BOS token
1249
+ if (bos != LLAMA_TOKEN_NULL) {
1250
+ tmp.push_back(bos);
1251
+ }
1252
+ if (eos != LLAMA_TOKEN_NULL) {
1253
+ tmp.push_back(eos);
1254
+ }
1255
+ if (tmp.empty()) {
1256
+ tmp.push_back(0);
1257
+ }
1258
+
1259
+ if (llama_model_has_encoder(model)) {
1260
+ llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
1261
+ llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
1262
+ if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
1263
+ decoder_start_token_id = bos;
1264
+ }
1265
+ tmp.clear();
1266
+ tmp.push_back(decoder_start_token_id);
1267
+ }
1268
+ if (llama_model_has_decoder(model)) {
1269
+ llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
1270
+ }
1271
+ llama_memory_clear(llama_get_memory(lctx), true);
1272
+ llama_synchronize(lctx);
1273
+ llama_perf_context_reset(lctx);
1274
+ llama_set_warmup(lctx, false);
1275
+
1276
+ // reset samplers to reset RNG state after warmup to the seeded state
1277
+ res->reset_samplers();
1278
+ }
1279
+
1280
+ return res;
1281
+ }
1282
+
1283
+ common_init_result::~common_init_result() = default;
1284
+
1285
+ std::string get_model_endpoint() {
1286
+ const char * model_endpoint_env = getenv("MODEL_ENDPOINT");
1287
+ // We still respect the use of environment-variable "HF_ENDPOINT" for backward-compatibility.
1288
+ const char * hf_endpoint_env = getenv("HF_ENDPOINT");
1289
+ const char * endpoint_env = model_endpoint_env ? model_endpoint_env : hf_endpoint_env;
1290
+ std::string model_endpoint = "https://huggingface.co/";
1291
+ if (endpoint_env) {
1292
+ model_endpoint = endpoint_env;
1293
+ if (model_endpoint.back() != '/') {
1294
+ model_endpoint += '/';
1295
+ }
1296
+ }
1297
+ return model_endpoint;
1298
+ }
1299
+
1300
+ void common_set_adapter_lora(struct llama_context * ctx, std::vector<common_adapter_lora_info> & lora) {
1301
+ std::vector<llama_adapter_lora *> loras;
1302
+ std::vector<float> scales;
1303
+
1304
+ for (auto & la: lora) {
1305
+ loras.push_back(la.ptr);
1306
+ scales.push_back(la.scale);
1307
+ }
1308
+
1309
+ llama_set_adapters_lora(ctx, loras.data(), loras.size(), scales.data());
1310
+ }
1311
+
1312
+ struct llama_model_params common_model_params_to_llama(common_params & params) {
1313
+ auto mparams = llama_model_default_params();
1314
+
1315
+ if (!params.devices.empty()) {
1316
+ mparams.devices = params.devices.data();
1317
+ }
1318
+
1319
+ mparams.n_gpu_layers = params.n_gpu_layers;
1320
+ mparams.main_gpu = params.main_gpu;
1321
+ mparams.split_mode = params.split_mode;
1322
+ mparams.tensor_split = params.tensor_split;
1323
+ mparams.use_mmap = params.use_mmap;
1324
+ mparams.use_direct_io = params.use_direct_io;
1325
+ mparams.use_mlock = params.use_mlock;
1326
+ mparams.check_tensors = params.check_tensors;
1327
+ mparams.use_extra_bufts = !params.no_extra_bufts;
1328
+ mparams.no_host = params.no_host;
1329
+
1330
+ if (params.kv_overrides.empty()) {
1331
+ mparams.kv_overrides = NULL;
1332
+ } else {
1333
+ GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
1334
+ mparams.kv_overrides = params.kv_overrides.data();
1335
+ }
1336
+
1337
+ if (params.tensor_buft_overrides.empty()) {
1338
+ mparams.tensor_buft_overrides = NULL;
1339
+ } else {
1340
+ GGML_ASSERT(params.tensor_buft_overrides.back().pattern == nullptr && "Tensor buffer overrides not terminated with empty pattern");
1341
+ mparams.tensor_buft_overrides = params.tensor_buft_overrides.data();
1342
+ }
1343
+
1344
+ mparams.progress_callback = params.load_progress_callback;
1345
+ mparams.progress_callback_user_data = params.load_progress_callback_user_data;
1346
+
1347
+ return mparams;
1348
+ }
1349
+
1350
+ struct llama_context_params common_context_params_to_llama(const common_params & params) {
1351
+ auto cparams = llama_context_default_params();
1352
+
1353
+ cparams.n_ctx = params.n_ctx;
1354
+ cparams.n_seq_max = params.n_parallel;
1355
+ cparams.n_batch = params.n_batch;
1356
+ cparams.n_ubatch = params.n_ubatch;
1357
+ cparams.n_threads = params.cpuparams.n_threads;
1358
+ cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
1359
+ params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
1360
+ cparams.embeddings = params.embedding;
1361
+ cparams.rope_scaling_type = params.rope_scaling_type;
1362
+ cparams.rope_freq_base = params.rope_freq_base;
1363
+ cparams.rope_freq_scale = params.rope_freq_scale;
1364
+ cparams.yarn_ext_factor = params.yarn_ext_factor;
1365
+ cparams.yarn_attn_factor = params.yarn_attn_factor;
1366
+ cparams.yarn_beta_fast = params.yarn_beta_fast;
1367
+ cparams.yarn_beta_slow = params.yarn_beta_slow;
1368
+ cparams.yarn_orig_ctx = params.yarn_orig_ctx;
1369
+ cparams.pooling_type = params.pooling_type;
1370
+ cparams.attention_type = params.attention_type;
1371
+ cparams.flash_attn_type = params.flash_attn_type;
1372
+ cparams.cb_eval = params.cb_eval;
1373
+ cparams.cb_eval_user_data = params.cb_eval_user_data;
1374
+ cparams.offload_kqv = !params.no_kv_offload;
1375
+ cparams.no_perf = params.no_perf;
1376
+ cparams.op_offload = !params.no_op_offload;
1377
+ cparams.swa_full = params.swa_full;
1378
+ cparams.kv_unified = params.kv_unified;
1379
+
1380
+ cparams.type_k = params.cache_type_k;
1381
+ cparams.type_v = params.cache_type_v;
1382
+
1383
+ return cparams;
1384
+ }
1385
+
1386
+ struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const cpu_params & params) {
1387
+ struct ggml_threadpool_params tpp;
1388
+
1389
+ ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
1390
+
1391
+ if (params.mask_valid) {
1392
+ std::memcpy(&tpp.cpumask, &params.cpumask, GGML_MAX_N_THREADS);
1393
+ }
1394
+
1395
+ tpp.prio = params.priority;
1396
+ tpp.poll = params.poll;
1397
+ tpp.strict_cpu = params.strict_cpu;
1398
+
1399
+ return tpp;
1400
+ }
1401
+
1402
+ //
1403
+ // Batch utils
1404
+ //
1405
+
1406
+ void common_batch_clear(struct llama_batch & batch) {
1407
+ batch.n_tokens = 0;
1408
+ }
1409
+
1410
+ void common_batch_add(
1411
+ struct llama_batch & batch,
1412
+ llama_token id,
1413
+ llama_pos pos,
1414
+ const std::vector<llama_seq_id> & seq_ids,
1415
+ bool logits) {
1416
+ GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
1417
+
1418
+ batch.token [batch.n_tokens] = id;
1419
+ batch.pos [batch.n_tokens] = pos;
1420
+ batch.n_seq_id[batch.n_tokens] = seq_ids.size();
1421
+ for (size_t i = 0; i < seq_ids.size(); ++i) {
1422
+ batch.seq_id[batch.n_tokens][i] = seq_ids[i];
1423
+ }
1424
+ batch.logits [batch.n_tokens] = logits;
1425
+
1426
+ batch.n_tokens++;
1427
+ }
1428
+
1429
+ //
1430
+ // Vocab utils
1431
+ //
1432
+
1433
+ std::vector<llama_token> common_tokenize(
1434
+ const struct llama_context * ctx,
1435
+ const std::string & text,
1436
+ bool add_special,
1437
+ bool parse_special) {
1438
+ const llama_model * model = llama_get_model(ctx);
1439
+ const llama_vocab * vocab = llama_model_get_vocab(model);
1440
+ return common_tokenize(vocab, text, add_special, parse_special);
1441
+ }
1442
+
1443
+ std::vector<llama_token> common_tokenize(
1444
+ const struct llama_vocab * vocab,
1445
+ const std::string & text,
1446
+ bool add_special,
1447
+ bool parse_special) {
1448
+ // upper limit for the number of tokens
1449
+ int n_tokens = text.length() + 2 * add_special;
1450
+ std::vector<llama_token> result(n_tokens);
1451
+ n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
1452
+ if (n_tokens == std::numeric_limits<int32_t>::min()) {
1453
+ throw std::runtime_error("Tokenization failed: input text too large, tokenization result exceeds int32_t limit");
1454
+ }
1455
+ if (n_tokens < 0) {
1456
+ result.resize(-n_tokens);
1457
+ int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
1458
+ GGML_ASSERT(check == -n_tokens);
1459
+ } else {
1460
+ result.resize(n_tokens);
1461
+ }
1462
+ return result;
1463
+ }
1464
+
1465
+ std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
1466
+ const llama_model * model = llama_get_model(ctx);
1467
+ const llama_vocab * vocab = llama_model_get_vocab(model);
1468
+ return common_token_to_piece(vocab, token, special);
1469
+ }
1470
+
1471
+ std::string common_token_to_piece(const struct llama_vocab * vocab, llama_token token, bool special) {
1472
+ std::string piece;
1473
+ piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
1474
+ const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
1475
+ if (n_chars < 0) {
1476
+ piece.resize(-n_chars);
1477
+ int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
1478
+ GGML_ASSERT(check == -n_chars);
1479
+ }
1480
+ else {
1481
+ piece.resize(n_chars);
1482
+ }
1483
+
1484
+ return piece;
1485
+ }
1486
+
1487
+ std::string common_detokenize(const struct llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
1488
+ const llama_model * model = llama_get_model(ctx);
1489
+ const llama_vocab * vocab = llama_model_get_vocab(model);
1490
+ return common_detokenize(vocab, tokens, special);
1491
+ }
1492
+
1493
+ std::string common_detokenize(const struct llama_vocab * vocab, const std::vector<llama_token> & tokens, bool special) {
1494
+ std::string text;
1495
+ text.resize(std::max(text.capacity(), tokens.size()));
1496
+ int32_t n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
1497
+ if (n_chars < 0) {
1498
+ text.resize(-n_chars);
1499
+ n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
1500
+ GGML_ASSERT(n_chars <= (int32_t)text.size()); // whitespace trimming is performed after per-token detokenization
1501
+ }
1502
+
1503
+ text.resize(n_chars);
1504
+
1505
+ // NOTE: the original tokenizer decodes bytes after collecting the pieces.
1506
+ return text;
1507
+ }
1508
+
1509
+ //
1510
+ // Embedding utils
1511
+ //
1512
+
1513
+ void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
1514
+ double sum = 0.0;
1515
+
1516
+ switch (embd_norm) {
1517
+ case -1: // no normalisation
1518
+ sum = 1.0;
1519
+ break;
1520
+ case 0: // max absolute
1521
+ for (int i = 0; i < n; i++) {
1522
+ if (sum < std::abs(inp[i])) {
1523
+ sum = std::abs(inp[i]);
1524
+ }
1525
+ }
1526
+ sum /= 32760.0; // make an int16 range
1527
+ break;
1528
+ case 2: // euclidean
1529
+ for (int i = 0; i < n; i++) {
1530
+ sum += inp[i] * inp[i];
1531
+ }
1532
+ sum = std::sqrt(sum);
1533
+ break;
1534
+ default: // p-norm (euclidean is p-norm p=2)
1535
+ for (int i = 0; i < n; i++) {
1536
+ sum += std::pow(std::abs(inp[i]), embd_norm);
1537
+ }
1538
+ sum = std::pow(sum, 1.0 / embd_norm);
1539
+ break;
1540
+ }
1541
+
1542
+ const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
1543
+
1544
+ for (int i = 0; i < n; i++) {
1545
+ out[i] = inp[i] * norm;
1546
+ }
1547
+ }
1548
+
1549
+ float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
1550
+ double sum = 0.0;
1551
+ double sum1 = 0.0;
1552
+ double sum2 = 0.0;
1553
+
1554
+ for (int i = 0; i < n; i++) {
1555
+ sum += embd1[i] * embd2[i];
1556
+ sum1 += embd1[i] * embd1[i];
1557
+ sum2 += embd2[i] * embd2[i];
1558
+ }
1559
+
1560
+ // Handle the case where one or both vectors are zero vectors
1561
+ if (sum1 == 0.0 || sum2 == 0.0) {
1562
+ if (sum1 == 0.0 && sum2 == 0.0) {
1563
+ return 1.0f; // two zero vectors are similar
1564
+ }
1565
+ return 0.0f;
1566
+ }
1567
+
1568
+ return sum / (sqrt(sum1) * sqrt(sum2));
1569
+ }
1570
+
1571
+ //
1572
+ // Control vector utils
1573
+ //
1574
+
1575
+ static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
1576
+ common_control_vector_data result = { -1, {} };
1577
+
1578
+ ggml_context * ctx = nullptr;
1579
+ struct gguf_init_params meta_gguf_params = {
1580
+ /* .no_alloc = */ false,
1581
+ /* .ctx = */ &ctx,
1582
+ };
1583
+ struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
1584
+ if (!ctx_gguf) {
1585
+ LOG_ERR("%s: failed to load control vector file from %s\n", __func__, load_info.fname.c_str());
1586
+ return result;
1587
+ }
1588
+
1589
+ int32_t n_tensors = gguf_get_n_tensors(ctx_gguf);
1590
+ if (n_tensors == 0) {
1591
+ LOG_WRN("%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
1592
+ }
1593
+
1594
+ for (int i = 0; i < n_tensors; i++) {
1595
+ std::string name = gguf_get_tensor_name(ctx_gguf, i);
1596
+
1597
+ int layer_idx = -1;
1598
+
1599
+ // split on '.'
1600
+ size_t dotpos = name.find('.');
1601
+ if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
1602
+ try {
1603
+ layer_idx = std::stoi(name.substr(dotpos + 1));
1604
+ } catch (...) {
1605
+ layer_idx = -1;
1606
+ }
1607
+ }
1608
+ if (layer_idx < 0) {
1609
+ LOG_ERR("%s: invalid/unparsable direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
1610
+ result.n_embd = -1;
1611
+ break;
1612
+ } else if (layer_idx == 0) {
1613
+ LOG_ERR("%s: invalid (zero) direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
1614
+ result.n_embd = -1;
1615
+ break;
1616
+ }
1617
+
1618
+ struct ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
1619
+ if (tensor->type != GGML_TYPE_F32) {
1620
+ LOG_ERR("%s: invalid (non-F32) direction tensor type in %s\n", __func__, load_info.fname.c_str());
1621
+ result.n_embd = -1;
1622
+ break;
1623
+ }
1624
+ if (ggml_n_dims(tensor) != 1) {
1625
+ LOG_ERR("%s: invalid (non-1D) direction tensor shape in %s\n", __func__, load_info.fname.c_str());
1626
+ result.n_embd = -1;
1627
+ break;
1628
+ }
1629
+
1630
+ if (result.n_embd == -1) {
1631
+ result.n_embd = ggml_nelements(tensor);
1632
+ } else if (ggml_nelements(tensor) != result.n_embd) {
1633
+ LOG_ERR("%s: direction tensor in %s does not match previous dimensions\n", __func__, load_info.fname.c_str());
1634
+ result.n_embd = -1;
1635
+ break;
1636
+ }
1637
+
1638
+ // extend if necessary - do not store data for layer 0 (it's not used)
1639
+ result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
1640
+
1641
+ const float * src = (const float *) tensor->data;
1642
+ float * dst = result.data.data() + result.n_embd * (layer_idx - 1); // layer 1 at [0]
1643
+ for (int j = 0; j < result.n_embd; j++) {
1644
+ dst[j] += src[j] * load_info.strength; // allows multiple directions for same layer in same file
1645
+ }
1646
+
1647
+ }
1648
+
1649
+ if (result.n_embd == -1) {
1650
+ LOG_WRN("%s: skipping %s due to invalid direction tensors\n", __func__, load_info.fname.c_str());
1651
+ result.data.clear();
1652
+ }
1653
+
1654
+ gguf_free(ctx_gguf);
1655
+ ggml_free(ctx);
1656
+
1657
+ return result;
1658
+ }
1659
+
1660
+ common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
1661
+ common_control_vector_data result = { -1, {} };
1662
+
1663
+ for (const auto & info : load_infos) {
1664
+ auto cur = common_control_vector_load_one(info);
1665
+
1666
+ if (cur.n_embd == -1) {
1667
+ result.n_embd = -1;
1668
+ break;
1669
+ }
1670
+ if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
1671
+ LOG_ERR("%s: control vectors in %s does not match previous dimensions\n", __func__, info.fname.c_str());
1672
+ result.n_embd = -1;
1673
+ break;
1674
+ }
1675
+
1676
+ if (result.n_embd == -1) {
1677
+ result = std::move(cur);
1678
+ } else {
1679
+ result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f); // extend if necessary
1680
+ for (size_t i = 0; i < cur.data.size(); i++) {
1681
+ result.data[i] += cur.data[i];
1682
+ }
1683
+ }
1684
+ }
1685
+
1686
+ if (result.n_embd == -1) {
1687
+ LOG_ERR("%s: no valid control vector files passed\n", __func__);
1688
+ result.data.clear();
1689
+ }
1690
+
1691
+ return result;
1692
+ }
1693
+
1694
+ ggml_opt_dataset_t common_opt_dataset_init(struct llama_context * ctx, const std::vector<llama_token> & tokens, int64_t stride) {
1695
+ const int64_t ne_datapoint = llama_n_ctx(ctx);
1696
+ const int64_t ndata = (tokens.size() - ne_datapoint - 1) / stride;
1697
+ ggml_opt_dataset_t result = ggml_opt_dataset_init(
1698
+ GGML_TYPE_I32, GGML_TYPE_I32, ne_datapoint, ne_datapoint, ndata, /*ndata_shard =*/ 1);
1699
+
1700
+ llama_token * data = (llama_token *) ggml_opt_dataset_data(result)->data;
1701
+ llama_token * labels = (llama_token *) ggml_opt_dataset_labels(result)->data;
1702
+
1703
+ for (int64_t idata = 0; idata < ndata; ++idata) {
1704
+ memcpy(data + idata*ne_datapoint, tokens.data() + idata*stride + 0, ne_datapoint*sizeof(llama_token));
1705
+ memcpy(labels + idata*ne_datapoint, tokens.data() + idata*stride + 1, ne_datapoint*sizeof(llama_token));
1706
+ }
1707
+
1708
+ return result;
1709
+ }
1710
+
1711
+ ggml_opt_optimizer_params common_opt_lr_pars(void * userdata) {
1712
+ ggml_opt_optimizer_params result = ggml_opt_get_default_optimizer_params(nullptr);
1713
+ const lr_opt & d = *(lr_opt *) userdata;
1714
+ result.adamw.alpha = result.sgd.alpha = d.get_lr(d.epoch);
1715
+ result.sgd.wd = result.adamw.wd = d.wd;
1716
+ return result;
1717
+ }
1718
+
1719
+ // TODO make all command line args case-insensitive
1720
+ static inline bool eq_case_insensitive(char const* a, char const* b) {
1721
+ return !
1722
+ #if defined(_MSC_VER)
1723
+ _stricmp
1724
+ #else
1725
+ strcasecmp
1726
+ #endif // defined(_MSC_VER)
1727
+ (a, b);
1728
+ }
1729
+
1730
+ enum ggml_opt_optimizer_type common_opt_get_optimizer(const char * n) {
1731
+ if (eq_case_insensitive("adamw", n)) {
1732
+ return GGML_OPT_OPTIMIZER_TYPE_ADAMW;
1733
+ }
1734
+ if (eq_case_insensitive("sgd", n)) {
1735
+ return GGML_OPT_OPTIMIZER_TYPE_SGD;
1736
+ }
1737
+ return GGML_OPT_OPTIMIZER_TYPE_COUNT;
1738
+ }
1739
+
1740
+ // TODO simplify to use just log and exp
1741
+ static float const k_log_2 = std::log(2.f);
1742
+
1743
+ void lr_opt::init() {
1744
+ if (lr_min > 0 && lr_min < lr0) {
1745
+ float nhalf = std::log(lr0 / lr_min) / k_log_2;
1746
+ float e = epochs;
1747
+ if (decay_epochs > 0 && decay_epochs < e) {
1748
+ e = decay_epochs;
1749
+ } else {
1750
+ decay_epochs = e;
1751
+ }
1752
+ scale_epoch = nhalf / e;
1753
+ }
1754
+ }
1755
+
1756
+ float lr_opt::get_lr(float epoch) const {
1757
+ float r = lr_min <= 0 ? lr0 :
1758
+ epoch >= decay_epochs ? lr_min :
1759
+ lr0 * std::pow(0.5f, epoch * scale_epoch);
1760
+ LOG_INF("epoch %.2g lr=%.2g\n", epoch, r);
1761
+ return r;
1762
+ }
1763
+
1764
+ bool common_replay_last_token(struct llama_context * ctx, llama_token last_token, int32_t pos) {
1765
+ llama_batch batch = llama_batch_get_one(&last_token, 1);
1766
+ batch.pos = &pos;
1767
+ if (llama_decode(ctx, batch)) {
1768
+ LOG_ERR("%s: failed to replay last token\n", __func__);
1769
+ return false;
1770
+ }
1771
+ return true;
1772
+ }
1773
+
1774
+ bool common_prompt_batch_decode(
1775
+ struct llama_context * ctx,
1776
+ const std::vector<llama_token> & tokens,
1777
+ int & n_past,
1778
+ int n_batch,
1779
+ std::string_view state_path,
1780
+ bool save_state) {
1781
+ const int n_eval = tokens.size();
1782
+ if (n_eval == 0) {
1783
+ return true;
1784
+ }
1785
+
1786
+ if (save_state && n_eval > 1) {
1787
+ const int n_tokens_before_last = n_eval - 1;
1788
+
1789
+ GGML_ASSERT(n_eval <= n_batch);
1790
+
1791
+ // Decode all but the last token so we can save the memory state before decoding the last token.
1792
+ // This is done so we can restore the session state later and replay the last token.
1793
+ // Memory implementations in recurrent/hybrid models don't support removing tokens from their
1794
+ // memory, so we can't just remove the last token from the memory and replay the last token which
1795
+ // is the reason for this logic.
1796
+ if (llama_decode(ctx, llama_batch_get_one(const_cast<llama_token*>(tokens.data()), n_tokens_before_last))) {
1797
+ LOG_ERR("%s : failed to eval\n", __func__);
1798
+ return false;
1799
+ }
1800
+ n_past += n_tokens_before_last;
1801
+
1802
+ llama_state_save_file(ctx, state_path.data(), tokens.data(), n_tokens_before_last);
1803
+ LOG_INF("saved session before last token to %s, n_tokens = %d\n", state_path.data(), n_tokens_before_last);
1804
+
1805
+ llama_token last_token = tokens.back();
1806
+ llama_batch batch = llama_batch_get_one(&last_token, 1);
1807
+ int32_t pos = n_past;
1808
+ batch.pos = &pos;
1809
+
1810
+ if (llama_decode(ctx, batch)) {
1811
+ LOG_ERR("%s : failed to eval last token\n", __func__);
1812
+ return false;
1813
+ }
1814
+ n_past++;
1815
+ } else {
1816
+ if (llama_decode(ctx, llama_batch_get_one(const_cast<llama_token*>(tokens.data()), n_eval))) {
1817
+ LOG_ERR("%s : failed to eval\n", __func__);
1818
+ return false;
1819
+ }
1820
+ n_past += n_eval;
1821
+ }
1822
+
1823
+ return true;
1824
+ }