whispercpp 1.3.6 → 1.3.7

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 (828) hide show
  1. checksums.yaml +4 -4
  2. data/.document +3 -0
  3. data/.rdoc_options +2 -0
  4. data/README.md +38 -5
  5. data/Rakefile +18 -3
  6. data/ext/dependencies.rb +10 -4
  7. data/ext/dependencies_for_windows.rb +17 -0
  8. data/ext/extconf.rb +20 -8
  9. data/ext/options.rb +54 -14
  10. data/ext/options_for_windows.rb +51 -0
  11. data/ext/ruby_whisper.c +36 -42
  12. data/ext/ruby_whisper.h +135 -0
  13. data/ext/ruby_whisper_context.c +107 -28
  14. data/ext/ruby_whisper_log_queue.c +180 -0
  15. data/ext/ruby_whisper_log_settable.h +47 -0
  16. data/ext/ruby_whisper_parakeet.c +49 -0
  17. data/ext/ruby_whisper_parakeet_context.c +304 -0
  18. data/ext/ruby_whisper_parakeet_context_params.c +117 -0
  19. data/ext/ruby_whisper_parakeet_model.c +84 -0
  20. data/ext/ruby_whisper_parakeet_params.c +548 -0
  21. data/ext/ruby_whisper_parakeet_segment.c +157 -0
  22. data/ext/ruby_whisper_parakeet_token.c +188 -0
  23. data/ext/ruby_whisper_parakeet_transcribe.cpp +58 -0
  24. data/ext/ruby_whisper_params.c +256 -65
  25. data/ext/ruby_whisper_segment.c +6 -6
  26. data/ext/ruby_whisper_transcribe.cpp +42 -15
  27. data/ext/sources/CMakeLists.txt +41 -3
  28. data/ext/sources/CMakePresets.json +95 -0
  29. data/ext/sources/cmake/parakeet-config.cmake.in +30 -0
  30. data/ext/sources/cmake/parakeet.pc.in +10 -0
  31. data/ext/sources/cmake/whisper.pc.in +1 -1
  32. data/ext/sources/examples/CMakeLists.txt +4 -2
  33. data/ext/sources/examples/bench/bench.cpp +1 -1
  34. data/ext/sources/examples/cli/cli.cpp +43 -9
  35. data/ext/sources/examples/common-ggml.cpp +2 -0
  36. data/ext/sources/examples/common-whisper.cpp +139 -67
  37. data/ext/sources/examples/common-whisper.h +11 -0
  38. data/ext/sources/examples/ffmpeg-transcode.cpp +211 -341
  39. data/ext/sources/examples/parakeet-cli/CMakeLists.txt +8 -0
  40. data/ext/sources/examples/parakeet-cli/parakeet-cli.cpp +243 -0
  41. data/ext/sources/examples/parakeet-quantize/CMakeLists.txt +7 -0
  42. data/ext/sources/examples/parakeet-quantize/parakeet-quantize.cpp +230 -0
  43. data/ext/sources/examples/server/server.cpp +199 -163
  44. data/ext/sources/ggml/CMakeLists.txt +21 -13
  45. data/ext/sources/ggml/cmake/FindNCCL.cmake +36 -0
  46. data/ext/sources/ggml/cmake/ggml-config.cmake.in +12 -2
  47. data/ext/sources/ggml/include/ggml-alloc.h +1 -0
  48. data/ext/sources/ggml/include/ggml-backend.h +72 -10
  49. data/ext/sources/ggml/include/ggml-cuda.h +3 -0
  50. data/ext/sources/ggml/include/ggml-rpc.h +3 -3
  51. data/ext/sources/ggml/include/ggml.h +101 -9
  52. data/ext/sources/ggml/include/gguf.h +10 -2
  53. data/ext/sources/ggml/src/CMakeLists.txt +22 -5
  54. data/ext/sources/ggml/src/ggml-alloc.c +5 -1
  55. data/ext/sources/ggml/src/ggml-backend-impl.h +22 -2
  56. data/ext/sources/ggml/src/ggml-backend-meta.cpp +2263 -0
  57. data/ext/sources/ggml/src/ggml-backend-reg.cpp +12 -0
  58. data/ext/sources/ggml/src/ggml-backend.cpp +110 -9
  59. data/ext/sources/ggml/src/ggml-blas/ggml-blas.cpp +4 -0
  60. data/ext/sources/ggml/src/ggml-cann/aclnn_ops.cpp +672 -257
  61. data/ext/sources/ggml/src/ggml-cann/aclnn_ops.h +71 -0
  62. data/ext/sources/ggml/src/ggml-cann/common.h +20 -10
  63. data/ext/sources/ggml/src/ggml-cann/ggml-cann.cpp +211 -30
  64. data/ext/sources/ggml/src/ggml-common.h +11 -0
  65. data/ext/sources/ggml/src/ggml-cpu/CMakeLists.txt +58 -29
  66. data/ext/sources/ggml/src/ggml-cpu/amx/amx.cpp +2 -0
  67. data/ext/sources/ggml/src/ggml-cpu/amx/mmq.cpp +16 -16
  68. data/ext/sources/ggml/src/ggml-cpu/arch/arm/quants.c +116 -7
  69. data/ext/sources/ggml/src/ggml-cpu/arch/arm/repack.cpp +65 -0
  70. data/ext/sources/ggml/src/ggml-cpu/arch/loongarch/quants.c +151 -1
  71. data/ext/sources/ggml/src/ggml-cpu/arch/powerpc/quants.c +0 -1
  72. data/ext/sources/ggml/src/ggml-cpu/arch/riscv/quants.c +4279 -1292
  73. data/ext/sources/ggml/src/ggml-cpu/arch/riscv/repack.cpp +5 -35
  74. data/ext/sources/ggml/src/ggml-cpu/arch/s390/quants.c +0 -1
  75. data/ext/sources/ggml/src/ggml-cpu/arch/wasm/quants.c +72 -1
  76. data/ext/sources/ggml/src/ggml-cpu/arch/x86/quants.c +177 -27
  77. data/ext/sources/ggml/src/ggml-cpu/arch/x86/repack.cpp +1 -1
  78. data/ext/sources/ggml/src/ggml-cpu/arch-fallback.h +5 -0
  79. data/ext/sources/ggml/src/ggml-cpu/cmake/FindSMTIME.cmake +32 -0
  80. data/ext/sources/ggml/src/ggml-cpu/ggml-cpu-impl.h +10 -0
  81. data/ext/sources/ggml/src/ggml-cpu/ggml-cpu.c +95 -5
  82. data/ext/sources/ggml/src/ggml-cpu/ggml-cpu.cpp +2 -0
  83. data/ext/sources/ggml/src/ggml-cpu/kleidiai/kleidiai.cpp +146 -134
  84. data/ext/sources/ggml/src/ggml-cpu/llamafile/sgemm.cpp +88 -70
  85. data/ext/sources/ggml/src/ggml-cpu/ops.cpp +372 -73
  86. data/ext/sources/ggml/src/ggml-cpu/ops.h +3 -0
  87. data/ext/sources/ggml/src/ggml-cpu/quants.c +55 -0
  88. data/ext/sources/ggml/src/ggml-cpu/quants.h +3 -0
  89. data/ext/sources/ggml/src/ggml-cpu/repack.cpp +3 -0
  90. data/ext/sources/ggml/src/ggml-cpu/simd-gemm.h +90 -0
  91. data/ext/sources/ggml/src/ggml-cpu/simd-mappings.h +3 -16
  92. data/ext/sources/ggml/src/ggml-cpu/spacemit/ime.cpp +1402 -687
  93. data/ext/sources/ggml/src/ggml-cpu/spacemit/ime.h +8 -0
  94. data/ext/sources/ggml/src/ggml-cpu/spacemit/ime1_kernels.cpp +597 -2766
  95. data/ext/sources/ggml/src/ggml-cpu/spacemit/ime2_kernels.cpp +5768 -0
  96. data/ext/sources/ggml/src/ggml-cpu/spacemit/ime_env.cpp +320 -0
  97. data/ext/sources/ggml/src/ggml-cpu/spacemit/ime_env.h +55 -0
  98. data/ext/sources/ggml/src/ggml-cpu/spacemit/ime_kernels.h +182 -19
  99. data/ext/sources/ggml/src/ggml-cpu/spacemit/repack.cpp +1795 -0
  100. data/ext/sources/ggml/src/ggml-cpu/spacemit/repack.h +14 -0
  101. data/ext/sources/ggml/src/ggml-cpu/spacemit/rvv_kernels.cpp +3178 -0
  102. data/ext/sources/ggml/src/ggml-cpu/spacemit/rvv_kernels.h +95 -0
  103. data/ext/sources/ggml/src/ggml-cpu/spacemit/spine_barrier.h +34 -0
  104. data/ext/sources/ggml/src/ggml-cpu/spacemit/spine_mem_pool.cpp +760 -0
  105. data/ext/sources/ggml/src/ggml-cpu/spacemit/spine_mem_pool.h +32 -0
  106. data/ext/sources/ggml/src/ggml-cpu/spacemit/spine_tcm.h +409 -0
  107. data/ext/sources/ggml/src/ggml-cpu/vec.cpp +37 -53
  108. data/ext/sources/ggml/src/ggml-cpu/vec.h +225 -240
  109. data/ext/sources/ggml/src/ggml-cuda/CMakeLists.txt +17 -7
  110. data/ext/sources/ggml/src/ggml-cuda/allreduce.cu +971 -0
  111. data/ext/sources/ggml/src/ggml-cuda/allreduce.cuh +29 -0
  112. data/ext/sources/ggml/src/ggml-cuda/argsort.cu +62 -26
  113. data/ext/sources/ggml/src/ggml-cuda/binbcast.cu +44 -18
  114. data/ext/sources/ggml/src/ggml-cuda/binbcast.cuh +1 -0
  115. data/ext/sources/ggml/src/ggml-cuda/common.cuh +242 -28
  116. data/ext/sources/ggml/src/ggml-cuda/concat.cu +120 -114
  117. data/ext/sources/ggml/src/ggml-cuda/conv2d-transpose.cu +45 -21
  118. data/ext/sources/ggml/src/ggml-cuda/conv2d-transpose.cuh +1 -0
  119. data/ext/sources/ggml/src/ggml-cuda/convert.cu +53 -0
  120. data/ext/sources/ggml/src/ggml-cuda/convert.cuh +10 -0
  121. data/ext/sources/ggml/src/ggml-cuda/cpy.cu +14 -6
  122. data/ext/sources/ggml/src/ggml-cuda/dequantize.cuh +22 -0
  123. data/ext/sources/ggml/src/ggml-cuda/fattn-common.cuh +278 -44
  124. data/ext/sources/ggml/src/ggml-cuda/fattn-mma-f16.cuh +331 -130
  125. data/ext/sources/ggml/src/ggml-cuda/fattn-tile.cu +12 -0
  126. data/ext/sources/ggml/src/ggml-cuda/fattn-tile.cuh +126 -27
  127. data/ext/sources/ggml/src/ggml-cuda/fattn-vec.cuh +40 -15
  128. data/ext/sources/ggml/src/ggml-cuda/fattn-wmma-f16.cu +18 -9
  129. data/ext/sources/ggml/src/ggml-cuda/fattn.cu +152 -49
  130. data/ext/sources/ggml/src/ggml-cuda/fattn.cuh +2 -0
  131. data/ext/sources/ggml/src/ggml-cuda/fwht.cu +101 -0
  132. data/ext/sources/ggml/src/ggml-cuda/fwht.cuh +4 -0
  133. data/ext/sources/ggml/src/ggml-cuda/gated_delta_net.cu +84 -35
  134. data/ext/sources/ggml/src/ggml-cuda/getrows.cu +34 -12
  135. data/ext/sources/ggml/src/ggml-cuda/ggml-cuda.cu +1069 -609
  136. data/ext/sources/ggml/src/ggml-cuda/im2col.cu +32 -29
  137. data/ext/sources/ggml/src/ggml-cuda/mean.cu +4 -2
  138. data/ext/sources/ggml/src/ggml-cuda/mma.cuh +242 -195
  139. data/ext/sources/ggml/src/ggml-cuda/mmf.cuh +3 -3
  140. data/ext/sources/ggml/src/ggml-cuda/mmq.cu +18 -12
  141. data/ext/sources/ggml/src/ggml-cuda/mmq.cuh +502 -423
  142. data/ext/sources/ggml/src/ggml-cuda/mmvf.cu +19 -12
  143. data/ext/sources/ggml/src/ggml-cuda/mmvq.cu +485 -57
  144. data/ext/sources/ggml/src/ggml-cuda/mmvq.cuh +6 -1
  145. data/ext/sources/ggml/src/ggml-cuda/norm.cu +36 -10
  146. data/ext/sources/ggml/src/ggml-cuda/out-prod.cu +23 -7
  147. data/ext/sources/ggml/src/ggml-cuda/quantize.cu +133 -26
  148. data/ext/sources/ggml/src/ggml-cuda/quantize.cuh +1 -1
  149. data/ext/sources/ggml/src/ggml-cuda/reduce_rows.cuh +5 -1
  150. data/ext/sources/ggml/src/ggml-cuda/rope.cu +11 -4
  151. data/ext/sources/ggml/src/ggml-cuda/scale.cu +4 -1
  152. data/ext/sources/ggml/src/ggml-cuda/set-rows.cu +14 -6
  153. data/ext/sources/ggml/src/ggml-cuda/snake.cu +72 -0
  154. data/ext/sources/ggml/src/ggml-cuda/snake.cuh +8 -0
  155. data/ext/sources/ggml/src/ggml-cuda/softcap.cu +4 -1
  156. data/ext/sources/ggml/src/ggml-cuda/ssm-conv.cu +45 -13
  157. data/ext/sources/ggml/src/ggml-cuda/ssm-conv.cuh +1 -1
  158. data/ext/sources/ggml/src/ggml-cuda/ssm-scan.cu +40 -18
  159. data/ext/sources/ggml/src/ggml-cuda/sumrows.cu +8 -4
  160. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_16.cu +1 -0
  161. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_32.cu +1 -0
  162. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_8.cu +2 -0
  163. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_4.cu +1 -0
  164. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_16.cu +1 -0
  165. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_32.cu +1 -0
  166. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_4.cu +1 -0
  167. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_8.cu +2 -0
  168. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_16.cu +1 -0
  169. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_4.cu +1 -0
  170. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_8.cu +2 -0
  171. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_4.cu +1 -0
  172. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_8.cu +2 -0
  173. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq192-dv128.cu +5 -0
  174. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq320-dv256.cu +5 -0
  175. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq512-dv512.cu +5 -0
  176. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-bf16-bf16.cu +7 -0
  177. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-bf16-f16.cu +7 -0
  178. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-bf16-q4_0.cu +7 -0
  179. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-bf16-q4_1.cu +7 -0
  180. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-bf16-q5_0.cu +7 -0
  181. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-bf16-q5_1.cu +7 -0
  182. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-bf16-q8_0.cu +7 -0
  183. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-f16-bf16.cu +7 -0
  184. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-q4_0-bf16.cu +7 -0
  185. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-q4_1-bf16.cu +7 -0
  186. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-q5_0-bf16.cu +7 -0
  187. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-q5_1-bf16.cu +7 -0
  188. data/ext/sources/ggml/src/ggml-cuda/template-instances/fattn-vec-instance-q8_0-bf16.cu +7 -0
  189. data/ext/sources/ggml/src/ggml-cuda/template-instances/mmq-instance-nvfp4.cu +5 -0
  190. data/ext/sources/ggml/src/ggml-cuda/template-instances/mmq-instance-q1_0.cu +5 -0
  191. data/ext/sources/ggml/src/ggml-cuda/top-k.cu +5 -4
  192. data/ext/sources/ggml/src/ggml-cuda/topk-moe.cu +26 -23
  193. data/ext/sources/ggml/src/ggml-cuda/unary.cu +31 -2
  194. data/ext/sources/ggml/src/ggml-cuda/unary.cuh +2 -0
  195. data/ext/sources/ggml/src/ggml-cuda/vecdotq.cuh +80 -0
  196. data/ext/sources/ggml/src/ggml-cuda/vendors/cuda.h +7 -2
  197. data/ext/sources/ggml/src/ggml-cuda/vendors/hip.h +22 -4
  198. data/ext/sources/ggml/src/ggml-cuda/vendors/musa.h +3 -0
  199. data/ext/sources/ggml/src/ggml-hexagon/CMakeLists.txt +2 -1
  200. data/ext/sources/ggml/src/ggml-hexagon/ggml-hexagon.cpp +1428 -743
  201. data/ext/sources/ggml/src/ggml-hexagon/htp/CMakeLists.txt +45 -7
  202. data/ext/sources/ggml/src/ggml-hexagon/htp/act-ops.c +53 -84
  203. data/ext/sources/ggml/src/ggml-hexagon/htp/argsort-ops.c +25 -12
  204. data/ext/sources/ggml/src/ggml-hexagon/htp/binary-ops.c +165 -184
  205. data/ext/sources/ggml/src/ggml-hexagon/htp/cmake-toolchain.cmake +5 -5
  206. data/ext/sources/ggml/src/ggml-hexagon/htp/concat-ops.c +277 -0
  207. data/ext/sources/ggml/src/ggml-hexagon/htp/cpy-ops.c +170 -127
  208. data/ext/sources/ggml/src/ggml-hexagon/htp/cumsum-ops.c +270 -0
  209. data/ext/sources/ggml/src/ggml-hexagon/htp/diag-ops.c +216 -0
  210. data/ext/sources/ggml/src/ggml-hexagon/htp/fill-ops.c +123 -0
  211. data/ext/sources/ggml/src/ggml-hexagon/htp/flash-attn-ops.c +125 -97
  212. data/ext/sources/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c +1148 -0
  213. data/ext/sources/ggml/src/ggml-hexagon/htp/get-rows-ops.c +148 -42
  214. data/ext/sources/ggml/src/ggml-hexagon/htp/hex-dma.c +2 -2
  215. data/ext/sources/ggml/src/ggml-hexagon/htp/hex-dma.h +252 -62
  216. data/ext/sources/ggml/src/ggml-hexagon/htp/hex-dump.h +9 -0
  217. data/ext/sources/ggml/src/ggml-hexagon/htp/hex-utils.h +87 -1
  218. data/ext/sources/ggml/src/ggml-hexagon/htp/hmx-flash-attn-ops.c +1878 -0
  219. data/ext/sources/ggml/src/ggml-hexagon/htp/hmx-matmul-ops.c +2066 -0
  220. data/ext/sources/ggml/src/ggml-hexagon/htp/hmx-ops.c +6 -0
  221. data/ext/sources/ggml/src/ggml-hexagon/htp/hmx-ops.h +88 -0
  222. data/ext/sources/ggml/src/ggml-hexagon/htp/hmx-profile.h +34 -0
  223. data/ext/sources/ggml/src/ggml-hexagon/htp/hmx-queue.c +158 -0
  224. data/ext/sources/ggml/src/ggml-hexagon/htp/hmx-queue.h +134 -0
  225. data/ext/sources/ggml/src/ggml-hexagon/htp/hmx-utils.h +200 -0
  226. data/ext/sources/ggml/src/ggml-hexagon/htp/htp-ctx.h +96 -13
  227. data/ext/sources/ggml/src/ggml-hexagon/htp/htp-ops.h +182 -57
  228. data/ext/sources/ggml/src/ggml-hexagon/htp/htp_iface.idl +9 -3
  229. data/ext/sources/ggml/src/ggml-hexagon/htp/hvx-base.h +71 -3
  230. data/ext/sources/ggml/src/ggml-hexagon/htp/hvx-copy.h +27 -10
  231. data/ext/sources/ggml/src/ggml-hexagon/htp/hvx-div.h +63 -23
  232. data/ext/sources/ggml/src/ggml-hexagon/htp/hvx-exp.h +9 -8
  233. data/ext/sources/ggml/src/ggml-hexagon/htp/hvx-flash-attn.h +47 -0
  234. data/ext/sources/ggml/src/ggml-hexagon/htp/hvx-log.h +65 -0
  235. data/ext/sources/ggml/src/ggml-hexagon/htp/hvx-pow.h +42 -0
  236. data/ext/sources/ggml/src/ggml-hexagon/htp/hvx-repl.h +74 -0
  237. data/ext/sources/ggml/src/ggml-hexagon/htp/hvx-sigmoid.h +1 -0
  238. data/ext/sources/ggml/src/ggml-hexagon/htp/hvx-sin-cos.h +90 -0
  239. data/ext/sources/ggml/src/ggml-hexagon/htp/hvx-utils.h +5 -8
  240. data/ext/sources/ggml/src/ggml-hexagon/htp/main.c +529 -815
  241. data/ext/sources/ggml/src/ggml-hexagon/htp/matmul-ops.c +2522 -234
  242. data/ext/sources/ggml/src/ggml-hexagon/htp/pad-ops.c +547 -0
  243. data/ext/sources/ggml/src/ggml-hexagon/htp/repeat-ops.c +148 -0
  244. data/ext/sources/ggml/src/ggml-hexagon/htp/rope-ops.c +291 -95
  245. data/ext/sources/ggml/src/ggml-hexagon/htp/set-rows-ops.c +59 -37
  246. data/ext/sources/ggml/src/ggml-hexagon/htp/softmax-ops.c +121 -133
  247. data/ext/sources/ggml/src/ggml-hexagon/htp/solve-tri-ops.c +267 -0
  248. data/ext/sources/ggml/src/ggml-hexagon/htp/ssm-conv.c +244 -151
  249. data/ext/sources/ggml/src/ggml-hexagon/htp/sum-rows-ops.c +6 -6
  250. data/ext/sources/ggml/src/ggml-hexagon/htp/unary-ops.c +719 -45
  251. data/ext/sources/ggml/src/ggml-hexagon/htp/vtcm-utils.h +16 -0
  252. data/ext/sources/ggml/src/ggml-hexagon/htp-opnode.h +272 -0
  253. data/ext/sources/ggml/src/ggml-hexagon/libggml-htp.inf +3 -1
  254. data/ext/sources/ggml/src/ggml-hip/CMakeLists.txt +22 -9
  255. data/ext/sources/ggml/src/ggml-impl.h +6 -1
  256. data/ext/sources/ggml/src/ggml-metal/ggml-metal-device.cpp +138 -13
  257. data/ext/sources/ggml/src/ggml-metal/ggml-metal-device.h +32 -1
  258. data/ext/sources/ggml/src/ggml-metal/ggml-metal-device.m +164 -28
  259. data/ext/sources/ggml/src/ggml-metal/ggml-metal-impl.h +80 -0
  260. data/ext/sources/ggml/src/ggml-metal/ggml-metal-ops.cpp +190 -19
  261. data/ext/sources/ggml/src/ggml-metal/ggml-metal-ops.h +2 -0
  262. data/ext/sources/ggml/src/ggml-metal/ggml-metal.cpp +39 -26
  263. data/ext/sources/ggml/src/ggml-metal/ggml-metal.metal +823 -322
  264. data/ext/sources/ggml/src/ggml-musa/CMakeLists.txt +5 -6
  265. data/ext/sources/ggml/src/ggml-opencl/CMakeLists.txt +54 -5
  266. data/ext/sources/ggml/src/ggml-opencl/ggml-opencl.cpp +12248 -5907
  267. data/ext/sources/ggml/src/ggml-opencl/kernels/concat.cl +67 -0
  268. data/ext/sources/ggml/src/ggml-opencl/kernels/cpy.cl +59 -0
  269. data/ext/sources/ggml/src/ggml-opencl/kernels/cvt.cl +1819 -112
  270. data/ext/sources/ggml/src/ggml-opencl/kernels/gated_delta_net.cl +249 -0
  271. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_moe_mxfp4_f32_ns.cl +306 -0
  272. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_moe_q4_0_f32_ns.cl +256 -0
  273. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_moe_q4_1_f32_ns.cl +258 -0
  274. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_moe_q4_k_f32_ns.cl +283 -0
  275. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_moe_q5_0_f32_ns.cl +260 -0
  276. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_moe_q5_1_f32_ns.cl +262 -0
  277. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_moe_q5_k_f32_ns.cl +288 -0
  278. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_moe_q6_k_f32_ns.cl +267 -0
  279. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_noshuffle_iq4_nl_f32.cl +150 -0
  280. data/ext/sources/ggml/src/ggml-opencl/kernels/{mul_mat_Ab_Bi_8x4.cl → gemm_noshuffle_q4_0_f32.cl} +1 -1
  281. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_k_f32.cl +172 -0
  282. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_0_f32.cl +131 -0
  283. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_1_f32.cl +134 -0
  284. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_k_f32.cl +176 -0
  285. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q6_k_f32.cl +140 -0
  286. data/ext/sources/ggml/src/ggml-opencl/kernels/{mul_mm_q8_0_f32_8x4.cl → gemm_noshuffle_q8_0_f32.cl} +1 -1
  287. data/ext/sources/ggml/src/ggml-opencl/kernels/gemm_xmem_f16_f32_os8.cl +233 -0
  288. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_moe_mxfp4_f32_ns.cl +165 -0
  289. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_moe_q4_0_f32_ns.cl +120 -0
  290. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_moe_q4_1_f32_ns.cl +123 -0
  291. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_moe_q4_k_f32_ns.cl +155 -0
  292. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_moe_q5_0_f32_ns.cl +123 -0
  293. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_moe_q5_1_f32_ns.cl +125 -0
  294. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_moe_q5_k_f32_ns.cl +160 -0
  295. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_moe_q6_k_f32_ns.cl +141 -0
  296. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_noshuffle_iq4_nl_f32.cl +302 -0
  297. data/ext/sources/ggml/src/ggml-opencl/kernels/{gemv_noshuffle_general.cl → gemv_noshuffle_q4_0_f32.cl} +5 -5
  298. data/ext/sources/ggml/src/ggml-opencl/kernels/{gemv_noshuffle.cl → gemv_noshuffle_q4_0_f32_spec.cl} +5 -5
  299. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_noshuffle_q4_k_f32.cl +318 -0
  300. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_noshuffle_q5_0_f32.cl +291 -0
  301. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_noshuffle_q5_1_f32.cl +294 -0
  302. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_noshuffle_q5_k_f32.cl +326 -0
  303. data/ext/sources/ggml/src/ggml-opencl/kernels/gemv_noshuffle_q6_k_f32.cl +293 -0
  304. data/ext/sources/ggml/src/ggml-opencl/kernels/get_rows.cl +15 -9
  305. data/ext/sources/ggml/src/ggml-opencl/kernels/moe_reorder_b.cl +30 -0
  306. data/ext/sources/ggml/src/ggml-opencl/kernels/moe_sort_by_expert.cl +82 -0
  307. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mm_iq4_nl_f32_l4_lm.cl +171 -0
  308. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mm_q4_k_f32_l4_lm.cl +179 -0
  309. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mm_q5_0_f32_l4_lm.cl +173 -0
  310. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mm_q5_1_f32_l4_lm.cl +175 -0
  311. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mm_q5_k_f32_l4_lm.cl +192 -0
  312. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mv_iq4_nl_f32.cl +164 -0
  313. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mv_iq4_nl_f32_flat.cl +202 -0
  314. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mv_q4_k_f32_flat.cl +196 -0
  315. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mv_q5_0_f32.cl +241 -0
  316. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mv_q5_0_f32_flat.cl +243 -0
  317. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mv_q5_1_f32.cl +243 -0
  318. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mv_q5_1_f32_flat.cl +247 -0
  319. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mv_q5_k_f32.cl +187 -0
  320. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mv_q5_k_f32_flat.cl +203 -0
  321. data/ext/sources/ggml/src/ggml-opencl/kernels/mul_mv_q6_k_f32_flat.cl +48 -64
  322. data/ext/sources/ggml/src/ggml-openvino/ggml-decoder.cpp +15 -5
  323. data/ext/sources/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +18 -11
  324. data/ext/sources/ggml/src/ggml-openvino/ggml-openvino.cpp +35 -13
  325. data/ext/sources/ggml/src/ggml-openvino/ggml-quants.cpp +264 -192
  326. data/ext/sources/ggml/src/ggml-openvino/openvino/op/rope.cpp +33 -7
  327. data/ext/sources/ggml/src/ggml-openvino/openvino/op/unary_gelu.cpp +25 -0
  328. data/ext/sources/ggml/src/ggml-openvino/openvino/op_table.cpp +1 -0
  329. data/ext/sources/ggml/src/ggml-openvino/openvino/op_table.h +1 -0
  330. data/ext/sources/ggml/src/ggml-openvino/openvino/rt_info/weightless_caching_attributes.hpp +41 -0
  331. data/ext/sources/ggml/src/ggml-openvino/openvino/translate_session.cpp +27 -3
  332. data/ext/sources/ggml/src/ggml-openvino/openvino/utils.cpp +67 -36
  333. data/ext/sources/ggml/src/ggml-openvino/openvino/utils.h +1 -0
  334. data/ext/sources/ggml/src/ggml-openvino/utils.cpp +101 -44
  335. data/ext/sources/ggml/src/ggml-openvino/utils.h +23 -3
  336. data/ext/sources/ggml/src/ggml-opt.cpp +1 -0
  337. data/ext/sources/ggml/src/ggml-quants.c +289 -114
  338. data/ext/sources/ggml/src/ggml-quants.h +3 -0
  339. data/ext/sources/ggml/src/ggml-rpc/CMakeLists.txt +24 -0
  340. data/ext/sources/ggml/src/ggml-rpc/ggml-rpc.cpp +167 -311
  341. data/ext/sources/ggml/src/ggml-rpc/transport.cpp +683 -0
  342. data/ext/sources/ggml/src/ggml-rpc/transport.h +34 -0
  343. data/ext/sources/ggml/src/ggml-sycl/CMakeLists.txt +50 -4
  344. data/ext/sources/ggml/src/ggml-sycl/add-id.cpp +1 -1
  345. data/ext/sources/ggml/src/ggml-sycl/backend.hpp +3 -1
  346. data/ext/sources/ggml/src/ggml-sycl/common.cpp +74 -2
  347. data/ext/sources/ggml/src/ggml-sycl/common.hpp +41 -1
  348. data/ext/sources/ggml/src/ggml-sycl/convert.cpp +115 -13
  349. data/ext/sources/ggml/src/ggml-sycl/convert.hpp +9 -0
  350. data/ext/sources/ggml/src/ggml-sycl/cumsum.cpp +148 -0
  351. data/ext/sources/ggml/src/ggml-sycl/cumsum.hpp +5 -0
  352. data/ext/sources/ggml/src/ggml-sycl/dequantize.hpp +663 -0
  353. data/ext/sources/ggml/src/ggml-sycl/diag.cpp +67 -0
  354. data/ext/sources/ggml/src/ggml-sycl/diag.hpp +5 -0
  355. data/ext/sources/ggml/src/ggml-sycl/dmmv.cpp +586 -6
  356. data/ext/sources/ggml/src/ggml-sycl/element_wise.cpp +1 -90
  357. data/ext/sources/ggml/src/ggml-sycl/element_wise.hpp +0 -2
  358. data/ext/sources/ggml/src/ggml-sycl/fattn-buffers.cpp +56 -0
  359. data/ext/sources/ggml/src/ggml-sycl/fattn-buffers.hpp +63 -0
  360. data/ext/sources/ggml/src/ggml-sycl/fattn-common.hpp +7 -5
  361. data/ext/sources/ggml/src/ggml-sycl/fattn-tile.cpp +4 -0
  362. data/ext/sources/ggml/src/ggml-sycl/fattn-tile.hpp +76 -168
  363. data/ext/sources/ggml/src/ggml-sycl/fattn-vec.hpp +7 -0
  364. data/ext/sources/ggml/src/ggml-sycl/fattn.cpp +3 -1
  365. data/ext/sources/ggml/src/ggml-sycl/fill.cpp +55 -0
  366. data/ext/sources/ggml/src/ggml-sycl/fill.hpp +5 -0
  367. data/ext/sources/ggml/src/ggml-sycl/gated_delta_net.cpp +69 -31
  368. data/ext/sources/ggml/src/ggml-sycl/gated_delta_net.hpp +1 -0
  369. data/ext/sources/ggml/src/ggml-sycl/gemm.hpp +3 -0
  370. data/ext/sources/ggml/src/ggml-sycl/getrows.cpp +79 -3
  371. data/ext/sources/ggml/src/ggml-sycl/ggml-sycl.cpp +823 -190
  372. data/ext/sources/ggml/src/ggml-sycl/im2col.cpp +353 -89
  373. data/ext/sources/ggml/src/ggml-sycl/im2col.hpp +5 -3
  374. data/ext/sources/ggml/src/ggml-sycl/mmvq.cpp +1344 -26
  375. data/ext/sources/ggml/src/ggml-sycl/mmvq.hpp +16 -0
  376. data/ext/sources/ggml/src/ggml-sycl/pad.cpp +27 -27
  377. data/ext/sources/ggml/src/ggml-sycl/quants.hpp +71 -0
  378. data/ext/sources/ggml/src/ggml-sycl/set_rows.cpp +7 -1
  379. data/ext/sources/ggml/src/ggml-sycl/solve_tri.cpp +172 -0
  380. data/ext/sources/ggml/src/ggml-sycl/solve_tri.hpp +8 -0
  381. data/ext/sources/ggml/src/ggml-sycl/ssm_conv.cpp +6 -1
  382. data/ext/sources/ggml/src/ggml-sycl/ssm_scan.cpp +156 -0
  383. data/ext/sources/ggml/src/ggml-sycl/ssm_scan.hpp +5 -0
  384. data/ext/sources/ggml/src/ggml-sycl/sycl_hw.cpp +62 -10
  385. data/ext/sources/ggml/src/ggml-sycl/sycl_hw.hpp +18 -6
  386. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-tile-instance-dkq512-dv512.cpp +6 -0
  387. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-f16-f16.cpp +1 -0
  388. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-f16-q4_0.cpp +1 -0
  389. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-f16-q4_1.cpp +1 -0
  390. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-f16-q5_0.cpp +1 -0
  391. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-f16-q5_1.cpp +1 -0
  392. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-f16-q8_0.cpp +1 -0
  393. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q4_0-f16.cpp +1 -0
  394. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q4_0-q4_0.cpp +1 -0
  395. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q4_0-q4_1.cpp +1 -0
  396. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q4_0-q5_0.cpp +1 -0
  397. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q4_0-q5_1.cpp +1 -0
  398. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q4_0-q8_0.cpp +1 -0
  399. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q4_1-f16.cpp +1 -0
  400. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q4_1-q4_0.cpp +1 -0
  401. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q4_1-q4_1.cpp +1 -0
  402. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q4_1-q5_0.cpp +1 -0
  403. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q4_1-q5_1.cpp +1 -0
  404. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q4_1-q8_0.cpp +1 -0
  405. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q5_0-f16.cpp +1 -0
  406. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q5_0-q4_0.cpp +1 -0
  407. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q5_0-q4_1.cpp +1 -0
  408. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q5_0-q5_0.cpp +1 -0
  409. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q5_0-q5_1.cpp +1 -0
  410. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q5_0-q8_0.cpp +1 -0
  411. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q5_1-f16.cpp +1 -0
  412. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q5_1-q4_0.cpp +1 -0
  413. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q5_1-q4_1.cpp +1 -0
  414. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q5_1-q5_0.cpp +1 -0
  415. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q5_1-q5_1.cpp +1 -0
  416. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q5_1-q8_0.cpp +1 -0
  417. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q8_0-f16.cpp +1 -0
  418. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q8_0-q4_0.cpp +1 -0
  419. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q8_0-q4_1.cpp +1 -0
  420. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q8_0-q5_0.cpp +1 -0
  421. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q8_0-q5_1.cpp +1 -0
  422. data/ext/sources/ggml/src/ggml-sycl/template-instances/fattn-vec-instance-q8_0-q8_0.cpp +1 -0
  423. data/ext/sources/ggml/src/ggml-sycl/type.hpp +112 -0
  424. data/ext/sources/ggml/src/ggml-sycl/upscale.cpp +410 -0
  425. data/ext/sources/ggml/src/ggml-sycl/upscale.hpp +9 -0
  426. data/ext/sources/ggml/src/ggml-sycl/vecdotq.hpp +215 -53
  427. data/ext/sources/ggml/src/ggml-virtgpu/ggml-backend-buffer.cpp +4 -0
  428. data/ext/sources/ggml/src/ggml-virtgpu/ggml-backend-device.cpp +2 -0
  429. data/ext/sources/ggml/src/ggml-virtgpu/ggml-backend.cpp +2 -0
  430. data/ext/sources/ggml/src/ggml-virtgpu/virtgpu-shm.cpp +1 -0
  431. data/ext/sources/ggml/src/ggml-virtgpu/virtgpu.cpp +1 -0
  432. data/ext/sources/ggml/src/ggml-virtgpu/virtgpu.h +0 -2
  433. data/ext/sources/ggml/src/ggml-vulkan/CMakeLists.txt +11 -0
  434. data/ext/sources/ggml/src/ggml-vulkan/ggml-vulkan.cpp +2060 -535
  435. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt +4 -0
  436. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/contig_copy.comp +6 -2
  437. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/conv2d_mm.comp +146 -13
  438. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/copy.comp +3 -1
  439. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/copy_from_quant.comp +1 -1
  440. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/copy_to_quant.comp +25 -1
  441. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs.glsl +88 -0
  442. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs_cm2.glsl +643 -1
  443. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/dequant_nvfp4.comp +32 -0
  444. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/dequant_q1_0.comp +29 -0
  445. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/diag.comp +0 -1
  446. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/dot_product_funcs.glsl +27 -0
  447. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/exp.comp +0 -1
  448. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/feature-tests/coopmat2_decode_vector.comp +7 -0
  449. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp +197 -48
  450. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl +60 -59
  451. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp +115 -113
  452. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm2.comp +122 -31
  453. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_dequant.glsl +131 -0
  454. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_mmq_funcs.glsl +203 -0
  455. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/fwht.comp +115 -0
  456. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp +125 -64
  457. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/generic_binary_head.glsl +0 -1
  458. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/glu_head.glsl +10 -1
  459. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/glu_main.glsl +16 -6
  460. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/im2col.comp +76 -54
  461. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/im2col_3d.comp +0 -1
  462. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/log.comp +0 -1
  463. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec.comp +122 -27
  464. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_iface.glsl +6 -6
  465. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q2_k.comp +1 -1
  466. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q4_k.comp +1 -1
  467. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vec_q5_k.comp +1 -1
  468. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vecq.comp +1 -0
  469. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_vecq_funcs.glsl +88 -55
  470. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm.comp +11 -17
  471. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_cm2.comp +43 -10
  472. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_funcs.glsl +159 -125
  473. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_funcs.glsl +8 -8
  474. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_shmem_types.glsl +24 -9
  475. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/multi_add.comp +0 -1
  476. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/rope_funcs.glsl +5 -2
  477. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/rope_head.glsl +0 -1
  478. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/rope_params.glsl +3 -2
  479. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/snake.comp +49 -0
  480. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/ssm_conv.comp +11 -1
  481. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/tri.comp +0 -1
  482. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl +79 -2
  483. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +171 -147
  484. data/ext/sources/ggml/src/ggml-webgpu/CMakeLists.txt +5 -2
  485. data/ext/sources/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp +2202 -283
  486. data/ext/sources/ggml/src/ggml-webgpu/ggml-webgpu.cpp +2610 -1403
  487. data/ext/sources/ggml/src/ggml-webgpu/pre_wgsl.hpp +37 -7
  488. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/add_id.wgsl +64 -0
  489. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/binary.wgsl +8 -7
  490. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/common_decls.tmpl +76 -95
  491. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/concat.wgsl +19 -1
  492. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/conv2d.wgsl +165 -0
  493. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/{cpy.tmpl.wgsl → cpy.wgsl} +25 -50
  494. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/flash_attn.wgsl +107 -184
  495. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/flash_attn_quant_staging.tmpl +124 -0
  496. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/flash_attn_tile.wgsl +397 -0
  497. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/flash_attn_vec_blk.wgsl +101 -0
  498. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/flash_attn_vec_reduce.wgsl +84 -0
  499. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/flash_attn_vec_split.wgsl +619 -0
  500. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl +149 -0
  501. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/get_rows.wgsl +183 -78
  502. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/glu.wgsl +155 -0
  503. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/im2col.wgsl +101 -0
  504. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_decls.tmpl +655 -495
  505. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_id.wgsl +195 -0
  506. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_id_gather.wgsl +52 -0
  507. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_id_vec.wgsl +154 -0
  508. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_reg_tile.wgsl +8 -6
  509. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_subgroup_matrix.wgsl +5 -1
  510. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_vec.wgsl +80 -409
  511. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_vec_acc.tmpl +1432 -0
  512. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_vec_q_acc.tmpl +303 -0
  513. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/quant_inner_loops.tmpl +21 -0
  514. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/quantize_q8.wgsl +173 -0
  515. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/rms_norm_mul.wgsl +152 -0
  516. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/{rope.tmpl.wgsl → rope.wgsl} +71 -142
  517. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/row_norm.wgsl +153 -0
  518. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/scale.wgsl +6 -4
  519. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/set.wgsl +109 -0
  520. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/set_rows.wgsl +2 -3
  521. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/set_rows_quant.wgsl +224 -0
  522. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/{soft_max.tmpl.wgsl → soft_max.wgsl} +106 -206
  523. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/solve_tri.wgsl +121 -0
  524. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/ssm_conv.wgsl +65 -0
  525. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/ssm_scan.wgsl +193 -0
  526. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/unary.wgsl +68 -48
  527. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/upscale.wgsl +240 -0
  528. data/ext/sources/ggml/src/ggml-zdnn/ggml-zdnn.cpp +18 -14
  529. data/ext/sources/ggml/src/ggml-zendnn/CMakeLists.txt +1 -1
  530. data/ext/sources/ggml/src/ggml-zendnn/ggml-zendnn.cpp +244 -10
  531. data/ext/sources/ggml/src/ggml.c +110 -28
  532. data/ext/sources/ggml/src/gguf.cpp +173 -28
  533. data/ext/sources/include/parakeet.h +342 -0
  534. data/ext/sources/include/whisper.h +10 -0
  535. data/ext/sources/media/matmul.png +0 -0
  536. data/ext/sources/src/CMakeLists.txt +23 -0
  537. data/ext/sources/src/parakeet-arch.h +188 -0
  538. data/ext/sources/src/parakeet.cpp +3838 -0
  539. data/ext/sources/src/whisper.cpp +56 -12
  540. data/extsources.rb +26 -10
  541. data/lib/whisper/log_settable.rb +36 -0
  542. data/lib/whisper/model/uri.rb +13 -1
  543. data/lib/whisper/output.rb +74 -0
  544. data/sig/whisper.rbs +411 -62
  545. data/test/helper.rb +2 -0
  546. data/test/jfk_reader/jfk_reader.c +50 -7
  547. data/test/test_callback.rb +1 -0
  548. data/test/test_package.rb +6 -5
  549. data/test/test_parakeet.rb +28 -0
  550. data/test/test_parakeet_callback.rb +107 -0
  551. data/test/test_parakeet_context.rb +116 -0
  552. data/test/test_parakeet_context_params.rb +24 -0
  553. data/test/test_parakeet_model.rb +21 -0
  554. data/test/test_parakeet_params.rb +78 -0
  555. data/test/test_parakeet_segment.rb +42 -0
  556. data/test/test_parakeet_token.rb +73 -0
  557. data/test/test_params.rb +2 -0
  558. data/test/test_vad_segment.rb +1 -1
  559. data/test/test_whisper.rb +24 -6
  560. data/whispercpp.gemspec +2 -2
  561. metadata +215 -281
  562. data/ext/sources/bindings/javascript/CMakeLists.txt +0 -41
  563. data/ext/sources/bindings/javascript/emscripten.cpp +0 -93
  564. data/ext/sources/bindings/javascript/libwhisper.worker.js +0 -1
  565. data/ext/sources/bindings/javascript/package.json +0 -26
  566. data/ext/sources/bindings/javascript/whisper.js +0 -19
  567. data/ext/sources/examples/addon.node/CMakeLists.txt +0 -31
  568. data/ext/sources/examples/addon.node/__test__/whisper.spec.js +0 -133
  569. data/ext/sources/examples/addon.node/addon.cpp +0 -557
  570. data/ext/sources/examples/addon.node/index.js +0 -59
  571. data/ext/sources/examples/addon.node/package.json +0 -16
  572. data/ext/sources/examples/addon.node/vad-example.js +0 -132
  573. data/ext/sources/examples/bench.wasm/CMakeLists.txt +0 -49
  574. data/ext/sources/examples/bench.wasm/emscripten.cpp +0 -87
  575. data/ext/sources/examples/bench.wasm/index-tmpl.html +0 -285
  576. data/ext/sources/examples/coi-serviceworker.js +0 -146
  577. data/ext/sources/examples/command/CMakeLists.txt +0 -10
  578. data/ext/sources/examples/command/command.cpp +0 -802
  579. data/ext/sources/examples/command/commands.txt +0 -9
  580. data/ext/sources/examples/command.wasm/CMakeLists.txt +0 -50
  581. data/ext/sources/examples/command.wasm/emscripten.cpp +0 -327
  582. data/ext/sources/examples/command.wasm/index-tmpl.html +0 -415
  583. data/ext/sources/examples/generate-karaoke.sh +0 -57
  584. data/ext/sources/examples/helpers.js +0 -191
  585. data/ext/sources/examples/livestream.sh +0 -112
  586. data/ext/sources/examples/lsp/CMakeLists.txt +0 -10
  587. data/ext/sources/examples/lsp/lsp.cpp +0 -471
  588. data/ext/sources/examples/lsp/whisper.vim +0 -362
  589. data/ext/sources/examples/python/test_whisper_processor.py +0 -7
  590. data/ext/sources/examples/python/whisper_processor.py +0 -54
  591. data/ext/sources/examples/server/bench.js +0 -29
  592. data/ext/sources/examples/server.py +0 -120
  593. data/ext/sources/examples/stream/CMakeLists.txt +0 -10
  594. data/ext/sources/examples/stream/stream.cpp +0 -437
  595. data/ext/sources/examples/stream.wasm/CMakeLists.txt +0 -49
  596. data/ext/sources/examples/stream.wasm/emscripten.cpp +0 -216
  597. data/ext/sources/examples/stream.wasm/index-tmpl.html +0 -491
  598. data/ext/sources/examples/sycl/CMakeLists.txt +0 -9
  599. data/ext/sources/examples/sycl/build.sh +0 -22
  600. data/ext/sources/examples/sycl/ls-sycl-device.cpp +0 -11
  601. data/ext/sources/examples/sycl/run-whisper.sh +0 -17
  602. data/ext/sources/examples/talk-llama/CMakeLists.txt +0 -48
  603. data/ext/sources/examples/talk-llama/eleven-labs.py +0 -80
  604. data/ext/sources/examples/talk-llama/llama-adapter.cpp +0 -488
  605. data/ext/sources/examples/talk-llama/llama-adapter.h +0 -89
  606. data/ext/sources/examples/talk-llama/llama-arch.cpp +0 -2877
  607. data/ext/sources/examples/talk-llama/llama-arch.h +0 -628
  608. data/ext/sources/examples/talk-llama/llama-batch.cpp +0 -919
  609. data/ext/sources/examples/talk-llama/llama-batch.h +0 -173
  610. data/ext/sources/examples/talk-llama/llama-chat.cpp +0 -896
  611. data/ext/sources/examples/talk-llama/llama-chat.h +0 -71
  612. data/ext/sources/examples/talk-llama/llama-context.cpp +0 -3633
  613. data/ext/sources/examples/talk-llama/llama-context.h +0 -359
  614. data/ext/sources/examples/talk-llama/llama-cparams.cpp +0 -5
  615. data/ext/sources/examples/talk-llama/llama-cparams.h +0 -47
  616. data/ext/sources/examples/talk-llama/llama-ext.h +0 -12
  617. data/ext/sources/examples/talk-llama/llama-grammar.cpp +0 -1464
  618. data/ext/sources/examples/talk-llama/llama-grammar.h +0 -194
  619. data/ext/sources/examples/talk-llama/llama-graph.cpp +0 -2735
  620. data/ext/sources/examples/talk-llama/llama-graph.h +0 -1031
  621. data/ext/sources/examples/talk-llama/llama-hparams.cpp +0 -258
  622. data/ext/sources/examples/talk-llama/llama-hparams.h +0 -353
  623. data/ext/sources/examples/talk-llama/llama-impl.cpp +0 -171
  624. data/ext/sources/examples/talk-llama/llama-impl.h +0 -75
  625. data/ext/sources/examples/talk-llama/llama-io.cpp +0 -15
  626. data/ext/sources/examples/talk-llama/llama-io.h +0 -35
  627. data/ext/sources/examples/talk-llama/llama-kv-cache-iswa.cpp +0 -330
  628. data/ext/sources/examples/talk-llama/llama-kv-cache-iswa.h +0 -137
  629. data/ext/sources/examples/talk-llama/llama-kv-cache.cpp +0 -2285
  630. data/ext/sources/examples/talk-llama/llama-kv-cache.h +0 -389
  631. data/ext/sources/examples/talk-llama/llama-kv-cells.h +0 -533
  632. data/ext/sources/examples/talk-llama/llama-memory-hybrid-iswa.cpp +0 -275
  633. data/ext/sources/examples/talk-llama/llama-memory-hybrid-iswa.h +0 -140
  634. data/ext/sources/examples/talk-llama/llama-memory-hybrid.cpp +0 -268
  635. data/ext/sources/examples/talk-llama/llama-memory-hybrid.h +0 -139
  636. data/ext/sources/examples/talk-llama/llama-memory-recurrent.cpp +0 -1165
  637. data/ext/sources/examples/talk-llama/llama-memory-recurrent.h +0 -182
  638. data/ext/sources/examples/talk-llama/llama-memory.cpp +0 -59
  639. data/ext/sources/examples/talk-llama/llama-memory.h +0 -122
  640. data/ext/sources/examples/talk-llama/llama-mmap.cpp +0 -752
  641. data/ext/sources/examples/talk-llama/llama-mmap.h +0 -73
  642. data/ext/sources/examples/talk-llama/llama-model-loader.cpp +0 -1655
  643. data/ext/sources/examples/talk-llama/llama-model-loader.h +0 -206
  644. data/ext/sources/examples/talk-llama/llama-model-saver.cpp +0 -299
  645. data/ext/sources/examples/talk-llama/llama-model-saver.h +0 -40
  646. data/ext/sources/examples/talk-llama/llama-model.cpp +0 -9056
  647. data/ext/sources/examples/talk-llama/llama-model.h +0 -597
  648. data/ext/sources/examples/talk-llama/llama-quant.cpp +0 -1304
  649. data/ext/sources/examples/talk-llama/llama-quant.h +0 -1
  650. data/ext/sources/examples/talk-llama/llama-sampler.cpp +0 -3885
  651. data/ext/sources/examples/talk-llama/llama-sampler.h +0 -42
  652. data/ext/sources/examples/talk-llama/llama-vocab.cpp +0 -3970
  653. data/ext/sources/examples/talk-llama/llama-vocab.h +0 -187
  654. data/ext/sources/examples/talk-llama/llama.cpp +0 -1194
  655. data/ext/sources/examples/talk-llama/llama.h +0 -1573
  656. data/ext/sources/examples/talk-llama/models/afmoe.cpp +0 -190
  657. data/ext/sources/examples/talk-llama/models/apertus.cpp +0 -125
  658. data/ext/sources/examples/talk-llama/models/arcee.cpp +0 -135
  659. data/ext/sources/examples/talk-llama/models/arctic.cpp +0 -137
  660. data/ext/sources/examples/talk-llama/models/arwkv7.cpp +0 -86
  661. data/ext/sources/examples/talk-llama/models/baichuan.cpp +0 -123
  662. data/ext/sources/examples/talk-llama/models/bailingmoe.cpp +0 -143
  663. data/ext/sources/examples/talk-llama/models/bailingmoe2.cpp +0 -133
  664. data/ext/sources/examples/talk-llama/models/bert.cpp +0 -184
  665. data/ext/sources/examples/talk-llama/models/bitnet.cpp +0 -145
  666. data/ext/sources/examples/talk-llama/models/bloom.cpp +0 -101
  667. data/ext/sources/examples/talk-llama/models/chameleon.cpp +0 -178
  668. data/ext/sources/examples/talk-llama/models/chatglm.cpp +0 -132
  669. data/ext/sources/examples/talk-llama/models/codeshell.cpp +0 -111
  670. data/ext/sources/examples/talk-llama/models/cogvlm.cpp +0 -102
  671. data/ext/sources/examples/talk-llama/models/cohere2-iswa.cpp +0 -134
  672. data/ext/sources/examples/talk-llama/models/command-r.cpp +0 -122
  673. data/ext/sources/examples/talk-llama/models/dbrx.cpp +0 -122
  674. data/ext/sources/examples/talk-llama/models/deci.cpp +0 -135
  675. data/ext/sources/examples/talk-llama/models/deepseek.cpp +0 -142
  676. data/ext/sources/examples/talk-llama/models/deepseek2.cpp +0 -262
  677. data/ext/sources/examples/talk-llama/models/delta-net-base.cpp +0 -445
  678. data/ext/sources/examples/talk-llama/models/dots1.cpp +0 -132
  679. data/ext/sources/examples/talk-llama/models/dream.cpp +0 -105
  680. data/ext/sources/examples/talk-llama/models/ernie4-5-moe.cpp +0 -148
  681. data/ext/sources/examples/talk-llama/models/ernie4-5.cpp +0 -110
  682. data/ext/sources/examples/talk-llama/models/eurobert.cpp +0 -97
  683. data/ext/sources/examples/talk-llama/models/exaone-moe.cpp +0 -145
  684. data/ext/sources/examples/talk-llama/models/exaone.cpp +0 -114
  685. data/ext/sources/examples/talk-llama/models/exaone4.cpp +0 -123
  686. data/ext/sources/examples/talk-llama/models/falcon-h1.cpp +0 -111
  687. data/ext/sources/examples/talk-llama/models/falcon.cpp +0 -120
  688. data/ext/sources/examples/talk-llama/models/gemma-embedding.cpp +0 -116
  689. data/ext/sources/examples/talk-llama/models/gemma.cpp +0 -112
  690. data/ext/sources/examples/talk-llama/models/gemma2-iswa.cpp +0 -128
  691. data/ext/sources/examples/talk-llama/models/gemma3.cpp +0 -155
  692. data/ext/sources/examples/talk-llama/models/gemma3n-iswa.cpp +0 -384
  693. data/ext/sources/examples/talk-llama/models/glm4-moe.cpp +0 -170
  694. data/ext/sources/examples/talk-llama/models/glm4.cpp +0 -157
  695. data/ext/sources/examples/talk-llama/models/gpt2.cpp +0 -105
  696. data/ext/sources/examples/talk-llama/models/gptneox.cpp +0 -144
  697. data/ext/sources/examples/talk-llama/models/granite-hybrid.cpp +0 -195
  698. data/ext/sources/examples/talk-llama/models/granite.cpp +0 -210
  699. data/ext/sources/examples/talk-llama/models/grok.cpp +0 -159
  700. data/ext/sources/examples/talk-llama/models/grovemoe.cpp +0 -139
  701. data/ext/sources/examples/talk-llama/models/hunyuan-dense.cpp +0 -132
  702. data/ext/sources/examples/talk-llama/models/hunyuan-moe.cpp +0 -153
  703. data/ext/sources/examples/talk-llama/models/internlm2.cpp +0 -120
  704. data/ext/sources/examples/talk-llama/models/jais.cpp +0 -86
  705. data/ext/sources/examples/talk-llama/models/jais2.cpp +0 -123
  706. data/ext/sources/examples/talk-llama/models/jamba.cpp +0 -106
  707. data/ext/sources/examples/talk-llama/models/kimi-linear.cpp +0 -381
  708. data/ext/sources/examples/talk-llama/models/lfm2.cpp +0 -196
  709. data/ext/sources/examples/talk-llama/models/llada-moe.cpp +0 -122
  710. data/ext/sources/examples/talk-llama/models/llada.cpp +0 -99
  711. data/ext/sources/examples/talk-llama/models/llama-iswa.cpp +0 -178
  712. data/ext/sources/examples/talk-llama/models/llama.cpp +0 -175
  713. data/ext/sources/examples/talk-llama/models/maincoder.cpp +0 -117
  714. data/ext/sources/examples/talk-llama/models/mamba-base.cpp +0 -289
  715. data/ext/sources/examples/talk-llama/models/mamba.cpp +0 -54
  716. data/ext/sources/examples/talk-llama/models/mimo2-iswa.cpp +0 -129
  717. data/ext/sources/examples/talk-llama/models/minicpm3.cpp +0 -200
  718. data/ext/sources/examples/talk-llama/models/minimax-m2.cpp +0 -123
  719. data/ext/sources/examples/talk-llama/models/mistral3.cpp +0 -160
  720. data/ext/sources/examples/talk-llama/models/models.h +0 -704
  721. data/ext/sources/examples/talk-llama/models/modern-bert.cpp +0 -109
  722. data/ext/sources/examples/talk-llama/models/mpt.cpp +0 -126
  723. data/ext/sources/examples/talk-llama/models/nemotron-h.cpp +0 -162
  724. data/ext/sources/examples/talk-llama/models/nemotron.cpp +0 -122
  725. data/ext/sources/examples/talk-llama/models/neo-bert.cpp +0 -104
  726. data/ext/sources/examples/talk-llama/models/olmo.cpp +0 -121
  727. data/ext/sources/examples/talk-llama/models/olmo2.cpp +0 -150
  728. data/ext/sources/examples/talk-llama/models/olmoe.cpp +0 -124
  729. data/ext/sources/examples/talk-llama/models/openai-moe-iswa.cpp +0 -127
  730. data/ext/sources/examples/talk-llama/models/openelm.cpp +0 -124
  731. data/ext/sources/examples/talk-llama/models/orion.cpp +0 -123
  732. data/ext/sources/examples/talk-llama/models/paddleocr.cpp +0 -122
  733. data/ext/sources/examples/talk-llama/models/pangu-embedded.cpp +0 -121
  734. data/ext/sources/examples/talk-llama/models/phi2.cpp +0 -121
  735. data/ext/sources/examples/talk-llama/models/phi3.cpp +0 -152
  736. data/ext/sources/examples/talk-llama/models/plamo.cpp +0 -110
  737. data/ext/sources/examples/talk-llama/models/plamo2.cpp +0 -320
  738. data/ext/sources/examples/talk-llama/models/plamo3.cpp +0 -128
  739. data/ext/sources/examples/talk-llama/models/plm.cpp +0 -169
  740. data/ext/sources/examples/talk-llama/models/qwen.cpp +0 -108
  741. data/ext/sources/examples/talk-llama/models/qwen2.cpp +0 -126
  742. data/ext/sources/examples/talk-llama/models/qwen2moe.cpp +0 -151
  743. data/ext/sources/examples/talk-llama/models/qwen2vl.cpp +0 -117
  744. data/ext/sources/examples/talk-llama/models/qwen3.cpp +0 -120
  745. data/ext/sources/examples/talk-llama/models/qwen35.cpp +0 -381
  746. data/ext/sources/examples/talk-llama/models/qwen35moe.cpp +0 -422
  747. data/ext/sources/examples/talk-llama/models/qwen3moe.cpp +0 -131
  748. data/ext/sources/examples/talk-llama/models/qwen3next.cpp +0 -525
  749. data/ext/sources/examples/talk-llama/models/qwen3vl-moe.cpp +0 -140
  750. data/ext/sources/examples/talk-llama/models/qwen3vl.cpp +0 -132
  751. data/ext/sources/examples/talk-llama/models/refact.cpp +0 -94
  752. data/ext/sources/examples/talk-llama/models/rnd1.cpp +0 -126
  753. data/ext/sources/examples/talk-llama/models/rwkv6-base.cpp +0 -164
  754. data/ext/sources/examples/talk-llama/models/rwkv6.cpp +0 -94
  755. data/ext/sources/examples/talk-llama/models/rwkv6qwen2.cpp +0 -86
  756. data/ext/sources/examples/talk-llama/models/rwkv7-base.cpp +0 -137
  757. data/ext/sources/examples/talk-llama/models/rwkv7.cpp +0 -90
  758. data/ext/sources/examples/talk-llama/models/seed-oss.cpp +0 -124
  759. data/ext/sources/examples/talk-llama/models/smallthinker.cpp +0 -126
  760. data/ext/sources/examples/talk-llama/models/smollm3.cpp +0 -128
  761. data/ext/sources/examples/talk-llama/models/stablelm.cpp +0 -146
  762. data/ext/sources/examples/talk-llama/models/starcoder.cpp +0 -100
  763. data/ext/sources/examples/talk-llama/models/starcoder2.cpp +0 -121
  764. data/ext/sources/examples/talk-llama/models/step35-iswa.cpp +0 -165
  765. data/ext/sources/examples/talk-llama/models/t5-dec.cpp +0 -166
  766. data/ext/sources/examples/talk-llama/models/t5-enc.cpp +0 -96
  767. data/ext/sources/examples/talk-llama/models/wavtokenizer-dec.cpp +0 -149
  768. data/ext/sources/examples/talk-llama/models/xverse.cpp +0 -108
  769. data/ext/sources/examples/talk-llama/prompts/talk-alpaca.txt +0 -23
  770. data/ext/sources/examples/talk-llama/speak +0 -40
  771. data/ext/sources/examples/talk-llama/speak.bat +0 -1
  772. data/ext/sources/examples/talk-llama/speak.ps1 +0 -14
  773. data/ext/sources/examples/talk-llama/talk-llama.cpp +0 -813
  774. data/ext/sources/examples/talk-llama/unicode-data.cpp +0 -7034
  775. data/ext/sources/examples/talk-llama/unicode-data.h +0 -20
  776. data/ext/sources/examples/talk-llama/unicode.cpp +0 -1103
  777. data/ext/sources/examples/talk-llama/unicode.h +0 -111
  778. data/ext/sources/examples/wchess/CMakeLists.txt +0 -10
  779. data/ext/sources/examples/wchess/libwchess/CMakeLists.txt +0 -19
  780. data/ext/sources/examples/wchess/libwchess/Chessboard.cpp +0 -803
  781. data/ext/sources/examples/wchess/libwchess/Chessboard.h +0 -33
  782. data/ext/sources/examples/wchess/libwchess/WChess.cpp +0 -193
  783. data/ext/sources/examples/wchess/libwchess/WChess.h +0 -63
  784. data/ext/sources/examples/wchess/libwchess/test-chessboard.cpp +0 -117
  785. data/ext/sources/examples/wchess/wchess.cmd/CMakeLists.txt +0 -8
  786. data/ext/sources/examples/wchess/wchess.cmd/wchess.cmd.cpp +0 -253
  787. data/ext/sources/examples/whisper.wasm/CMakeLists.txt +0 -50
  788. data/ext/sources/examples/whisper.wasm/emscripten.cpp +0 -118
  789. data/ext/sources/examples/whisper.wasm/index-tmpl.html +0 -659
  790. data/ext/sources/ggml/src/ggml-cuda/template-instances/generate_cu_files.py +0 -99
  791. data/ext/sources/ggml/src/ggml-hexagon/htp/htp-msg.h +0 -155
  792. data/ext/sources/ggml/src/ggml-hexagon/op-desc.h +0 -153
  793. data/ext/sources/ggml/src/ggml-opencl/kernels/embed_kernel.py +0 -26
  794. data/ext/sources/ggml/src/ggml-openvino/openvino/pass/eliminate_zp.cpp +0 -123
  795. data/ext/sources/ggml/src/ggml-openvino/openvino/pass/eliminate_zp.h +0 -17
  796. data/ext/sources/ggml/src/ggml-virtgpu/regenerate_remoting.py +0 -333
  797. data/ext/sources/ggml/src/ggml-vulkan/vulkan-shaders/rte.glsl +0 -5
  798. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/embed_wgsl.py +0 -182
  799. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/glu.tmpl.wgsl +0 -323
  800. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat.wgsl +0 -718
  801. data/ext/sources/ggml/src/ggml-webgpu/wgsl-shaders/rms_norm.wgsl +0 -123
  802. data/ext/sources/tests/CMakeLists.txt +0 -112
  803. data/ext/sources/tests/earnings21/eval.mk +0 -58
  804. data/ext/sources/tests/earnings21/eval.py +0 -68
  805. data/ext/sources/tests/earnings21/normalizers/__init__.py +0 -2
  806. data/ext/sources/tests/earnings21/normalizers/basic.py +0 -80
  807. data/ext/sources/tests/earnings21/normalizers/english.json +0 -1741
  808. data/ext/sources/tests/earnings21/normalizers/english.py +0 -550
  809. data/ext/sources/tests/earnings21/requirements.txt +0 -6
  810. data/ext/sources/tests/en-0-ref.txt +0 -1
  811. data/ext/sources/tests/en-1-ref.txt +0 -1
  812. data/ext/sources/tests/en-2-ref.txt +0 -1
  813. data/ext/sources/tests/es-0-ref.txt +0 -1
  814. data/ext/sources/tests/librispeech/eval.mk +0 -39
  815. data/ext/sources/tests/librispeech/eval.py +0 -47
  816. data/ext/sources/tests/librispeech/normalizers/__init__.py +0 -2
  817. data/ext/sources/tests/librispeech/normalizers/basic.py +0 -80
  818. data/ext/sources/tests/librispeech/normalizers/english.json +0 -1741
  819. data/ext/sources/tests/librispeech/normalizers/english.py +0 -550
  820. data/ext/sources/tests/librispeech/requirements.txt +0 -6
  821. data/ext/sources/tests/run-tests.sh +0 -130
  822. data/ext/sources/tests/test-c.c +0 -3
  823. data/ext/sources/tests/test-vad-full.cpp +0 -56
  824. data/ext/sources/tests/test-vad.cpp +0 -83
  825. data/ext/sources/tests/test-whisper.js +0 -58
  826. data/lib/whisper/context.rb +0 -15
  827. data/lib/whisper/segment.rb +0 -58
  828. /data/ext/sources/ggml/src/ggml-opencl/kernels/{gemv_noshuffle_general_q8_0_f32.cl → gemv_noshuffle_q8_0_f32.cl} +0 -0
@@ -1,3633 +0,0 @@
1
- #include "llama-context.h"
2
-
3
- #include "llama-arch.h"
4
- #include "llama-impl.h"
5
- #include "llama-batch.h"
6
- #include "llama-io.h"
7
- #include "llama-memory.h"
8
- #include "llama-mmap.h"
9
- #include "llama-model.h"
10
- #include "llama-ext.h"
11
-
12
- #include <cinttypes>
13
- #include <cmath>
14
- #include <cstring>
15
- #include <limits>
16
- #include <stdexcept>
17
-
18
- //
19
- // llama_context
20
- //
21
-
22
- llama_context::llama_context(
23
- const llama_model & model,
24
- llama_context_params params) :
25
- model(model),
26
- cvec(std::make_unique<llama_adapter_cvec>()),
27
- loras(std::make_unique<llama_adapter_loras>()),
28
- balloc(std::make_unique<llama_batch_allocr>(model.hparams.n_pos_per_embd())) {
29
- // TODO warning when creating llama_context with awkward ctx size that is not a power of 2,
30
- // may need to be backend-dependent
31
- LLAMA_LOG_INFO("%s: constructing llama_context\n", __func__);
32
-
33
- t_start_us = model.t_start_us;
34
- t_load_us = model.t_load_us;
35
-
36
- const auto & hparams = model.hparams;
37
-
38
- cparams.n_seq_max = std::max(1u, params.n_seq_max);
39
- if (cparams.n_seq_max > LLAMA_MAX_SEQ) {
40
- throw std::runtime_error("n_seq_max must be <= " + std::to_string(LLAMA_MAX_SEQ));
41
- }
42
-
43
- cparams.n_threads = params.n_threads;
44
- cparams.n_threads_batch = params.n_threads_batch;
45
- cparams.yarn_ext_factor = params.yarn_ext_factor >= 0.0f ? params.yarn_ext_factor : hparams.yarn_ext_factor;
46
- cparams.yarn_attn_factor = params.yarn_attn_factor >= 0.0f ? params.yarn_attn_factor : hparams.yarn_attn_factor;
47
- cparams.yarn_beta_fast = params.yarn_beta_fast >= 0.0f ? params.yarn_beta_fast : hparams.yarn_beta_fast;
48
- cparams.yarn_beta_slow = params.yarn_beta_slow >= 0.0f ? params.yarn_beta_slow : hparams.yarn_beta_slow;
49
- cparams.embeddings = params.embeddings;
50
- cparams.offload_kqv = params.offload_kqv;
51
- cparams.no_perf = params.no_perf;
52
- cparams.pooling_type = params.pooling_type;
53
- cparams.warmup = false;
54
-
55
- cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
56
- cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
57
- cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
58
-
59
- cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
60
- hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
61
- hparams.n_ctx_train;
62
-
63
- cparams.cb_eval = params.cb_eval;
64
- cparams.cb_eval_user_data = params.cb_eval_user_data;
65
-
66
- // Initialize backend samplers here so they are part of the sampling graph
67
- // before the reserve passes run later in this function. This avoids a later
68
- // re-reserve when graph nodes change.
69
- if (params.samplers != nullptr && params.n_samplers > 0) {
70
- for (size_t i = 0; i < params.n_samplers; ++i) {
71
- const auto & config = params.samplers[i];
72
-
73
- if (llama_sampler_chain_get(config.sampler, -1) == nullptr) {
74
- throw std::runtime_error("the backend samplers must be of type llama_sampler_chain");
75
- }
76
-
77
- if (set_sampler(config.seq_id, config.sampler)) {
78
- const int n_samplers = llama_sampler_chain_n(config.sampler);
79
-
80
- LLAMA_LOG_INFO("%s: setting backend sampler for seq_id %d (n = %d)\n", __func__, config.seq_id, n_samplers);
81
- }
82
- }
83
- }
84
-
85
- auto rope_scaling_type = params.rope_scaling_type;
86
- if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
87
- rope_scaling_type = hparams.rope_scaling_type_train;
88
- }
89
-
90
- if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
91
- cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
92
- }
93
-
94
- if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
95
- cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
96
- }
97
-
98
- if (cparams.yarn_ext_factor != 0) {
99
- static auto get_mscale = [](float scale, float mscale) {
100
- return scale <= 1.0f ? 1.0f : (0.1f * mscale * logf(scale) + 1.0f);
101
- };
102
-
103
- const float factor = 1.0f / cparams.rope_freq_scale;
104
-
105
- // ref: https://github.com/huggingface/transformers/blob/6d00f6b0a5679c36510f203e4226e36f517c3032/src/transformers/modeling_rope_utils.py#L336-L348
106
- if (hparams.rope_yarn_log_mul != 0.0f) {
107
- // note: here we assume `mscale == 1.0f`
108
- // TODO: start reading the actual value of mscale and handle the case where it is not 1.0f
109
- float mscale = 1.0f;
110
- const float mscale_all_dims = hparams.rope_yarn_log_mul;
111
-
112
- // [TAG_DEEPSEEK2_YARN_LOG_MUL_FIX]
113
- // special-case DEEPSEEK v2:
114
- // https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite-Chat/blob/main/config.json#L42-L43
115
- if (model.arch == LLM_ARCH_DEEPSEEK2 && mscale_all_dims != 1.0f) {
116
- mscale = mscale_all_dims;
117
- }
118
-
119
- cparams.yarn_attn_factor = get_mscale(factor, mscale) / get_mscale(factor, mscale_all_dims);
120
-
121
- LLAMA_LOG_WARN("%s: setting new yarn_attn_factor = %.4f (mscale == %.1f, mscale_all_dim = %.1f)\n",
122
- __func__, cparams.yarn_attn_factor, mscale, mscale_all_dims);
123
- } else {
124
- cparams.yarn_attn_factor = get_mscale(factor, 1.0f);
125
- }
126
-
127
- // when YARN is applied with yarn_ext_factor != 0.0f, we need to cancel this factor:
128
- // https://github.com/ggml-org/llama.cpp/blob/a81a569577cc38b32558958b048228150be63eae/ggml/src/ggml-cpu/ops.cpp#L5541-L5544
129
- //
130
- // ref: https://github.com/ggml-org/llama.cpp/discussions/7416
131
- // https://github.com/ggml-org/llama.cpp/pull/17945
132
- cparams.yarn_attn_factor *= 1.0f / (1.0f + 0.1f * logf(factor));
133
- }
134
-
135
- cparams.yarn_attn_factor *= hparams.rope_attn_factor;
136
-
137
- if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
138
- if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
139
- cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
140
- } else {
141
- cparams.pooling_type = hparams.pooling_type;
142
- }
143
- }
144
-
145
- if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
146
- cparams.causal_attn = hparams.causal_attn;
147
- } else {
148
- cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
149
- }
150
-
151
- cparams.flash_attn = params.flash_attn_type != LLAMA_FLASH_ATTN_TYPE_DISABLED;
152
- cparams.auto_fa = params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO;
153
-
154
- cparams.fused_gdn_ar = true;
155
- cparams.fused_gdn_ch = true;
156
- cparams.auto_fgdn = true;
157
-
158
- // with causal attention, the batch size is limited by the context size
159
- cparams.n_batch = cparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
160
-
161
- cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
162
-
163
- cparams.op_offload = params.op_offload;
164
- cparams.kv_unified = params.kv_unified;
165
-
166
- // initialized later
167
- cparams.pipeline_parallel = false;
168
-
169
- {
170
- const char * LLAMA_GRAPH_REUSE_DISABLE = getenv("LLAMA_GRAPH_REUSE_DISABLE");
171
- graph_reuse_disable = LLAMA_GRAPH_REUSE_DISABLE ? (atoi(LLAMA_GRAPH_REUSE_DISABLE) != 0) : graph_reuse_disable;
172
-
173
- if (graph_reuse_disable) {
174
- LLAMA_LOG_WARN("%s: graph reuse disabled\n", __func__);
175
- }
176
- }
177
-
178
- // ref: https://github.com/ggml-org/llama.cpp/pull/17046#discussion_r2503085732
179
- cparams.n_ctx = GGML_PAD(cparams.n_ctx, 256);
180
-
181
- if (cparams.kv_unified) {
182
- cparams.n_ctx_seq = cparams.n_ctx;
183
- } else {
184
- cparams.n_ctx_seq = cparams.n_ctx / cparams.n_seq_max;
185
- cparams.n_ctx_seq = GGML_PAD(cparams.n_ctx_seq, 256);
186
-
187
- if (cparams.n_ctx_seq == 0) {
188
- throw std::runtime_error("n_ctx_seq == 0");
189
- }
190
-
191
- if (cparams.n_ctx != cparams.n_ctx_seq * cparams.n_seq_max) {
192
- cparams.n_ctx = cparams.n_ctx_seq * cparams.n_seq_max;
193
- LLAMA_LOG_WARN("%s: n_ctx is not divisible by n_seq_max - rounding down to %u\n", __func__, cparams.n_ctx);
194
- }
195
- }
196
-
197
- LLAMA_LOG_INFO("%s: n_seq_max = %u\n", __func__, cparams.n_seq_max);
198
- LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
199
- LLAMA_LOG_INFO("%s: n_ctx_seq = %u\n", __func__, cparams.n_ctx_seq);
200
- LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
201
- LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
202
- LLAMA_LOG_INFO("%s: causal_attn = %d\n", __func__, cparams.causal_attn);
203
- LLAMA_LOG_INFO("%s: flash_attn = %s\n", __func__, llama_flash_attn_type_name(params.flash_attn_type));
204
- LLAMA_LOG_INFO("%s: kv_unified = %s\n", __func__, cparams.kv_unified ? "true" : "false");
205
- LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
206
- LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
207
-
208
- if (cparams.n_ctx_seq < hparams.n_ctx_train) {
209
- LLAMA_LOG_WARN("%s: n_ctx_seq (%u) < n_ctx_train (%u) -- the full capacity of the model will not be utilized\n",
210
- __func__, cparams.n_ctx_seq, hparams.n_ctx_train);
211
- }
212
-
213
- if (cparams.n_ctx_seq > hparams.n_ctx_train) {
214
- LLAMA_LOG_WARN("%s: n_ctx_seq (%u) > n_ctx_train (%u) -- possible training context overflow\n",
215
- __func__, cparams.n_ctx_seq, hparams.n_ctx_train);
216
- }
217
-
218
- if (!hparams.vocab_only) {
219
- // GPU backends
220
- for (auto * dev : model.devices) {
221
- ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
222
- if (backend == nullptr) {
223
- throw std::runtime_error(format("failed to initialize %s backend", ggml_backend_dev_name(dev)));
224
- }
225
- backends.emplace_back(backend);
226
- }
227
-
228
- // add ACCEL backends (such as BLAS)
229
- for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
230
- ggml_backend_dev_t dev = ggml_backend_dev_get(i);
231
- if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_ACCEL) {
232
- ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
233
- if (backend == nullptr) {
234
- throw std::runtime_error(format("failed to initialize %s backend", ggml_backend_dev_name(dev)));
235
- }
236
- backends.emplace_back(backend);
237
- }
238
- }
239
-
240
- // add CPU backend
241
- backend_cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
242
- if (backend_cpu == nullptr) {
243
- throw std::runtime_error("failed to initialize CPU backend");
244
- }
245
- backends.emplace_back(backend_cpu);
246
-
247
- // create a list of the set_n_threads functions in the backends
248
- for (auto & backend : backends) {
249
- ggml_backend_dev_t dev = ggml_backend_get_device(backend.get());
250
- ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr;
251
- if (reg) {
252
- auto ggml_backend_set_n_threads_fn = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads");
253
- if (ggml_backend_set_n_threads_fn) {
254
- set_n_threads_fns.emplace_back(backend.get(), ggml_backend_set_n_threads_fn);
255
- }
256
- }
257
- }
258
-
259
- llama_set_abort_callback(this, params.abort_callback, params.abort_callback_data);
260
-
261
- // graph outputs buffer
262
- {
263
- if (output_reserve(params.n_seq_max) < params.n_seq_max) {
264
- throw std::runtime_error("failed to reserve initial output buffer");
265
- }
266
-
267
- LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
268
- ggml_backend_buffer_name (buf_output.get()),
269
- ggml_backend_buffer_get_size(buf_output.get()) / 1024.0 / 1024.0);
270
- }
271
- }
272
-
273
- // init the memory module
274
- if (!hparams.vocab_only) {
275
- llama_memory_params params_mem = {
276
- /*.type_k =*/ params.type_k,
277
- /*.type_v =*/ params.type_v,
278
- /*.swa_full =*/ params.swa_full,
279
- };
280
-
281
- memory.reset(model.create_memory(params_mem, cparams));
282
- }
283
-
284
- // init backends
285
- if (!hparams.vocab_only) {
286
- LLAMA_LOG_DEBUG("%s: enumerating backends\n", __func__);
287
-
288
- backend_buft.clear();
289
- backend_ptrs.clear();
290
- backend_buf_exp_size.clear();
291
-
292
- for (auto & backend : backends) {
293
- auto * buft = ggml_backend_get_default_buffer_type(backend.get());
294
- auto backend_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
295
-
296
- if (backend_type == GGML_BACKEND_DEVICE_TYPE_CPU && !model.devices.empty()) {
297
- // use the host buffer of the first device CPU for faster transfer of the intermediate state
298
- auto * dev = model.devices[0];
299
- auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
300
- if (host_buft) {
301
- buft = host_buft;
302
- }
303
- }
304
-
305
- backend_buft.push_back(buft);
306
- backend_ptrs.push_back(backend.get());
307
- backend_buf_exp_size.push_back(0);
308
- }
309
-
310
- LLAMA_LOG_DEBUG("%s: backend_ptrs.size() = %zu\n", __func__, backend_ptrs.size());
311
-
312
- // TODO: move these checks to ggml_backend_sched
313
- // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
314
- bool pipeline_parallel =
315
- model.n_devices() > 1 &&
316
- model.n_gpu_layers() > model.hparams.n_layer &&
317
- model.split_mode() == LLAMA_SPLIT_MODE_LAYER &&
318
- cparams.offload_kqv &&
319
- !model.has_tensor_overrides();
320
-
321
- // pipeline parallelism requires support for async compute and events in all devices
322
- if (pipeline_parallel) {
323
- for (auto & backend : backends) {
324
- auto dev_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
325
- if (dev_type == GGML_BACKEND_DEVICE_TYPE_CPU) {
326
- // ignore CPU backend
327
- // TODO: should we ignore ACCEL types too?
328
- continue;
329
- }
330
- auto * dev = ggml_backend_get_device(backend.get());
331
- ggml_backend_dev_props props;
332
- ggml_backend_dev_get_props(dev, &props);
333
- if (!props.caps.async || !props.caps.events) {
334
- // device does not support async compute or events
335
- pipeline_parallel = false;
336
- break;
337
- }
338
- }
339
- }
340
-
341
- cparams.pipeline_parallel = pipeline_parallel;
342
-
343
- if (cparams.pipeline_parallel) {
344
- LLAMA_LOG_INFO("%s: pipeline parallelism enabled\n", __func__);
345
-
346
- if (!graph_reuse_disable) {
347
- // TODO: figure out a way to make graph reuse work with pipeline parallelism
348
- // ref: https://github.com/ggml-org/llama.cpp/pull/20463
349
- LLAMA_LOG_WARN("%s: graph reuse is currently not compatible with pipeline parallelism - disabling\n", __func__);
350
-
351
- graph_reuse_disable = true;
352
- }
353
- }
354
-
355
- sched_reserve();
356
-
357
- if (!cparams.flash_attn) {
358
- if (ggml_is_quantized(params.type_v)) {
359
- throw std::runtime_error("quantized V cache was requested, but this requires Flash Attention");
360
- }
361
- }
362
- }
363
-
364
- // Initialize the full vocabulary token ids for backend samplers.
365
- {
366
- const int n_vocab = model.vocab.n_tokens();
367
-
368
- sampling.token_ids_full_vocab.resize(n_vocab);
369
- for (int i = 0; i < n_vocab; ++i) {
370
- sampling.token_ids_full_vocab[i] = i;
371
- }
372
- }
373
- }
374
-
375
- llama_context::~llama_context() {
376
- if (!model.hparams.no_alloc) {
377
- for (size_t i = 0; i < backend_ptrs.size(); ++i) {
378
- ggml_backend_t backend = backend_ptrs[i];
379
- ggml_backend_buffer_type_t buft = backend_buft[i];
380
-
381
- const size_t size_exp = backend_buf_exp_size[i];
382
- const size_t size_act = ggml_backend_sched_get_buffer_size(sched.get(), backend);
383
- if (size_exp == size_act) {
384
- LLAMA_LOG_DEBUG("%s: %10s compute buffer size is %8.4f MiB, matches expectation of %8.4f MiB\n",
385
- __func__, ggml_backend_buft_name(buft), size_act / (1024.0*1024.0), size_exp / (1024.0*1024.0));
386
- } else {
387
- LLAMA_LOG_WARN("%s: %10s compute buffer size of %8.4f MiB, does not match expectation of %8.4f MiB\n",
388
- __func__, ggml_backend_buft_name(buft), size_act / (1024.0*1024.0), size_exp / (1024.0*1024.0));
389
- }
390
- }
391
- }
392
- ggml_opt_free(opt_ctx);
393
- }
394
-
395
- void llama_context::sched_reserve() {
396
- if (!sched_need_reserve) {
397
- return;
398
- }
399
-
400
- sched_need_reserve = false;
401
-
402
- LLAMA_LOG_INFO("%s: reserving ...\n", __func__);
403
-
404
- synchronize();
405
-
406
- const int64_t t_start_us = ggml_time_us();
407
-
408
- const uint32_t n_seqs = cparams.n_seq_max;
409
- const uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
410
-
411
- const size_t max_nodes = this->graph_max_nodes(n_tokens);
412
-
413
- LLAMA_LOG_DEBUG("%s: max_nodes = %zu\n", __func__, max_nodes);
414
-
415
- gf_res_prev.reset(new llm_graph_result(max_nodes));
416
- gf_res_reserve.reset(new llm_graph_result(max_nodes));
417
-
418
- sched.reset(ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), max_nodes, cparams.pipeline_parallel, cparams.op_offload));
419
-
420
- llama_memory_context_ptr mctx;
421
- if (memory) {
422
- LLAMA_LOG_DEBUG("%s: reserving full memory module\n", __func__);
423
- mctx = memory->init_full();
424
- if (!mctx) {
425
- throw std::runtime_error("failed to initialize memory module");
426
- }
427
- }
428
-
429
- // avoid reserving graphs with zero outputs - assume one output per sequence
430
- const int n_outputs = n_seqs;
431
-
432
- LLAMA_LOG_DEBUG("%s: worst-case: n_tokens = %d, n_seqs = %d, n_outputs = %d\n", __func__, n_tokens, n_seqs, n_outputs);
433
-
434
- // resolve automatic Flash Attention use
435
- if (cparams.auto_fa) {
436
- auto * gf = graph_reserve(1, n_seqs, n_outputs, mctx.get(), true);
437
- if (!gf) {
438
- throw std::runtime_error("failed to reserve graph for Flash Attention check");
439
- }
440
-
441
- const size_t prefix_len = strlen(LLAMA_TENSOR_NAME_FATTN) + 1;
442
- bool fa_device_mismatch = false;
443
- for (int i = 0; i < ggml_graph_n_nodes(gf); i++) {
444
- ggml_tensor * n = ggml_graph_node(gf, i);
445
- if (n->op != GGML_OP_FLASH_ATTN_EXT) {
446
- continue;
447
- }
448
- ggml_backend_dev_t device_fa = ggml_backend_get_device(ggml_backend_sched_get_tensor_backend(sched.get(), n));
449
-
450
- // TODO: instead of the tensor names, use a map to keep track of which (FA) tensors belong to which layer
451
- GGML_ASSERT(strncmp(n->name, LLAMA_TENSOR_NAME_FATTN "-", prefix_len) == 0);
452
- const int il = std::stoi(n->name + prefix_len);
453
- ggml_backend_dev_t device_kv = model.dev_layer(il);
454
- if (device_fa != device_kv) {
455
- LLAMA_LOG_WARN("%s: layer %d is assigned to device %s but the Flash Attention tensor "
456
- "is assigned to device %s (usually due to missing support)\n",
457
- __func__, il, ggml_backend_dev_name(device_kv), ggml_backend_dev_name(device_fa));
458
- // FIXME: fa_device_mismatch logic is wrong for --no-kv-offload, but this is broken anyways
459
- fa_device_mismatch = true;
460
- break;
461
- }
462
- }
463
-
464
- if (fa_device_mismatch) {
465
- cparams.flash_attn = false;
466
- LLAMA_LOG_WARN("%s: Flash Attention was auto, set to disabled\n", __func__);
467
- } else {
468
- cparams.flash_attn = true;
469
- LLAMA_LOG_INFO("%s: Flash Attention was auto, set to enabled\n", __func__);
470
- }
471
-
472
- cparams.auto_fa = false;
473
- }
474
-
475
- if (cparams.auto_fgdn) {
476
- LLAMA_LOG_INFO("%s: resolving fused Gated Delta Net support:\n", __func__);
477
-
478
- if (cparams.fused_gdn_ar) {
479
- auto * gf = graph_reserve(1, n_seqs, n_outputs, mctx.get(), true);
480
- if (!gf) {
481
- throw std::runtime_error("failed to reserve graph for fused Gated Delta Net check (autoregressive)");
482
- }
483
-
484
- const size_t prefix_len = strlen(LLAMA_TENSOR_NAME_FGDN_AR) + 1;
485
- bool gdn_device_mismatch = false;
486
- for (int i = 0; i < ggml_graph_n_nodes(gf); i++) {
487
- ggml_tensor * n = ggml_graph_node(gf, i);
488
- if (n->op != GGML_OP_GATED_DELTA_NET) {
489
- continue;
490
- }
491
- ggml_backend_dev_t device_gdn = ggml_backend_get_device(ggml_backend_sched_get_tensor_backend(sched.get(), n));
492
-
493
- GGML_ASSERT(strncmp(n->name, LLAMA_TENSOR_NAME_FGDN_AR "-", prefix_len) == 0);
494
- const int il = std::stoi(n->name + prefix_len);
495
- ggml_backend_dev_t device_kv = model.dev_layer(il);
496
- if (device_gdn != device_kv) {
497
- LLAMA_LOG_WARN("%s: layer %d is assigned to device %s but the fused Gated Delta Net tensor "
498
- "is assigned to device %s (usually due to missing support)\n",
499
- __func__, il, ggml_backend_dev_name(device_kv), ggml_backend_dev_name(device_gdn));
500
- gdn_device_mismatch = true;
501
- break;
502
- }
503
- }
504
-
505
- if (gdn_device_mismatch) {
506
- cparams.fused_gdn_ar = false;
507
- LLAMA_LOG_WARN("%s: fused Gated Delta Net (autoregressive) not supported, set to disabled\n", __func__);
508
- } else {
509
- LLAMA_LOG_INFO("%s: fused Gated Delta Net (autoregressive) enabled\n", __func__);
510
- }
511
- }
512
-
513
- if (cparams.fused_gdn_ch) {
514
- // more than one token in the batch per sequence in order to take the chunked path
515
- // note: n_outputs must match n_tokens for embedding models with mean/rank pooling,
516
- // because build_pooling creates inp_mean with shape [n_tokens, n_seqs] and multiplies
517
- // it with t_embd which is reduced to [n_outputs, ...] via out_ids. if n_outputs != n_tokens,
518
- // the ggml_mul_mat assertion fails. this matches the pp reservation below (line ~553).
519
- const uint32_t n_tokens_ch = 16*n_seqs;
520
- auto * gf = graph_reserve(n_tokens_ch, n_seqs, n_tokens_ch, mctx.get(), true);
521
- if (!gf) {
522
- throw std::runtime_error("failed to reserve graph for fused Gated Delta Net check (chunked)");
523
- }
524
-
525
- const size_t prefix_len = strlen(LLAMA_TENSOR_NAME_FGDN_CH) + 1;
526
- bool gdn_device_mismatch = false;
527
- for (int i = 0; i < ggml_graph_n_nodes(gf); i++) {
528
- ggml_tensor * n = ggml_graph_node(gf, i);
529
- if (n->op != GGML_OP_GATED_DELTA_NET) {
530
- continue;
531
- }
532
- ggml_backend_dev_t device_gdn = ggml_backend_get_device(ggml_backend_sched_get_tensor_backend(sched.get(), n));
533
-
534
- GGML_ASSERT(strncmp(n->name, LLAMA_TENSOR_NAME_FGDN_CH "-", prefix_len) == 0);
535
- const int il = std::stoi(n->name + prefix_len);
536
- ggml_backend_dev_t device_kv = model.dev_layer(il);
537
- if (device_gdn != device_kv) {
538
- LLAMA_LOG_WARN("%s: layer %d is assigned to device %s but the fused Gated Delta Net tensor "
539
- "is assigned to device %s (usually due to missing support)\n",
540
- __func__, il, ggml_backend_dev_name(device_kv), ggml_backend_dev_name(device_gdn));
541
- gdn_device_mismatch = true;
542
- break;
543
- }
544
- }
545
-
546
- if (gdn_device_mismatch) {
547
- cparams.fused_gdn_ch = false;
548
- LLAMA_LOG_WARN("%s: fused Gated Delta Net (chunked) not supported, set to disabled\n", __func__);
549
- } else {
550
- LLAMA_LOG_INFO("%s: fused Gated Delta Net (chunked) enabled\n", __func__);
551
- }
552
- }
553
-
554
- cparams.auto_fgdn = false;
555
- }
556
-
557
- // reserve worst-case graph
558
- int n_splits_pp = -1;
559
- int n_nodes_pp = -1;
560
-
561
- int n_splits_tg = -1;
562
- int n_nodes_tg = -1;
563
-
564
- // reserve pp (prompt processing) graph first so that buffers are only allocated once
565
- {
566
- auto * gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get(),
567
- model.hparams.no_alloc, model.hparams.no_alloc ? backend_buf_exp_size.data() : nullptr);
568
- if (!gf) {
569
- if (cparams.pipeline_parallel) {
570
- LLAMA_LOG_WARN("%s: compute buffer allocation failed, retrying without pipeline parallelism\n", __func__);
571
- cparams.pipeline_parallel = false;
572
- sched.reset(ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), max_nodes, false, cparams.op_offload));
573
- gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get());
574
- }
575
- if (!gf) {
576
- throw std::runtime_error("failed to allocate compute pp buffers");
577
- }
578
- }
579
-
580
- n_splits_pp = ggml_backend_sched_get_n_splits(sched.get());
581
- n_nodes_pp = ggml_graph_n_nodes(gf);
582
- }
583
-
584
- // reserve with tg (token generation) graph to get the number of splits and nodes
585
- {
586
- auto * gf = graph_reserve(n_seqs, n_seqs, n_seqs, mctx.get(), model.hparams.no_alloc);
587
- if (!gf) {
588
- throw std::runtime_error("failed to allocate compute tg buffers");
589
- }
590
-
591
- n_splits_tg = ggml_backend_sched_get_n_splits(sched.get());
592
- n_nodes_tg = ggml_graph_n_nodes(gf);
593
- }
594
-
595
- // reserve again with pp graph to avoid ggml-alloc reallocations during inference
596
- {
597
- // TODO: not sure if the following graph would be worster case for multi-stream KV caches:
598
- //
599
- // auto * gf = graph_reserve(n_tokens, 1, n_tokens, mctx.get());
600
- //
601
- auto * gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get(), model.hparams.no_alloc);
602
- if (!gf) {
603
- throw std::runtime_error("failed to allocate compute pp buffers");
604
- }
605
- }
606
-
607
- for (size_t i = 0; i < backend_ptrs.size(); ++i) {
608
- ggml_backend_t backend = backend_ptrs[i];
609
- ggml_backend_buffer_type_t buft = backend_buft[i];
610
- if (!model.hparams.no_alloc) {
611
- backend_buf_exp_size[i] = ggml_backend_sched_get_buffer_size(sched.get(), backend);
612
- }
613
- if (backend_buf_exp_size[i] > 1) {
614
- LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
615
- ggml_backend_buft_name(buft),
616
- backend_buf_exp_size[i] / 1024.0 / 1024.0);
617
- }
618
- }
619
-
620
- if (n_nodes_pp == n_nodes_tg) {
621
- LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, n_nodes_pp);
622
- } else {
623
- LLAMA_LOG_INFO("%s: graph nodes = %d (with bs=%d), %d (with bs=1)\n", __func__, n_nodes_pp, n_tokens, n_nodes_tg);
624
- }
625
-
626
- if (n_splits_pp == n_splits_tg) {
627
- LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits_pp);
628
- } else {
629
- LLAMA_LOG_INFO("%s: graph splits = %d (with bs=%d), %d (with bs=1)\n", __func__, n_splits_pp, n_tokens, n_splits_tg);
630
- }
631
-
632
- const int64_t t_end_us = ggml_time_us();
633
-
634
- LLAMA_LOG_INFO("%s: reserve took %.2f ms, sched copies = %d\n",
635
- __func__, (t_end_us - t_start_us)/1000.0, ggml_backend_sched_get_n_copies(sched.get()));
636
- }
637
-
638
- void llama_context::synchronize() {
639
- if (!sched) {
640
- return;
641
- }
642
-
643
- ggml_backend_sched_synchronize(sched.get());
644
-
645
- // FIXME: if multiple single tokens are evaluated without a synchronization,
646
- // the stats will be added to the prompt evaluation stats
647
- // this should only happen when using batch size 1 to evaluate a batch
648
-
649
- // add the evaluation to the stats
650
- if (n_queued_tokens == 1) {
651
- if (!cparams.no_perf) {
652
- t_eval_us += ggml_time_us() - t_compute_start_us;
653
- }
654
- n_eval++;
655
- } else if (n_queued_tokens > 1) {
656
- if (!cparams.no_perf) {
657
- t_p_eval_us += ggml_time_us() - t_compute_start_us;
658
- }
659
- n_p_eval += n_queued_tokens;
660
- }
661
-
662
- // get a more accurate load time, upon first eval
663
- if (n_queued_tokens > 0 && !has_evaluated_once) {
664
- t_load_us = ggml_time_us() - t_start_us;
665
- has_evaluated_once = true;
666
- }
667
-
668
- n_queued_tokens = 0;
669
- t_compute_start_us = 0;
670
- }
671
-
672
- const llama_model & llama_context::get_model() const {
673
- return model;
674
- }
675
-
676
- const llama_cparams & llama_context::get_cparams() const {
677
- return cparams;
678
- }
679
-
680
- ggml_backend_sched_t llama_context::get_sched() const {
681
- return sched.get();
682
- }
683
-
684
- uint32_t llama_context::n_ctx() const {
685
- return cparams.n_ctx;
686
- }
687
-
688
- uint32_t llama_context::n_ctx_seq() const {
689
- return cparams.n_ctx_seq;
690
- }
691
-
692
- uint32_t llama_context::n_batch() const {
693
- return cparams.n_batch;
694
- }
695
-
696
- uint32_t llama_context::n_ubatch() const {
697
- return cparams.n_ubatch;
698
- }
699
-
700
- uint32_t llama_context::n_seq_max() const {
701
- return cparams.n_seq_max;
702
- }
703
-
704
- uint32_t llama_context::n_threads() const {
705
- return cparams.n_threads;
706
- }
707
-
708
- uint32_t llama_context::n_threads_batch() const {
709
- return cparams.n_threads_batch;
710
- }
711
-
712
- llama_memory_t llama_context::get_memory() const {
713
- return memory.get();
714
- }
715
-
716
- bool llama_context::memory_update(bool optimize) {
717
- if (!memory) {
718
- return false;
719
- }
720
-
721
- {
722
- const auto mctx = memory->init_update(this, optimize);
723
- switch (mctx->get_status()) {
724
- case LLAMA_MEMORY_STATUS_SUCCESS:
725
- {
726
- // noop
727
- } break;
728
- case LLAMA_MEMORY_STATUS_NO_UPDATE:
729
- {
730
- // no updates need to be performed
731
- return false;
732
- }
733
- case LLAMA_MEMORY_STATUS_FAILED_PREPARE:
734
- case LLAMA_MEMORY_STATUS_FAILED_COMPUTE:
735
- {
736
- LLAMA_LOG_ERROR("%s: failed to prepare memory update\n", __func__);
737
- return false;
738
- }
739
- }
740
-
741
- // reset the previous graph result to make sure that it won't be reused
742
- // TODO: change the mctx->apply() to return information if a graph reserve is needed
743
- // reset the graph result only if the memory module did reset the scheduler
744
- gf_res_prev->reset();
745
-
746
- if (!mctx->apply()) {
747
- LLAMA_LOG_ERROR("%s: failed to apply memory update\n", __func__);
748
- }
749
- }
750
-
751
- // if the memory module did any computation, we have to reserve a new worst-case graph
752
- {
753
- const auto mctx = memory->init_full();
754
- if (!mctx) {
755
- throw std::runtime_error("failed to initialize memory context");
756
- }
757
-
758
- const uint32_t n_seqs = cparams.n_seq_max;
759
- const uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
760
-
761
- auto * gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get());
762
- if (!gf) {
763
- LLAMA_LOG_ERROR("%s: failed to reserve graph after the memory update\n", __func__);
764
- }
765
- }
766
-
767
- return true;
768
- }
769
-
770
- enum llama_pooling_type llama_context::pooling_type() const {
771
- return cparams.pooling_type;
772
- }
773
-
774
- float * llama_context::get_logits() {
775
- output_reorder();
776
-
777
- return logits.data;
778
- }
779
-
780
- int64_t llama_context::output_resolve_row(int32_t i) const {
781
- int64_t j = -1;
782
-
783
- // support negative indices (last output row)
784
- if (i < 0) {
785
- j = n_outputs + i;
786
- if (j < 0) {
787
- throw std::runtime_error(format("negative index out of range [0, %d)", n_outputs));
788
- }
789
- } else if ((size_t) i >= output_ids.size()) {
790
- throw std::runtime_error(format("out of range [0, %zu)", output_ids.size()));
791
- } else {
792
- // use output_ids to translate the batch token index into a row number
793
- // that holds this token's data.
794
- j = output_ids[i];
795
- }
796
-
797
- if (j < 0) {
798
- // the batch token was not configured to output anything
799
- throw std::runtime_error(format("batch.logits[%d] != true", i));
800
- }
801
-
802
- if (j >= n_outputs) {
803
- throw std::runtime_error(format("corrupt output buffer (j=%" PRId64 ", n_outputs=%d)", j, n_outputs));
804
- }
805
-
806
- return j;
807
- }
808
-
809
- float * llama_context::get_logits_ith(int32_t i) {
810
- output_reorder();
811
-
812
- try {
813
- if (logits.data == nullptr) {
814
- throw std::runtime_error("no logits");
815
- }
816
-
817
- const int64_t j = output_resolve_row(i);
818
- return logits.data + j*model.vocab.n_tokens();
819
- } catch (const std::exception & err) {
820
- LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
821
- #ifndef NDEBUG
822
- GGML_ABORT("fatal error");
823
- #else
824
- return nullptr;
825
- #endif
826
- }
827
- }
828
-
829
- float * llama_context::get_embeddings() {
830
- output_reorder();
831
-
832
- return embd.data;
833
- }
834
-
835
- llama_token * llama_context::get_sampled_tokens() const{
836
- return sampling.sampled.data;
837
- }
838
-
839
- float * llama_context::get_embeddings_ith(int32_t i) {
840
- output_reorder();
841
-
842
- try {
843
- if (embd.data == nullptr) {
844
- throw std::runtime_error("no embeddings");
845
- }
846
-
847
- const int64_t j = output_resolve_row(i);
848
- const uint32_t n_embd_out = model.hparams.n_embd_out();
849
- return embd.data + j*n_embd_out;
850
- } catch (const std::exception & err) {
851
- LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
852
- #ifndef NDEBUG
853
- GGML_ABORT("fatal error");
854
- #else
855
- return nullptr;
856
- #endif
857
- }
858
- }
859
-
860
- float * llama_context::get_embeddings_seq(llama_seq_id seq_id) {
861
- auto it = embd_seq.find(seq_id);
862
- if (it == embd_seq.end()) {
863
- return nullptr;
864
- }
865
-
866
- return it->second.data();
867
- }
868
-
869
- llama_token llama_context::get_sampled_token_ith(int32_t idx) {
870
- output_reorder();
871
-
872
- if (!sampling.sampled.has_data()) {
873
- return LLAMA_TOKEN_NULL;
874
- }
875
-
876
- try {
877
- const int64_t row = output_resolve_row(idx);
878
- GGML_ASSERT(row < (int64_t) sampling.sampled.size);
879
- return sampling.sampled.data[row];
880
- } catch (const std::exception & err) {
881
- LLAMA_LOG_ERROR("%s: invalid backend sampled token id %d, reason: %s\n", __func__, idx, err.what());
882
- return LLAMA_TOKEN_NULL;
883
- }
884
- }
885
-
886
- float * llama_context::get_sampled_probs_ith(int32_t idx) {
887
- output_reorder();
888
-
889
- if (!sampling.probs.has_data()) {
890
- return nullptr;
891
- }
892
-
893
- try {
894
- const int64_t row = output_resolve_row(idx);
895
- if ((size_t) row >= sampling.probs_count.size() || sampling.probs_count[row] == 0) {
896
- return nullptr;
897
- }
898
- return sampling.probs.data + row*model.vocab.n_tokens();
899
- } catch (const std::exception & err) {
900
- LLAMA_LOG_ERROR("%s: invalid backend sampled probs id %d, reason: %s\n", __func__, idx, err.what());
901
- return nullptr;
902
- }
903
- }
904
-
905
- float * llama_context::get_sampled_logits_ith(int32_t idx) {
906
- output_reorder();
907
-
908
- if (!sampling.logits.has_data()) {
909
- return nullptr;
910
- }
911
-
912
- try {
913
- const int64_t row = output_resolve_row(idx);
914
- if ((size_t) row >= sampling.logits_count.size() || sampling.logits_count[row] == 0) {
915
- return nullptr;
916
- }
917
- return sampling.logits.data + row*model.vocab.n_tokens();
918
- } catch (const std::exception & err) {
919
- LLAMA_LOG_ERROR("%s: invalid backend sampled logits id %d, reason: %s\n", __func__, idx, err.what());
920
- return nullptr;
921
- }
922
- }
923
-
924
- const llama_token * llama_context::get_sampled_candidates_ith(int32_t idx) {
925
- output_reorder();
926
-
927
- try {
928
- const int64_t row = output_resolve_row(idx);
929
- if (sampling.candidates.has_data() &&
930
- (size_t) row < sampling.candidates_count.size() &&
931
- sampling.candidates_count[row] > 0) {
932
- return sampling.candidates.data + row*model.vocab.n_tokens();
933
- }
934
- } catch (const std::exception & err) {
935
- // fallback to full vocab list
936
- GGML_UNUSED(err);
937
- }
938
-
939
- return sampling.token_ids_full_vocab.data();
940
- }
941
-
942
- size_t llama_context::get_sampled_candidates_count(int32_t idx) {
943
- output_reorder();
944
-
945
- if (!sampling.candidates.has_data()) {
946
- return 0;
947
- }
948
-
949
- try {
950
- const int64_t row = output_resolve_row(idx);
951
- if ((size_t) row >= sampling.candidates_count.size()) {
952
- return 0;
953
- }
954
- return sampling.candidates_count[row];
955
- } catch (const std::exception & err) {
956
- LLAMA_LOG_ERROR("%s: invalid backend sampled candidates count id %d, reason: %s\n", __func__, idx, err.what());
957
- return 0;
958
- }
959
- }
960
-
961
- size_t llama_context::get_sampled_logits_count(int32_t idx) {
962
- output_reorder();
963
-
964
- if (!sampling.logits.has_data()) {
965
- return model.vocab.n_tokens();
966
- }
967
-
968
- try {
969
- const int64_t row = output_resolve_row(idx);
970
- if ((size_t) row >= sampling.logits_count.size()) {
971
- return 0;
972
- }
973
- return sampling.logits_count[row];
974
- } catch (const std::exception & err) {
975
- LLAMA_LOG_ERROR("%s: invalid backend sampled logits count id %d, reason: %s\n", __func__, idx, err.what());
976
- return 0;
977
- }
978
- }
979
-
980
- size_t llama_context::get_sampled_probs_count(int32_t idx) {
981
- output_reorder();
982
-
983
- if (!sampling.probs.has_data()) {
984
- return 0;
985
- }
986
-
987
- try {
988
- const int64_t row = output_resolve_row(idx);
989
- if ((size_t) row >= sampling.probs_count.size()) {
990
- return 0;
991
- }
992
- return sampling.probs_count[row];
993
- } catch (const std::exception & err) {
994
- LLAMA_LOG_ERROR("%s: invalid backend sampled probs count id %d, reason: %s\n", __func__, idx, err.what());
995
- return 0;
996
- }
997
- }
998
-
999
-
1000
- void llama_context::attach_threadpool(
1001
- ggml_threadpool_t threadpool,
1002
- ggml_threadpool_t threadpool_batch) {
1003
- LLAMA_LOG_DEBUG("%s: call\n", __func__);
1004
-
1005
- this->threadpool = threadpool;
1006
- this->threadpool_batch = threadpool_batch ? threadpool_batch : threadpool;
1007
- }
1008
-
1009
- void llama_context::detach_threadpool() {
1010
- LLAMA_LOG_DEBUG("%s: call\n", __func__);
1011
-
1012
- this->threadpool = nullptr;
1013
- this->threadpool_batch = nullptr;
1014
- }
1015
-
1016
- void llama_context::set_n_threads(int32_t n_threads, int32_t n_threads_batch) {
1017
- LLAMA_LOG_DEBUG("%s: n_threads = %d, n_threads_batch = %d\n", __func__, n_threads, n_threads_batch);
1018
-
1019
- cparams.n_threads = n_threads;
1020
- cparams.n_threads_batch = n_threads_batch;
1021
- }
1022
-
1023
- void llama_context::set_abort_callback(bool (*abort_callback)(void * data), void * abort_callback_data) {
1024
- LLAMA_LOG_DEBUG("%s: call\n", __func__);
1025
-
1026
- this->abort_callback = abort_callback;
1027
- this->abort_callback_data = abort_callback_data;
1028
-
1029
- for (auto & backend : backends) {
1030
- auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend.get()));
1031
- auto * set_abort_callback_fn = (ggml_backend_set_abort_callback_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_abort_callback");
1032
- if (set_abort_callback_fn) {
1033
- set_abort_callback_fn(backend.get(), this->abort_callback, this->abort_callback_data);
1034
- }
1035
- }
1036
- }
1037
-
1038
- void llama_context::set_embeddings(bool value) {
1039
- LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value);
1040
-
1041
- cparams.embeddings = value;
1042
-
1043
- // TODO: not sure yet if we want to reserve here
1044
- //sched_need_reserve = true;
1045
- }
1046
-
1047
- void llama_context::set_causal_attn(bool value) {
1048
- LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value);
1049
-
1050
- if (cparams.causal_attn == value) {
1051
- return;
1052
- }
1053
-
1054
- cparams.causal_attn = value;
1055
-
1056
- sched_need_reserve = true;
1057
- }
1058
-
1059
- void llama_context::set_warmup(bool value) {
1060
- LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value);
1061
-
1062
- if (cparams.warmup == value) {
1063
- return;
1064
- }
1065
-
1066
- cparams.warmup = value;
1067
-
1068
- // warmups are usually with small batches, so no need to reserve
1069
- //sched_need_reserve = true;
1070
- }
1071
-
1072
- bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) {
1073
- if (!sampler && sampling.samplers.count(seq_id) == 0) {
1074
- return true;
1075
- }
1076
-
1077
- LLAMA_LOG_DEBUG("%s: seq_id = %d, sampler = %p\n", __func__, (int) seq_id, (void *) sampler);
1078
-
1079
- const bool can_offload =
1080
- sampler &&
1081
- sampler->iface->backend_init &&
1082
- sampler->iface->backend_apply &&
1083
- llama_sampler_chain_n(sampler) > 0;
1084
-
1085
- if (sampler && can_offload) {
1086
- auto * buft = ggml_backend_dev_buffer_type(model.dev_output());
1087
-
1088
- sampler->iface->backend_init(sampler, buft);
1089
-
1090
- sampling.samplers[seq_id] = sampler;
1091
-
1092
- sched_need_reserve = true;
1093
-
1094
- return true;
1095
- }
1096
-
1097
- if (sampler && !can_offload) {
1098
- LLAMA_LOG_WARN("%s: sampler '%s' for seq_id = %d, cannot be offloaded to the backend\n", __func__, llama_sampler_name(sampler), seq_id);
1099
-
1100
- if (sampling.samplers.count(seq_id) > 0) {
1101
- sched_need_reserve = true;
1102
- }
1103
-
1104
- sampling.samplers.erase(seq_id);
1105
-
1106
- return false;
1107
- }
1108
-
1109
- sampling.samplers.erase(seq_id);
1110
-
1111
- sched_need_reserve = true;
1112
-
1113
- return true;
1114
- }
1115
-
1116
- void llama_context::set_adapters_lora(llama_adapter_lora ** adapters, size_t n_adapters, float * scales) {
1117
- LLAMA_LOG_DEBUG("%s: adapters = %p\n", __func__, (void *) adapters);
1118
-
1119
- if (adapters_lora_are_same(adapters, n_adapters, scales)) {
1120
- return;
1121
- }
1122
-
1123
- loras.reset(new llama_adapter_loras());
1124
-
1125
- for (size_t i = 0; i < n_adapters; i ++) {
1126
- if (scales[i] != 0.0f) {
1127
- loras->insert({adapters[i], scales[i]});
1128
- }
1129
- }
1130
-
1131
- sched_need_reserve = true;
1132
- }
1133
-
1134
- bool llama_context::adapters_lora_are_same(llama_adapter_lora ** adapters, size_t n_adapters, float * scales) {
1135
- LLAMA_LOG_DEBUG("%s: adapters = %p\n", __func__, (void *) adapters);
1136
-
1137
- // Adapters with a zero scale are never added to `loras`, so also ignore them for the comparison.
1138
- size_t n_non_zero = 0;
1139
-
1140
- for (size_t i = 0; i < n_adapters; i ++) {
1141
- if (scales[i] == 0.0f) {
1142
- continue;
1143
- }
1144
- n_non_zero++;
1145
-
1146
- auto it = loras->find(adapters[i]);
1147
-
1148
- if (it == loras->end() || it->second != scales[i]) {
1149
- return false;
1150
- }
1151
- }
1152
-
1153
- if (n_non_zero != loras->size()) {
1154
- return false;
1155
- }
1156
-
1157
- return true;
1158
- }
1159
-
1160
- bool llama_context::set_adapter_cvec(
1161
- const float * data,
1162
- size_t len,
1163
- int32_t n_embd,
1164
- int32_t il_start,
1165
- int32_t il_end) {
1166
- LLAMA_LOG_DEBUG("%s: il_start = %d, il_end = %d\n", __func__, il_start, il_end);
1167
-
1168
- // TODO: should we reserve?
1169
-
1170
- return cvec->apply(model, data, len, n_embd, il_start, il_end);
1171
- }
1172
-
1173
- llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, llm_graph_type gtype, llama_memory_context_i * mctx, ggml_status & ret) {
1174
- if (mctx && !mctx->apply()) {
1175
- LLAMA_LOG_ERROR("%s: failed to apply memory context\n", __func__);
1176
- ret = GGML_STATUS_FAILED;
1177
- return nullptr;
1178
- }
1179
-
1180
- auto * res = gf_res_prev.get();
1181
- auto * gf = res->get_gf();
1182
-
1183
- // the new graph parameters
1184
- // in order to correctly reuse a graph, it's full topology has to be uniquely determined by these parameters
1185
- const auto gparams = graph_params(res, ubatch, mctx, gtype);
1186
-
1187
- if (!graph_reuse_disable && res->can_reuse(gparams)) {
1188
- //LLAMA_LOG_DEBUG("%s: reusing previous graph\n", __func__);
1189
-
1190
- n_reused++;
1191
- } else {
1192
- res->reset();
1193
-
1194
- ggml_backend_sched_reset(sched.get());
1195
- ggml_backend_sched_set_eval_callback(sched.get(), cparams.cb_eval, cparams.cb_eval_user_data);
1196
-
1197
- //const auto t_start_us = ggml_time_us();
1198
-
1199
- gf = model.build_graph(gparams);
1200
-
1201
- //LLAMA_LOG_INFO("graph build time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0);
1202
-
1203
- if (!gf) {
1204
- LLAMA_LOG_ERROR("%s: failed to initialize graph\n", __func__);
1205
- ret = GGML_STATUS_FAILED;
1206
- return nullptr;
1207
- }
1208
-
1209
- if (!ggml_backend_sched_alloc_graph(sched.get(), gf)) {
1210
- LLAMA_LOG_ERROR("%s: failed to allocate graph\n", __func__);
1211
- ret = GGML_STATUS_ALLOC_FAILED;
1212
- return nullptr;
1213
- }
1214
- }
1215
-
1216
- // set the input data for the input tensors
1217
- {
1218
- //const auto t_start_us = ggml_time_us();
1219
-
1220
- // FIXME this call causes a crash if any model inputs were not used in the graph and were therefore not allocated
1221
- res->set_inputs(&ubatch);
1222
-
1223
- //LLAMA_LOG_INFO("graph set inputs time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0);
1224
- }
1225
-
1226
- const auto status = graph_compute(res->get_gf(), ubatch.n_tokens > 1);
1227
- if (status != GGML_STATUS_SUCCESS) {
1228
- LLAMA_LOG_ERROR("%s: failed to compute graph, compute status: %d\n", __func__, status);
1229
- ret = status;
1230
- return nullptr;
1231
- }
1232
-
1233
- ret = GGML_STATUS_SUCCESS;
1234
-
1235
- return res;
1236
- }
1237
-
1238
- int llama_context::encode(const llama_batch & batch_inp) {
1239
- GGML_ASSERT((!batch_inp.token && batch_inp.embd) || (batch_inp.token && !batch_inp.embd)); // NOLINT
1240
-
1241
- if (batch_inp.n_tokens == 0) {
1242
- LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
1243
- return -1;
1244
- }
1245
-
1246
- const auto & hparams = model.hparams;
1247
-
1248
- const int64_t n_embd = hparams.n_embd_inp();
1249
- const int64_t n_vocab = model.vocab.n_tokens();
1250
-
1251
- // note: during encode, we always pass the full sequence starting from pos = 0
1252
- if (!balloc->init(batch_inp, model.vocab, nullptr, n_embd, cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max, true)) {
1253
- LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__);
1254
- return -1;
1255
- }
1256
-
1257
- const uint32_t n_tokens = balloc->get_n_tokens();
1258
-
1259
- // [TAG_NO_CACHE_PAD]
1260
- // TODO: add new split mode where we pad the input sequences so that ubatch.equal_seqs == true
1261
- const llama_ubatch ubatch = balloc->split_simple(n_tokens);
1262
-
1263
- // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
1264
- GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
1265
-
1266
- if (t_compute_start_us == 0) {
1267
- t_compute_start_us = ggml_time_us();
1268
- }
1269
-
1270
- // TODO: this clear of the buffer can easily be forgotten - need something better
1271
- embd_seq.clear();
1272
-
1273
- sched_reserve();
1274
-
1275
- n_queued_tokens += n_tokens;
1276
-
1277
- // reserve output buffer
1278
- if (output_reserve(n_tokens) < n_tokens) {
1279
- LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
1280
- return -2;
1281
- };
1282
-
1283
- for (uint32_t i = 0; i < n_tokens; ++i) {
1284
- output_ids[i] = i;
1285
- }
1286
-
1287
- n_outputs = n_tokens;
1288
-
1289
- const auto causal_attn_org = cparams.causal_attn;
1290
-
1291
- // always use non-causal attention for encoder graphs
1292
- // TODO: this is a tmp solution until we have a proper way to support enc-dec models
1293
- // ref: https://github.com/ggml-org/llama.cpp/pull/12181#issuecomment-2730451223
1294
- cparams.causal_attn = false;
1295
-
1296
- ggml_status status;
1297
- const auto * res = process_ubatch(ubatch, LLM_GRAPH_TYPE_ENCODER, nullptr, status);
1298
-
1299
- cparams.causal_attn = causal_attn_org;
1300
-
1301
- if (!res) {
1302
- switch (status) {
1303
- case GGML_STATUS_ABORTED: return 2;
1304
- case GGML_STATUS_ALLOC_FAILED: return -2;
1305
- case GGML_STATUS_FAILED: return -3;
1306
- case GGML_STATUS_SUCCESS: GGML_ABORT("should not happen");
1307
- }
1308
- }
1309
-
1310
- auto * t_logits = res->get_logits();
1311
- auto * t_embd = res->get_embd_pooled() ? res->get_embd_pooled() : res->get_embd();
1312
-
1313
- // extract logits
1314
- if (logits.data && t_logits) {
1315
- ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits);
1316
- GGML_ASSERT(backend_res != nullptr);
1317
- GGML_ASSERT(logits.data != nullptr);
1318
-
1319
- ggml_backend_tensor_get_async(backend_res, t_logits, logits.data, 0, n_tokens*n_vocab*sizeof(float));
1320
- }
1321
-
1322
- // extract embeddings
1323
- if (embd.data && t_embd) {
1324
- ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd);
1325
- GGML_ASSERT(backend_embd != nullptr);
1326
-
1327
- switch (cparams.pooling_type) {
1328
- case LLAMA_POOLING_TYPE_NONE:
1329
- {
1330
- // extract token embeddings
1331
- GGML_ASSERT(embd.data != nullptr);
1332
- const uint32_t n_embd_out = hparams.n_embd_out();
1333
-
1334
- GGML_ASSERT(n_tokens*n_embd_out <= (int64_t) embd.size);
1335
- ggml_backend_tensor_get_async(backend_embd, t_embd, embd.data, 0, n_tokens*n_embd_out*sizeof(float));
1336
- } break;
1337
- case LLAMA_POOLING_TYPE_MEAN:
1338
- case LLAMA_POOLING_TYPE_CLS:
1339
- case LLAMA_POOLING_TYPE_LAST:
1340
- {
1341
- // extract sequence embeddings
1342
- auto & embd_seq_out = embd_seq;
1343
-
1344
- for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
1345
- const llama_seq_id seq_id = ubatch.seq_id_unq[s];
1346
- const int32_t seq_idx = ubatch.seq_idx[seq_id];
1347
-
1348
- embd_seq_out[seq_id].resize(n_embd);
1349
- ggml_backend_tensor_get_async(backend_embd, t_embd, embd_seq_out[seq_id].data(), (n_embd*seq_idx)*sizeof(float), n_embd*sizeof(float));
1350
- }
1351
- } break;
1352
- case LLAMA_POOLING_TYPE_RANK:
1353
- {
1354
- // extract the rerank score - n_cls_out floats per sequence
1355
- auto & embd_seq_out = embd_seq;
1356
-
1357
- const uint32_t n_cls_out = hparams.n_cls_out;
1358
-
1359
- for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
1360
- const llama_seq_id seq_id = ubatch.seq_id_unq[s];
1361
- const int32_t seq_idx = ubatch.seq_idx[seq_id];
1362
-
1363
- embd_seq_out[seq_id].resize(n_cls_out);
1364
- ggml_backend_tensor_get_async(backend_embd, t_embd, embd_seq_out[seq_id].data(), (n_cls_out*seq_idx)*sizeof(float), n_cls_out*sizeof(float));
1365
- }
1366
- } break;
1367
- case LLAMA_POOLING_TYPE_UNSPECIFIED:
1368
- {
1369
- GGML_ABORT("unknown pooling type");
1370
- }
1371
- }
1372
- }
1373
-
1374
- // TODO: hacky solution
1375
- if (model.arch == LLM_ARCH_T5 && t_embd) {
1376
- //cross.t_embd = t_embd;
1377
-
1378
- synchronize();
1379
-
1380
- cross.n_embd = t_embd->ne[0];
1381
- cross.n_enc = t_embd->ne[1];
1382
- cross.v_embd.resize(cross.n_embd*cross.n_enc);
1383
- memcpy(cross.v_embd.data(), embd.data, ggml_nbytes(t_embd));
1384
-
1385
- const auto & batch = balloc->get_batch();
1386
-
1387
- // remember the sequence ids used during the encoding - needed for cross attention later
1388
- cross.seq_ids_enc.resize(n_tokens);
1389
- for (uint32_t i = 0; i < n_tokens; i++) {
1390
- cross.seq_ids_enc[i].clear();
1391
-
1392
- for (int s = 0; s < batch.n_seq_id[i]; s++) {
1393
- const llama_seq_id seq_id = batch.seq_id[i][s];
1394
-
1395
- cross.seq_ids_enc[i].insert(seq_id);
1396
- }
1397
- }
1398
- }
1399
-
1400
- return 0;
1401
- }
1402
-
1403
- static std::map<llama_seq_id, uint32_t> build_seq_to_output_row(const llama_ubatch & ubatch, uint32_t row_offset) {
1404
- std::map<llama_seq_id, uint32_t> seq_to_row;
1405
- // how many output tokens we have seen so far for this ubatch.
1406
- uint32_t local = 0;
1407
- for (uint32_t i = 0; i < ubatch.n_tokens; ++i) {
1408
- // skip tokens that are not output.
1409
- if (!ubatch.output[i]) {
1410
- continue;
1411
- }
1412
-
1413
- const llama_seq_id seq_id = ubatch.seq_id[i][0];
1414
- // row_offset is the number of output tokens before this ubatch.
1415
- seq_to_row[seq_id] = row_offset + local;
1416
- ++local;
1417
- }
1418
- return seq_to_row;
1419
- }
1420
-
1421
- static void copy_tensor_async_ints(
1422
- const std::map<llama_seq_id, ggml_tensor*> & tensor_map,
1423
- const buffer_view<llama_token> & sampled,
1424
- const std::map<llama_seq_id, uint32_t> & seq_to_row,
1425
- ggml_backend_sched_t sched) {
1426
- if (!sampled.has_data()) {
1427
- return;
1428
- }
1429
-
1430
- for (const auto & [seq_id, tensor] : tensor_map) {
1431
- auto it = seq_to_row.find(seq_id);
1432
- if (it == seq_to_row.end()) {
1433
- continue;
1434
- }
1435
-
1436
- const uint32_t row = it->second;
1437
- GGML_ASSERT(row < sampled.size);
1438
-
1439
- GGML_ASSERT(ggml_is_contiguous(tensor) && "sampled tokens tensor must be contiguous for async copy");
1440
-
1441
- ggml_backend_t backend = ggml_backend_sched_get_tensor_backend(sched, tensor);
1442
- ggml_backend_tensor_get_async(backend, tensor, sampled.data + row, 0, sizeof(sampled.data[row]));
1443
- }
1444
- }
1445
-
1446
- static void copy_tensor_async_floats(
1447
- const std::map<llama_seq_id, ggml_tensor*> & tensor_map,
1448
- const buffer_view<float> & dst,
1449
- size_t stride,
1450
- std::vector<uint32_t> & counts,
1451
- const std::map<llama_seq_id, uint32_t> & seq_to_row,
1452
- ggml_backend_sched_t sched) {
1453
- if (!dst.has_data()) {
1454
- return;
1455
- }
1456
-
1457
- for (const auto & [seq_id, tensor] : tensor_map) {
1458
- auto it = seq_to_row.find(seq_id);
1459
- if (it == seq_to_row.end()) {
1460
- continue;
1461
- }
1462
-
1463
- const uint32_t row = it->second;
1464
- GGML_ASSERT(row < counts.size());
1465
-
1466
- GGML_ASSERT(ggml_is_contiguous(tensor) && "logits/probs tensor must be contiguous for async copy");
1467
-
1468
- ggml_backend_t backend = ggml_backend_sched_get_tensor_backend(sched, tensor);
1469
- float * row_ptr = dst.data + (size_t) row * stride;
1470
- ggml_backend_tensor_get_async(backend, tensor, row_ptr, 0, ggml_nbytes(tensor));
1471
-
1472
- // Update the actual number of logits/probabilities that were written for this row.
1473
- counts[row] = ggml_nelements(tensor);
1474
- }
1475
- }
1476
-
1477
- static void copy_tensor_async_candidates(
1478
- const std::map<llama_seq_id, ggml_tensor*> & tensor_map,
1479
- const buffer_view<llama_token> & dst,
1480
- size_t stride,
1481
- std::vector<uint32_t> & counts,
1482
- const std::map<llama_seq_id, uint32_t> & seq_to_row,
1483
- ggml_backend_sched_t sched) {
1484
- if (!dst.has_data()) {
1485
- return;
1486
- }
1487
-
1488
- for (const auto & [seq_id, tensor] : tensor_map) {
1489
- auto it = seq_to_row.find(seq_id);
1490
- if (it == seq_to_row.end()) {
1491
- continue;
1492
- }
1493
-
1494
- const uint32_t row = it->second;
1495
- GGML_ASSERT(row < counts.size());
1496
-
1497
- GGML_ASSERT(ggml_is_contiguous(tensor) && "candidates tensor must be contiguous for async copy");
1498
-
1499
- ggml_backend_t backend = ggml_backend_sched_get_tensor_backend(sched, tensor);
1500
- llama_token * row_ptr = dst.data + (size_t) row * stride;
1501
- ggml_backend_tensor_get_async(backend, tensor, row_ptr, 0, ggml_nbytes(tensor));
1502
-
1503
- // Update the actual number of candidates that were written.
1504
- counts[row] = ggml_nelements(tensor);
1505
- }
1506
- }
1507
-
1508
- static bool needs_raw_logits(const llama_ubatch & ubatch, const std::map<llama_seq_id, llama_sampler *> & samplers) {
1509
- for (uint32_t i = 0; i < ubatch.n_tokens; i++) {
1510
- if (!ubatch.output[i]) {
1511
- continue;
1512
- }
1513
-
1514
- // Check if the output token has at least one sequence without a backend sampler.
1515
- for (int32_t j = 0; j < ubatch.n_seq_id[i]; ++j) {
1516
- llama_seq_id seq_id = ubatch.seq_id[i][j];
1517
- if (samplers.find(seq_id) == samplers.end()) {
1518
- return true;
1519
- }
1520
- }
1521
- }
1522
- return false; // all sequences use backend sampling
1523
- }
1524
-
1525
- int llama_context::decode(const llama_batch & batch_inp) {
1526
- GGML_ASSERT((!batch_inp.token && batch_inp.embd) || (batch_inp.token && !batch_inp.embd)); // NOLINT
1527
-
1528
- if (!memory) {
1529
- LLAMA_LOG_DEBUG("%s: cannot decode batches with this context (calling encode() instead)\n", __func__);
1530
- return encode(batch_inp);
1531
- }
1532
-
1533
- if (batch_inp.n_tokens == 0) {
1534
- LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
1535
- return -1;
1536
- }
1537
-
1538
- const auto & vocab = model.vocab;
1539
- const auto & hparams = model.hparams;
1540
-
1541
- const int64_t n_vocab = vocab.n_tokens();
1542
- const int64_t n_embd = hparams.n_embd_inp();
1543
-
1544
- // when computing embeddings, all tokens are output
1545
- const bool output_all = cparams.embeddings;
1546
- const bool has_samplers = !sampling.samplers.empty();
1547
-
1548
- const uint32_t n_seq_max = cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max;
1549
-
1550
- // TODO: avoid this workaround in the future
1551
- if (has_samplers && batch_inp.logits) {
1552
- std::vector<int32_t> seq_output_count(n_seq_max, 0);
1553
-
1554
- for (int32_t i = 0; i < batch_inp.n_tokens; ++i) {
1555
- if (batch_inp.logits[i] == 0) {
1556
- continue;
1557
- }
1558
-
1559
- const int ns = batch_inp.n_seq_id ? batch_inp.n_seq_id[i] : 1;
1560
-
1561
- for (int32_t s = 0; s < ns; ++s) {
1562
- const llama_seq_id seq_id = batch_inp.seq_id ? batch_inp.seq_id[i][s] : 0;
1563
-
1564
- seq_output_count[seq_id]++;
1565
- if (seq_output_count[seq_id] > 1) {
1566
- LLAMA_LOG_ERROR("%s: backend sampling requires at most one output token per sequence (seq_id %d had %d)\n",
1567
- __func__, seq_id, seq_output_count[seq_id]);
1568
- return -1;
1569
- }
1570
- }
1571
- }
1572
- }
1573
-
1574
- if (!balloc->init(batch_inp, vocab, memory.get(), n_embd, n_seq_max, output_all)) {
1575
- LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__);
1576
- return -1;
1577
- }
1578
-
1579
- const uint32_t n_tokens_all = balloc->get_n_tokens();
1580
- const uint32_t n_outputs_all = balloc->get_n_outputs();
1581
-
1582
- if (output_all) {
1583
- // require that all tokens are output
1584
- if (n_outputs_all != n_tokens_all) {
1585
- LLAMA_LOG_ERROR("%s: pooled embedding requires that all tokens are output (n_outputs_all = %d, n_tokens_all = %d)\n",
1586
- __func__, n_outputs_all, n_tokens_all);
1587
- return -1;
1588
- }
1589
- }
1590
-
1591
- GGML_ASSERT(n_tokens_all <= cparams.n_batch);
1592
-
1593
- GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
1594
-
1595
- if (t_compute_start_us == 0) {
1596
- t_compute_start_us = ggml_time_us();
1597
- }
1598
- n_queued_tokens += n_tokens_all;
1599
-
1600
- // TODO: this clear of the buffer can easily be forgotten - need something better
1601
- embd_seq.clear();
1602
- output_swaps.clear();
1603
-
1604
- sched_reserve();
1605
-
1606
- bool did_optimize = false;
1607
-
1608
- // handle any pending shifts/copies
1609
- memory_update(false);
1610
-
1611
- llama_memory_context_ptr mctx;
1612
-
1613
- while (true) {
1614
- mctx = memory->init_batch(*balloc, cparams.n_ubatch, output_all);
1615
- if (!mctx) {
1616
- return -2;
1617
- }
1618
-
1619
- switch (mctx->get_status()) {
1620
- case LLAMA_MEMORY_STATUS_SUCCESS:
1621
- {
1622
- } break;
1623
- case LLAMA_MEMORY_STATUS_NO_UPDATE:
1624
- {
1625
- LLAMA_LOG_ERROR("%s: unexpected memory context status: %d\n", __func__, mctx->get_status());
1626
-
1627
- return -2;
1628
- }
1629
- case LLAMA_MEMORY_STATUS_FAILED_PREPARE:
1630
- {
1631
- if (!did_optimize) {
1632
- did_optimize = true;
1633
-
1634
- if (memory_update(true)) {
1635
- LLAMA_LOG_DEBUG("%s: retrying batch size %d after cache optimization\n", __func__, balloc->get_n_tokens());
1636
-
1637
- continue;
1638
- }
1639
- }
1640
-
1641
- LLAMA_LOG_WARN("%s: failed to find a memory slot for batch of size %d\n", __func__, balloc->get_n_tokens());
1642
-
1643
- return 1;
1644
- }
1645
- case LLAMA_MEMORY_STATUS_FAILED_COMPUTE:
1646
- {
1647
- LLAMA_LOG_ERROR("%s: compute failed while preparing batch of size %d\n", __func__, balloc->get_n_tokens());
1648
-
1649
- return -2;
1650
- }
1651
- }
1652
-
1653
- break;
1654
- }
1655
-
1656
- // reserve output buffer
1657
- if (output_reserve(n_outputs_all) < n_outputs_all) {
1658
- LLAMA_LOG_ERROR("%s: could not reserve space for batch with %d outputs\n", __func__, n_outputs_all);
1659
- return -2;
1660
- };
1661
-
1662
- int64_t n_outputs_prev = 0;
1663
-
1664
- do {
1665
- const auto & ubatch = mctx->get_ubatch();
1666
-
1667
- // count the outputs in this ubatch
1668
- {
1669
- int32_t n_outputs_new = 0;
1670
-
1671
- if (n_outputs_all == n_tokens_all) {
1672
- n_outputs_new = ubatch.n_tokens;
1673
- } else {
1674
- for (uint32_t i = 0; i < ubatch.n_tokens; i++) {
1675
- n_outputs_new += (int32_t) (ubatch.output[i] != 0);
1676
- }
1677
- }
1678
-
1679
- // needs to happen before the graph is built
1680
- n_outputs = n_outputs_new;
1681
- }
1682
-
1683
- ggml_status status;
1684
- const auto * res = process_ubatch(ubatch, LLM_GRAPH_TYPE_DECODER, mctx.get(), status);
1685
-
1686
- if (!res) {
1687
- // the last ubatch failed or was aborted -> remove all positions of that ubatch from the memory module
1688
- llama_pos pos_min[LLAMA_MAX_SEQ];
1689
- for (int s = 0; s < LLAMA_MAX_SEQ; ++s) {
1690
- pos_min[s] = std::numeric_limits<llama_pos>::max();
1691
- }
1692
-
1693
- for (uint32_t i = 0; i < ubatch.n_tokens; ++i) {
1694
- const auto & seq_id = ubatch.seq_id[i][0];
1695
-
1696
- pos_min[seq_id] = std::min(pos_min[seq_id], ubatch.pos[i]);
1697
- }
1698
-
1699
- for (int s = 0; s < LLAMA_MAX_SEQ; ++s) {
1700
- if (pos_min[s] == std::numeric_limits<llama_pos>::max()) {
1701
- continue;
1702
- }
1703
-
1704
- LLAMA_LOG_WARN("%s: removing memory module entries for seq_id = %d, pos = [%d, +inf)\n", __func__, s, pos_min[s]);
1705
-
1706
- memory->seq_rm(s, pos_min[s], -1);
1707
- }
1708
-
1709
- switch (status) {
1710
- case GGML_STATUS_ABORTED: return 2;
1711
- case GGML_STATUS_ALLOC_FAILED: return -2;
1712
- case GGML_STATUS_FAILED: return -3;
1713
- case GGML_STATUS_SUCCESS: GGML_ABORT("should not happen");
1714
- }
1715
- }
1716
-
1717
- // plot the computation graph in dot format (for debugging purposes)
1718
- //if (n_past%100 == 0) {
1719
- // ggml_graph_dump_dot(gf, NULL, "llama.dot");
1720
- //}
1721
-
1722
- auto * t_logits = res->get_logits();
1723
- auto * t_embd = cparams.embeddings ? res->get_embd() : nullptr;
1724
-
1725
- if (t_embd && res->get_embd_pooled()) {
1726
- t_embd = res->get_embd_pooled();
1727
- }
1728
-
1729
- // extract logits
1730
- if (logits.data && t_logits && n_outputs > 0 && needs_raw_logits(ubatch, sampling.samplers)) {
1731
- ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits);
1732
- GGML_ASSERT(backend_res != nullptr);
1733
- GGML_ASSERT(logits.data != nullptr);
1734
-
1735
- float * logits_out = logits.data + n_outputs_prev*n_vocab;
1736
-
1737
- if (n_outputs) {
1738
- GGML_ASSERT( n_outputs_prev + n_outputs <= n_outputs_all);
1739
- GGML_ASSERT((n_outputs_prev + n_outputs)*n_vocab <= (int64_t) logits.size);
1740
- ggml_backend_tensor_get_async(backend_res, t_logits, logits_out, 0, n_outputs*n_vocab*sizeof(float));
1741
- }
1742
- }
1743
-
1744
- // extract embeddings
1745
- if (embd.data && t_embd && n_outputs > 0) {
1746
- ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd);
1747
- GGML_ASSERT(backend_embd != nullptr);
1748
-
1749
- switch (cparams.pooling_type) {
1750
- case LLAMA_POOLING_TYPE_NONE:
1751
- {
1752
- // extract token embeddings
1753
- GGML_ASSERT(embd.data != nullptr);
1754
- const uint32_t n_embd_out = hparams.n_embd_out();
1755
- float * embd_out = embd.data + n_outputs_prev*n_embd_out;
1756
-
1757
- if (n_outputs) {
1758
- GGML_ASSERT( n_outputs_prev + n_outputs <= n_outputs_all);
1759
- GGML_ASSERT((n_outputs_prev + n_outputs)*n_embd_out <= (int64_t) embd.size);
1760
- ggml_backend_tensor_get_async(backend_embd, t_embd, embd_out, 0, n_outputs*n_embd_out*sizeof(float));
1761
- }
1762
- } break;
1763
- case LLAMA_POOLING_TYPE_MEAN:
1764
- case LLAMA_POOLING_TYPE_CLS:
1765
- case LLAMA_POOLING_TYPE_LAST:
1766
- {
1767
- // extract sequence embeddings (cleared before processing each batch)
1768
- auto & embd_seq_out = embd_seq;
1769
-
1770
- for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
1771
- const llama_seq_id seq_id = ubatch.seq_id_unq[s];
1772
- const int32_t seq_idx = ubatch.seq_idx[seq_id];
1773
-
1774
- embd_seq_out[seq_id].resize(n_embd);
1775
- ggml_backend_tensor_get_async(backend_embd, t_embd, embd_seq_out[seq_id].data(), (n_embd*seq_idx)*sizeof(float), n_embd*sizeof(float));
1776
- }
1777
- } break;
1778
- case LLAMA_POOLING_TYPE_RANK:
1779
- {
1780
- // extract the rerank score - n_cls_out floats per sequence
1781
- auto & embd_seq_out = embd_seq;
1782
-
1783
- const uint32_t n_cls_out = hparams.n_cls_out;
1784
-
1785
- for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
1786
- const llama_seq_id seq_id = ubatch.seq_id_unq[s];
1787
- const int32_t seq_idx = ubatch.seq_idx[seq_id];
1788
-
1789
- embd_seq_out[seq_id].resize(n_cls_out);
1790
- ggml_backend_tensor_get_async(backend_embd, t_embd, embd_seq_out[seq_id].data(), (n_cls_out*seq_idx)*sizeof(float), n_cls_out*sizeof(float));
1791
- }
1792
- } break;
1793
- case LLAMA_POOLING_TYPE_UNSPECIFIED:
1794
- {
1795
- GGML_ABORT("unknown pooling type");
1796
- }
1797
- }
1798
- }
1799
-
1800
- // Copy backend sampling output if this ubatch produced any sampling tensors.
1801
- if (has_samplers && (!res->t_sampled.empty() || !res->t_sampled_probs.empty() || !res->t_sampled_logits.empty())) {
1802
- const auto seq_to_output_row = build_seq_to_output_row(ubatch, n_outputs_prev);
1803
- const auto stride = n_vocab;
1804
-
1805
- // async copy the sampling data from the backend to the host
1806
- copy_tensor_async_ints(res->t_sampled, sampling.sampled, seq_to_output_row, sched.get());
1807
-
1808
- copy_tensor_async_floats (res->t_sampled_logits, sampling.logits, stride, sampling.logits_count, seq_to_output_row, sched.get());
1809
- copy_tensor_async_floats (res->t_sampled_probs, sampling.probs, stride, sampling.probs_count, seq_to_output_row, sched.get());
1810
- copy_tensor_async_candidates(res->t_candidates, sampling.candidates, stride, sampling.candidates_count, seq_to_output_row, sched.get());
1811
- }
1812
-
1813
- n_outputs_prev += n_outputs;
1814
- } while (mctx->next());
1815
-
1816
- // set to total number of outputs in the batch, for use in llama_get_logits_ith
1817
- n_outputs = n_outputs_all;
1818
-
1819
- // set output mappings
1820
- if (n_outputs > 0) {
1821
- bool sorted_output = true;
1822
-
1823
- auto & out_ids = balloc->get_out_ids();
1824
-
1825
- GGML_ASSERT(out_ids.size() == (size_t) n_outputs);
1826
-
1827
- for (int64_t i = 0; i < n_outputs; ++i) {
1828
- int64_t out_id = out_ids[i];
1829
- output_ids[out_id] = i;
1830
- if (out_id != i) {
1831
- sorted_output = false;
1832
- }
1833
- }
1834
-
1835
- // make the outputs have the same order they had in the user-provided batch
1836
- // note: this is mostly relevant for recurrent models atm
1837
- if (!sorted_output && n_outputs > 1) {
1838
- GGML_ASSERT((size_t) n_outputs == out_ids.size());
1839
-
1840
- // TODO: is there something more efficient which also minimizes swaps?
1841
- // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
1842
- for (uint32_t i = 0; i < n_outputs - 1; ++i) {
1843
- uint32_t j_min = i;
1844
- for (uint32_t j = i + 1; j < n_outputs; ++j) {
1845
- if (out_ids[j] < out_ids[j_min]) {
1846
- j_min = j;
1847
- }
1848
- }
1849
- if (j_min == i) {
1850
- continue;
1851
- }
1852
- std::swap(out_ids[i], out_ids[j_min]);
1853
-
1854
- // remember the swaps and apply them lazily upon logits/embeddings access
1855
- output_swaps.push_back({ i, j_min });
1856
- }
1857
-
1858
- std::fill(output_ids.begin(), output_ids.end(), -1);
1859
-
1860
- for (uint32_t i = 0; i < n_outputs; ++i) {
1861
- output_ids[out_ids[i]] = i;
1862
- }
1863
- }
1864
- }
1865
-
1866
- // wait for the computation to finish (automatically done when obtaining the model output)
1867
- //synchronize();
1868
-
1869
- return 0;
1870
- }
1871
-
1872
- //
1873
- // output
1874
- //
1875
-
1876
- uint32_t llama_context::output_reserve(int32_t n_outputs) {
1877
- const auto & hparams = model.hparams;
1878
- const auto & vocab = model.vocab;
1879
-
1880
- const int64_t n_outputs_max = std::max<int64_t>(n_outputs, n_seq_max());
1881
-
1882
- const auto n_batch = cparams.n_batch;
1883
- const auto n_vocab = vocab.n_tokens();
1884
- const auto n_embd_out = hparams.n_embd_out();
1885
-
1886
- bool has_logits = true;
1887
- bool has_embd = cparams.embeddings;
1888
-
1889
- // TODO: hacky enc-dec support
1890
- if (model.arch == LLM_ARCH_T5) {
1891
- has_logits = true;
1892
- has_embd = true;
1893
- }
1894
-
1895
-
1896
- size_t backend_float_count = 0;
1897
- size_t backend_token_count = 0;
1898
-
1899
- logits.size = has_logits ? n_vocab*n_outputs_max : 0;
1900
- embd.size = has_embd ? n_embd_out*n_outputs_max : 0;
1901
-
1902
- // Allocate backend sampling output buffers if there are backend samplers configured.
1903
- const bool has_sampling = !sampling.samplers.empty();
1904
- if (has_sampling) {
1905
- backend_float_count = 2 * n_vocab * n_outputs_max; // logits + probs
1906
- backend_token_count = (1 + n_vocab) * n_outputs_max; // sampled + candidates
1907
- }
1908
-
1909
- if (output_ids.empty()) {
1910
- // init, never resized afterwards
1911
- output_ids.resize(n_batch);
1912
- }
1913
-
1914
- const size_t prev_size = buf_output ? ggml_backend_buffer_get_size(buf_output.get()) : 0;
1915
- const size_t new_size =
1916
- (logits.size + embd.size + backend_float_count) * sizeof(float) +
1917
- ( backend_token_count) * sizeof(llama_token);
1918
-
1919
- // alloc only when more than the current capacity is required
1920
- // TODO: also consider shrinking the buffer
1921
- if (!buf_output || prev_size < new_size) {
1922
- if (buf_output) {
1923
- #ifndef NDEBUG
1924
- // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
1925
- LLAMA_LOG_DEBUG("%s: reallocating output buffer from size %.02f MiB to %.02f MiB\n", __func__, prev_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
1926
- #endif
1927
- synchronize();
1928
-
1929
- // TODO: not needed?
1930
- buf_output = nullptr;
1931
- logits.data = nullptr;
1932
- embd.data = nullptr;
1933
- }
1934
-
1935
- auto * buft = ggml_backend_cpu_buffer_type();
1936
- // try to use the host buffer of the device where the output tensor is allocated for faster transfer to system memory
1937
- auto * output_dev = model.dev_output();
1938
- auto * output_dev_host_buft = output_dev ? ggml_backend_dev_host_buffer_type(output_dev) : nullptr;
1939
- if (output_dev_host_buft) {
1940
- buft = output_dev_host_buft;
1941
- }
1942
- buf_output.reset(ggml_backend_buft_alloc_buffer(buft, new_size));
1943
- if (buf_output == nullptr) {
1944
- LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
1945
- return 0;
1946
- }
1947
- }
1948
-
1949
- float * output_base = (float *) ggml_backend_buffer_get_base(buf_output.get());
1950
-
1951
- size_t offset = 0;
1952
- uint8_t * base = (uint8_t *) output_base;
1953
-
1954
- logits = has_logits ? buffer_view<float>{output_base, logits.size} : buffer_view<float>{nullptr, 0};
1955
- offset += logits.size * sizeof(float);
1956
-
1957
- embd = has_embd ? buffer_view<float>{(float *) (base + offset), embd.size} : buffer_view<float>{nullptr, 0};
1958
- offset += embd.size * sizeof(float);
1959
-
1960
- if (has_sampling) {
1961
- sampling.logits = {(float *) (base + offset), (size_t)(n_vocab*n_outputs_max)};
1962
- offset += sampling.logits.size * sizeof(float);
1963
-
1964
- sampling.probs = {(float *) (base + offset), (size_t)(n_vocab*n_outputs_max)};
1965
- offset += sampling.probs.size * sizeof(float);
1966
-
1967
- sampling.sampled = {(llama_token *) (base + offset), (size_t)n_outputs_max};
1968
- offset += sampling.sampled.size * sizeof(llama_token);
1969
-
1970
- sampling.candidates = {(llama_token *) (base + offset), (size_t)(n_vocab*n_outputs_max)};
1971
- offset += sampling.candidates.size * sizeof(llama_token);
1972
-
1973
- // The count vectors keep track of the actual number of logits/probs/candidates
1974
- // copied from the backend for each output row.
1975
-
1976
- sampling.logits_count.resize(n_outputs_max);
1977
- sampling.probs_count.resize(n_outputs_max);
1978
- sampling.candidates_count.resize(n_outputs_max);
1979
-
1980
- std::fill(sampling.logits_count.begin(), sampling.logits_count.end(), 0);
1981
- std::fill(sampling.probs_count.begin(), sampling.probs_count.end(), 0);
1982
- std::fill(sampling.candidates_count.begin(), sampling.candidates_count.end(), 0);
1983
-
1984
- std::fill_n(sampling.sampled.data, sampling.sampled.size, LLAMA_TOKEN_NULL);
1985
- } else {
1986
- sampling.logits = {nullptr, 0};
1987
- sampling.probs = {nullptr, 0};
1988
- sampling.sampled = {nullptr, 0};
1989
- sampling.candidates = {nullptr, 0};
1990
-
1991
- sampling.logits_count.clear();
1992
- sampling.probs_count.clear();
1993
- sampling.candidates_count.clear();
1994
- }
1995
-
1996
- // set all ids as invalid (negative)
1997
- std::fill(output_ids.begin(), output_ids.end(), -1);
1998
-
1999
- this->n_outputs = 0;
2000
-
2001
- return n_outputs_max;
2002
- }
2003
-
2004
- void llama_context::output_reorder() {
2005
- const uint64_t n_vocab = model.vocab.n_tokens();
2006
- const uint64_t n_embd = model.hparams.n_embd;
2007
-
2008
- for (size_t s = 0; s < output_swaps.size(); ++s) {
2009
- const uint64_t i0 = output_swaps[s].i0;
2010
- const uint64_t i1 = output_swaps[s].i1;
2011
-
2012
- if (logits.size > 0) {
2013
- for (uint64_t k = 0; k < n_vocab; k++) {
2014
- std::swap(logits.data[i0*n_vocab + k], logits.data[i1*n_vocab + k]);
2015
- }
2016
- }
2017
-
2018
- if (embd.size > 0) {
2019
- for (uint64_t k = 0; k < n_embd; k++) {
2020
- std::swap(embd.data[i0*n_embd + k], embd.data[i1*n_embd + k]);
2021
- }
2022
- }
2023
-
2024
- if (!sampling.samplers.empty()) {
2025
- assert(sampling.logits.size > 0);
2026
- assert(sampling.probs.size > 0);
2027
- assert(sampling.candidates.size > 0);
2028
- assert(sampling.sampled.size > 0);
2029
- assert(sampling.logits_count.size() > 0);
2030
- assert(sampling.probs_count.size() > 0);
2031
- assert(sampling.candidates_count.size() > 0);
2032
-
2033
- for (uint64_t k = 0; k < n_vocab; ++k) {
2034
- std::swap(sampling.logits.data[i0*n_vocab + k], sampling.logits.data[i1*n_vocab + k]);
2035
- }
2036
-
2037
- for (uint64_t k = 0; k < n_vocab; ++k) {
2038
- std::swap(sampling.probs.data[i0*n_vocab + k], sampling.probs.data[i1*n_vocab + k]);
2039
- }
2040
-
2041
- for (uint64_t k = 0; k < n_vocab; ++k) {
2042
- std::swap(sampling.candidates.data[i0*n_vocab + k], sampling.candidates.data[i1*n_vocab + k]);
2043
- }
2044
-
2045
- std::swap(sampling.sampled.data[i0], sampling.sampled.data[i1]);
2046
- std::swap(sampling.logits_count[i0], sampling.logits_count[i1]);
2047
- std::swap(sampling.probs_count[i0], sampling.probs_count[i1]);
2048
- std::swap(sampling.candidates_count[i0], sampling.candidates_count[i1]);
2049
- }
2050
- }
2051
-
2052
- output_swaps.clear();
2053
- }
2054
-
2055
- //
2056
- // graph
2057
- //
2058
-
2059
- uint32_t llama_context::graph_max_nodes(uint32_t n_tokens) const {
2060
- if (model.arch == LLM_ARCH_QWEN3NEXT || model.arch == LLM_ARCH_KIMI_LINEAR || model.arch == LLM_ARCH_QWEN35 || model.arch == LLM_ARCH_QWEN35MOE) {
2061
- return std::max<uint32_t>(n_tokens * 40, 32u * model.n_tensors());
2062
- }
2063
- uint32_t res = std::max<uint32_t>(1024u, 8u*model.n_tensors());
2064
- for (const auto & lora : model.loras) {
2065
- res += lora->get_n_nodes();
2066
- }
2067
- return res;
2068
- }
2069
-
2070
- llm_graph_result * llama_context::get_gf_res_reserve() const {
2071
- return static_cast<llm_graph_result *>(gf_res_reserve.get());
2072
- }
2073
-
2074
- ggml_cgraph * llama_context::graph_reserve(
2075
- uint32_t n_tokens, uint32_t n_seqs, uint32_t n_outputs, const llama_memory_context_i * mctx, bool split_only, size_t * sizes) {
2076
- LLAMA_LOG_DEBUG("%s: reserving a graph for ubatch with n_tokens = %4u, n_seqs = %2u, n_outputs = %4u\n", __func__, n_tokens, n_seqs, n_outputs);
2077
- GGML_ASSERT(n_outputs >= 1);
2078
-
2079
- if (n_tokens % n_seqs != 0) {
2080
- n_tokens = ((n_tokens + (n_seqs - 1)) / n_seqs) * n_seqs; // round to next multiple of n_seqs
2081
- n_outputs = std::max(n_outputs, n_tokens);
2082
-
2083
- LLAMA_LOG_DEBUG("%s: making n_tokens a multiple of n_seqs - n_tokens = %u, n_seqs = %u, n_outputs = %u\n", __func__, n_tokens, n_seqs, n_outputs);
2084
- }
2085
-
2086
- ggml_backend_sched_reset(sched.get());
2087
-
2088
- // when the scheduler is reset, we cannot reuse the old graph, so we reset the previous graph result to prevent that
2089
- gf_res_prev->reset();
2090
-
2091
- // store the n_outputs as it is, and restore it afterwards
2092
- // TODO: not sure if needed, might simplify in the future by removing this
2093
- const auto save_n_outputs = this->n_outputs;
2094
-
2095
- this->n_outputs = n_outputs;
2096
-
2097
- llama_batch_allocr balloc(model.hparams.n_pos_per_embd());
2098
- llama_ubatch ubatch = balloc.ubatch_reserve(n_tokens/n_seqs, n_seqs);
2099
-
2100
- // set one output token per sequence in order to activate all backend samplers
2101
- std::vector<llama_seq_id> seq_ids(n_seqs);
2102
- for (uint32_t i = 0; i < n_seqs; ++i) {
2103
- seq_ids[i] = i;
2104
- ubatch.n_seq_id[i] = 1;
2105
- ubatch.seq_id[i] = &seq_ids[i];
2106
- ubatch.output[i] = true;
2107
- }
2108
-
2109
- auto * res = gf_res_reserve.get();
2110
-
2111
- const auto gparams = graph_params(res, ubatch, mctx, LLM_GRAPH_TYPE_DEFAULT);
2112
-
2113
- res->reset();
2114
-
2115
- auto * gf = model.build_graph(gparams);
2116
-
2117
- this->n_outputs = save_n_outputs;
2118
-
2119
- // initialize scheduler with the specified graph
2120
- if (split_only) {
2121
- if (sizes) {
2122
- ggml_backend_sched_reserve_size(sched.get(), gf, sizes);
2123
- } else {
2124
- ggml_backend_sched_split_graph(sched.get(), gf);
2125
- }
2126
- } else if (!ggml_backend_sched_reserve(sched.get(), gf)) {
2127
- GGML_ASSERT(!sizes);
2128
- LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
2129
- return nullptr;
2130
- }
2131
-
2132
- return gf;
2133
- }
2134
-
2135
- llm_graph_params llama_context::graph_params(
2136
- llm_graph_result * res,
2137
- const llama_ubatch & ubatch,
2138
- const llama_memory_context_i * mctx,
2139
- llm_graph_type gtype) const {
2140
- return {
2141
- /*.arch =*/ model.arch,
2142
- /*.hparams =*/ model.hparams,
2143
- /*.cparams =*/ cparams,
2144
- /*.ubatch =*/ ubatch,
2145
- /*.gtype =*/ gtype,
2146
- /*.sched =*/ sched.get(),
2147
- /*.backend_cpu =*/ backend_cpu,
2148
- /*.cvec =*/ cvec.get(),
2149
- /*.loras =*/ loras.get(),
2150
- /*.mctx =*/ mctx,
2151
- /*.cross =*/ &cross,
2152
- /*.samplers =*/ sampling.samplers,
2153
- /*.n_outputs =*/ n_outputs,
2154
- /*.cb =*/ graph_get_cb(),
2155
- /*.res =*/ res,
2156
- };
2157
- }
2158
-
2159
- ggml_status llama_context::graph_compute(
2160
- ggml_cgraph * gf,
2161
- bool batched) {
2162
- int n_threads = batched ? cparams.n_threads_batch : cparams.n_threads;
2163
- ggml_threadpool_t tp = batched ? threadpool_batch : threadpool;
2164
-
2165
- if (backend_cpu != nullptr) {
2166
- auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend_cpu));
2167
- auto * set_threadpool_fn = (decltype(ggml_backend_cpu_set_threadpool) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_set_threadpool");
2168
- if (set_threadpool_fn) {
2169
- set_threadpool_fn(backend_cpu, tp);
2170
- }
2171
- }
2172
-
2173
- // set the number of threads for all the backends
2174
- for (const auto & set_n_threads_fn : set_n_threads_fns) {
2175
- set_n_threads_fn.second(set_n_threads_fn.first, n_threads);
2176
- }
2177
-
2178
- auto status = ggml_backend_sched_graph_compute_async(sched.get(), gf);
2179
- if (status != GGML_STATUS_SUCCESS) {
2180
- LLAMA_LOG_ERROR("%s: ggml_backend_sched_graph_compute_async failed with error %d\n", __func__, status);
2181
- }
2182
-
2183
- // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(sched));
2184
-
2185
- return status;
2186
- }
2187
-
2188
- llm_graph_cb llama_context::graph_get_cb() const {
2189
- return [&](const llama_ubatch & ubatch, ggml_tensor * cur, const char * name, int il) {
2190
- if (il >= 0) {
2191
- ggml_format_name(cur, "%s-%d", name, il);
2192
- } else {
2193
- ggml_set_name(cur, name);
2194
- }
2195
-
2196
- // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
2197
- // FIXME: fix in ggml_backend_sched
2198
- const bool full_offload = model.n_gpu_layers() > model.hparams.n_layer;
2199
- if (ubatch.n_tokens < 32 || full_offload) {
2200
- if (il != -1 && strcmp(name, "norm") == 0) {
2201
- const auto & dev_layer = model.dev_layer(il);
2202
- for (const auto & backend : backends) {
2203
- if (ggml_backend_get_device(backend.get()) == dev_layer) {
2204
- if (ggml_backend_supports_op(backend.get(), cur)) {
2205
- ggml_backend_sched_set_tensor_backend(sched.get(), cur, backend.get());
2206
- }
2207
- }
2208
- }
2209
- }
2210
- }
2211
- };
2212
- }
2213
-
2214
- //
2215
- // state save/load
2216
- //
2217
-
2218
- class llama_io_write_dummy : public llama_io_write_i {
2219
- public:
2220
- llama_io_write_dummy() = default;
2221
-
2222
- void write(const void * /* src */, size_t size) override {
2223
- size_written += size;
2224
- }
2225
-
2226
- void write_tensor(const ggml_tensor * /* tensor */, size_t /* offset */, size_t size) override {
2227
- size_written += size;
2228
- }
2229
-
2230
- size_t n_bytes() override {
2231
- return size_written;
2232
- }
2233
-
2234
- private:
2235
- size_t size_written = 0;
2236
- };
2237
-
2238
- class llama_io_write_buffer : public llama_io_write_i {
2239
- public:
2240
- llama_io_write_buffer(
2241
- uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
2242
-
2243
- void write(const void * src, size_t size) override {
2244
- if (size > buf_size) {
2245
- throw std::runtime_error("unexpectedly reached end of buffer");
2246
- }
2247
- memcpy(ptr, src, size);
2248
- ptr += size;
2249
- size_written += size;
2250
- buf_size -= size;
2251
- }
2252
-
2253
- void write_tensor(const ggml_tensor * tensor, size_t offset, size_t size) override {
2254
- if (size > buf_size) {
2255
- throw std::runtime_error("unexpectedly reached end of buffer");
2256
- }
2257
- ggml_backend_tensor_get(tensor, ptr, offset, size);
2258
- ptr += size;
2259
- size_written += size;
2260
- buf_size -= size;
2261
- }
2262
-
2263
- size_t n_bytes() override {
2264
- return size_written;
2265
- }
2266
-
2267
- private:
2268
- uint8_t * ptr;
2269
- size_t buf_size = 0;
2270
- size_t size_written = 0;
2271
- };
2272
-
2273
- class llama_io_read_buffer : public llama_io_read_i {
2274
- public:
2275
- llama_io_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
2276
-
2277
- const uint8_t * read(size_t size) override {
2278
- const uint8_t * base_ptr = ptr;
2279
- if (size > buf_size) {
2280
- throw std::runtime_error("unexpectedly reached end of buffer");
2281
- }
2282
- ptr += size;
2283
- size_read += size;
2284
- buf_size -= size;
2285
- return base_ptr;
2286
- }
2287
-
2288
- void read_to(void * dst, size_t size) override {
2289
- memcpy(dst, read(size), size);
2290
- }
2291
-
2292
- size_t n_bytes() override {
2293
- return size_read;
2294
- }
2295
-
2296
- private:
2297
- const uint8_t * ptr;
2298
- size_t buf_size = 0;
2299
- size_t size_read = 0;
2300
- };
2301
-
2302
- class llama_io_write_file : public llama_io_write_i {
2303
- public:
2304
- llama_io_write_file(llama_file * f) : file(f) {}
2305
-
2306
- void write(const void * src, size_t size) override {
2307
- file->write_raw(src, size);
2308
- size_written += size;
2309
- }
2310
-
2311
- void write_tensor(const ggml_tensor * tensor, size_t offset, size_t size) override {
2312
- temp_buffer.resize(size);
2313
- ggml_backend_tensor_get(tensor, temp_buffer.data(), offset, size);
2314
- write(temp_buffer.data(), temp_buffer.size());
2315
- }
2316
-
2317
- size_t n_bytes() override {
2318
- return size_written;
2319
- }
2320
-
2321
- private:
2322
- llama_file * file;
2323
- size_t size_written = 0;
2324
- std::vector<uint8_t> temp_buffer;
2325
- };
2326
-
2327
- class llama_io_read_file : public llama_io_read_i {
2328
- public:
2329
- llama_io_read_file(llama_file * f) : file(f) {}
2330
-
2331
- void read_to(void * dst, size_t size) override {
2332
- file->read_raw(dst, size);
2333
- size_read += size;
2334
- }
2335
-
2336
- const uint8_t * read(size_t size) override {
2337
- temp_buffer.resize(size);
2338
- read_to(temp_buffer.data(), size);
2339
- return temp_buffer.data();
2340
- }
2341
-
2342
- size_t n_bytes() override {
2343
- return size_read;
2344
- }
2345
-
2346
- private:
2347
- llama_file * file;
2348
- size_t size_read = 0;
2349
- std::vector<uint8_t> temp_buffer;
2350
- };
2351
-
2352
- size_t llama_context::state_get_size() {
2353
- llama_io_write_dummy io;
2354
- try {
2355
- return state_write_data(io);
2356
- } catch (const std::exception & err) {
2357
- LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
2358
- return 0;
2359
- }
2360
- }
2361
-
2362
- size_t llama_context::state_get_data(uint8_t * dst, size_t size) {
2363
- llama_io_write_buffer io(dst, size);
2364
- try {
2365
- return state_write_data(io);
2366
- } catch (const std::exception & err) {
2367
- LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
2368
- return 0;
2369
- }
2370
- }
2371
-
2372
- size_t llama_context::state_set_data(const uint8_t * src, size_t size) {
2373
- llama_io_read_buffer io(src, size);
2374
- try {
2375
- return state_read_data(io);
2376
- } catch (const std::exception & err) {
2377
- LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
2378
- return 0;
2379
- }
2380
- }
2381
-
2382
- size_t llama_context::state_seq_get_size(llama_seq_id seq_id, llama_state_seq_flags flags) {
2383
- llama_io_write_dummy io;
2384
- try {
2385
- return state_seq_write_data(io, seq_id, flags);
2386
- } catch (const std::exception & err) {
2387
- LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
2388
- return 0;
2389
- }
2390
- }
2391
-
2392
- size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, size_t size, llama_state_seq_flags flags) {
2393
- llama_io_write_buffer io(dst, size);
2394
- try {
2395
- return state_seq_write_data(io, seq_id, flags);
2396
- } catch (const std::exception & err) {
2397
- LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
2398
- return 0;
2399
- }
2400
- }
2401
-
2402
- size_t llama_context::state_seq_set_data(llama_seq_id seq_id, const uint8_t * src, size_t size, llama_state_seq_flags flags) {
2403
- llama_io_read_buffer io(src, size);
2404
- try {
2405
- return state_seq_read_data(io, seq_id, flags);
2406
- } catch (const std::exception & err) {
2407
- LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
2408
- return 0;
2409
- }
2410
- }
2411
-
2412
- bool llama_context::state_load_file(const char * filepath, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
2413
- llama_file file(filepath, "rb");
2414
-
2415
- // sanity checks
2416
- {
2417
- const uint32_t magic = file.read_u32();
2418
- const uint32_t version = file.read_u32();
2419
-
2420
- if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
2421
- LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
2422
- return false;
2423
- }
2424
- }
2425
-
2426
- // load the prompt
2427
- {
2428
- const uint32_t n_token_count = file.read_u32();
2429
-
2430
- if (n_token_count > n_token_capacity) {
2431
- LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
2432
- return false;
2433
- }
2434
-
2435
- file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
2436
- *n_token_count_out = n_token_count;
2437
- }
2438
-
2439
- // restore the context state
2440
- {
2441
- const size_t n_state_size_cur = file.size() - file.tell();
2442
-
2443
- llama_io_read_file io( &file);
2444
- const size_t n_read = state_read_data(io);
2445
-
2446
- if (n_read != n_state_size_cur) {
2447
- LLAMA_LOG_ERROR("%s: did not read all of the session file data! size %zu, got %zu\n", __func__, n_state_size_cur, n_read);
2448
- return false;
2449
- }
2450
- }
2451
-
2452
- return true;
2453
- }
2454
-
2455
- bool llama_context::state_save_file(const char * filepath, const llama_token * tokens, size_t n_token_count) {
2456
- llama_file file(filepath, "wb");
2457
-
2458
- file.write_u32(LLAMA_SESSION_MAGIC);
2459
- file.write_u32(LLAMA_SESSION_VERSION);
2460
-
2461
- // save the prompt
2462
- file.write_u32((uint32_t) n_token_count);
2463
- file.write_raw(tokens, sizeof(llama_token) * n_token_count);
2464
-
2465
- // save the context state using stream saving
2466
- llama_io_write_file io(&file);
2467
- state_write_data(io);
2468
-
2469
- return true;
2470
- }
2471
-
2472
- size_t llama_context::state_seq_load_file(llama_seq_id seq_id, const char * filepath, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
2473
- llama_file file(filepath, "rb");
2474
-
2475
- // version checks
2476
- {
2477
- const uint32_t magic = file.read_u32();
2478
- const uint32_t version = file.read_u32();
2479
-
2480
- if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
2481
- LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
2482
- return 0;
2483
- }
2484
- }
2485
-
2486
- // load the prompt
2487
- {
2488
- const uint32_t n_token_count = file.read_u32();
2489
-
2490
- if (n_token_count > n_token_capacity) {
2491
- LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
2492
- return 0;
2493
- }
2494
-
2495
- file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
2496
- *n_token_count_out = n_token_count;
2497
- }
2498
-
2499
- // restore the context state
2500
- {
2501
- const size_t state_size = file.size() - file.tell();
2502
- llama_io_read_file io(&file);
2503
- const size_t nread = state_seq_read_data(io, seq_id, 0);
2504
- if (!nread) {
2505
- LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
2506
- return 0;
2507
- }
2508
- GGML_ASSERT(nread <= state_size);
2509
- GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
2510
- }
2511
-
2512
- return file.tell();
2513
- }
2514
-
2515
- size_t llama_context::state_seq_save_file(llama_seq_id seq_id, const char * filepath, const llama_token * tokens, size_t n_token_count) {
2516
- llama_file file(filepath, "wb");
2517
-
2518
- file.write_u32(LLAMA_STATE_SEQ_MAGIC);
2519
- file.write_u32(LLAMA_STATE_SEQ_VERSION);
2520
-
2521
- // save the prompt
2522
- file.write_u32((uint32_t) n_token_count);
2523
- file.write_raw(tokens, sizeof(llama_token) * n_token_count);
2524
-
2525
- // save the context state using stream saving
2526
- llama_io_write_file io(&file);
2527
- state_seq_write_data(io, seq_id, 0);
2528
-
2529
- const size_t res = file.tell();
2530
- GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + io.n_bytes());
2531
-
2532
- return res;
2533
- }
2534
-
2535
- size_t llama_context::state_write_data(llama_io_write_i & io) {
2536
- LLAMA_LOG_DEBUG("%s: writing state\n", __func__);
2537
-
2538
- // write model info
2539
- {
2540
- LLAMA_LOG_DEBUG("%s: - writing model info\n", __func__);
2541
-
2542
- const std::string arch_str = llm_arch_name(model.arch);
2543
- io.write_string(arch_str);
2544
- // TODO: add more model-specific info which should prevent loading the session file if not identical
2545
- }
2546
-
2547
- if (memory != nullptr) {
2548
- LLAMA_LOG_DEBUG("%s: - writing memory module\n", __func__);
2549
- memory->state_write(io);
2550
- }
2551
-
2552
- return io.n_bytes();
2553
- }
2554
-
2555
- size_t llama_context::state_read_data(llama_io_read_i & io) {
2556
- LLAMA_LOG_DEBUG("%s: reading state\n", __func__);
2557
-
2558
- // read model info
2559
- {
2560
- LLAMA_LOG_DEBUG("%s: - reading model info\n", __func__);
2561
-
2562
- const std::string cur_arch_str = llm_arch_name(model.arch);
2563
-
2564
- std::string arch_str;
2565
- io.read_string(arch_str);
2566
- if (cur_arch_str != arch_str) {
2567
- throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
2568
- }
2569
- // TODO: add more info which needs to be identical but which is not verified otherwise
2570
- }
2571
-
2572
- if (memory) {
2573
- LLAMA_LOG_DEBUG("%s: - reading memory module\n", __func__);
2574
-
2575
- memory->state_read(io);
2576
- }
2577
-
2578
- return io.n_bytes();
2579
- }
2580
-
2581
- size_t llama_context::state_seq_write_data(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
2582
- GGML_UNUSED(seq_id);
2583
-
2584
- if (memory) {
2585
- memory->state_write(io, seq_id, flags);
2586
- }
2587
-
2588
- return io.n_bytes();
2589
- }
2590
-
2591
- size_t llama_context::state_seq_read_data(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
2592
- GGML_UNUSED(seq_id);
2593
-
2594
- if (memory) {
2595
- memory->state_read(io, seq_id, flags);
2596
- }
2597
-
2598
- return io.n_bytes();
2599
- }
2600
-
2601
- //
2602
- // perf
2603
- //
2604
-
2605
- llama_perf_context_data llama_context::perf_get_data() const {
2606
- llama_perf_context_data data = {};
2607
-
2608
- data.t_start_ms = 1e-3 * t_start_us;
2609
- data.t_load_ms = 1e-3 * t_load_us;
2610
- data.t_p_eval_ms = 1e-3 * t_p_eval_us;
2611
- data.t_eval_ms = 1e-3 * t_eval_us;
2612
- data.n_p_eval = std::max(1, n_p_eval);
2613
- data.n_eval = std::max(1, n_eval);
2614
- data.n_reused = std::max(0, n_reused);
2615
-
2616
- return data;
2617
- }
2618
-
2619
- void llama_context::perf_reset() {
2620
- t_start_us = ggml_time_us();
2621
- t_eval_us = n_eval = 0;
2622
- t_p_eval_us = n_p_eval = 0;
2623
- n_reused = 0;
2624
- }
2625
-
2626
- std::map<ggml_backend_buffer_type_t, llama_memory_breakdown_data> llama_context::memory_breakdown() const {
2627
- std::map<ggml_backend_buffer_type_t, llama_memory_breakdown_data> ret;
2628
- for (const auto & [buft, size] : model.memory_breakdown()) {
2629
- ret[buft].model += size;
2630
- }
2631
- if (memory) {
2632
- for (const auto & [buft, size] : memory->memory_breakdown()) {
2633
- ret[buft].context += size;
2634
- }
2635
- }
2636
- if (model.hparams.no_alloc) {
2637
- for (size_t i = 0; i < backends.size(); ++i) {
2638
- ggml_backend_t backend = backends[i].get();
2639
- ggml_backend_buffer_type_t buft = ggml_backend_sched_get_buffer_type(sched.get(), backend);
2640
- ret[buft].compute += backend_buf_exp_size[i];
2641
- }
2642
- } else {
2643
- for (const auto & backend_ptr : backends) {
2644
- ggml_backend_t backend = backend_ptr.get();
2645
- ggml_backend_buffer_type_t buft = ggml_backend_sched_get_buffer_type(sched.get(), backend);
2646
- ret[buft].compute += ggml_backend_sched_get_buffer_size(sched.get(), backend);
2647
- }
2648
- }
2649
- return ret;
2650
- }
2651
-
2652
- //
2653
- // training
2654
- //
2655
-
2656
- static void llama_set_param(struct ggml_tensor * tensor, llama_opt_param_filter param_filter, void * userdata) {
2657
- if (!tensor || tensor->type != GGML_TYPE_F32) {
2658
- return;
2659
- }
2660
- if (!param_filter(tensor, userdata)) {
2661
- return;
2662
- }
2663
- if (strcmp(tensor->name, "token_embd.weight") == 0) {
2664
- return; // FIXME
2665
- }
2666
- if (strcmp(tensor->name, "rope_freqs.weight") == 0) {
2667
- return; // FIXME
2668
- }
2669
- ggml_set_param(tensor);
2670
- }
2671
-
2672
- void llama_context::opt_init(struct llama_model * model, struct llama_opt_params lopt_params) {
2673
- GGML_ASSERT(!opt_ctx);
2674
- model->hparams.n_ctx_train = lopt_params.n_ctx_train > 0 ? lopt_params.n_ctx_train : n_ctx();
2675
- const uint32_t n_batch = std::min(this->n_batch(), model->hparams.n_ctx_train);
2676
- const uint32_t n_ubatch = std::min(this->n_ubatch(), n_batch);
2677
- GGML_ASSERT(model->hparams.n_ctx_train % n_batch == 0);
2678
- GGML_ASSERT(n_batch % n_ubatch == 0);
2679
-
2680
- ggml_opt_params opt_params = ggml_opt_default_params(sched.get(), GGML_OPT_LOSS_TYPE_CROSS_ENTROPY);
2681
- opt_params.opt_period = n_batch / n_ubatch;
2682
- opt_params.get_opt_pars = lopt_params.get_opt_pars;
2683
- opt_params.get_opt_pars_ud = lopt_params.get_opt_pars_ud;
2684
- opt_params.optimizer = lopt_params.optimizer_type;
2685
- opt_ctx = ggml_opt_init(opt_params);
2686
-
2687
- llama_opt_param_filter param_filter = lopt_params.param_filter;
2688
- void * param_filter_ud = lopt_params.param_filter_ud;
2689
-
2690
- //llama_set_param(model->tok_embd, param_filter, param_filter_ud); // FIXME
2691
- llama_set_param(model->type_embd, param_filter, param_filter_ud);
2692
- llama_set_param(model->pos_embd, param_filter, param_filter_ud);
2693
- llama_set_param(model->tok_norm, param_filter, param_filter_ud);
2694
- llama_set_param(model->tok_norm_b, param_filter, param_filter_ud);
2695
- llama_set_param(model->output_norm, param_filter, param_filter_ud);
2696
- llama_set_param(model->output_norm_b, param_filter, param_filter_ud);
2697
- llama_set_param(model->output, param_filter, param_filter_ud);
2698
- llama_set_param(model->output_b, param_filter, param_filter_ud);
2699
- llama_set_param(model->output_norm_enc, param_filter, param_filter_ud);
2700
- llama_set_param(model->cls, param_filter, param_filter_ud);
2701
- llama_set_param(model->cls_b, param_filter, param_filter_ud);
2702
- llama_set_param(model->cls_out, param_filter, param_filter_ud);
2703
- llama_set_param(model->cls_out_b, param_filter, param_filter_ud);
2704
- llama_set_param(model->cls_norm, param_filter, param_filter_ud);
2705
-
2706
- for (struct llama_layer & layer : model->layers) {
2707
- for (size_t i = 0; i < sizeof(layer)/sizeof(struct ggml_tensor *); ++i) {
2708
- llama_set_param(reinterpret_cast<struct ggml_tensor **>(&layer)[i], param_filter, param_filter_ud);
2709
- }
2710
- }
2711
- }
2712
-
2713
- void llama_context::opt_epoch_iter(
2714
- ggml_opt_dataset_t dataset,
2715
- ggml_opt_result_t result,
2716
- const std::vector<llama_token> & tokens,
2717
- const std::vector<llama_token> & labels_sparse,
2718
- llama_batch & batch,
2719
- ggml_opt_epoch_callback callback,
2720
- bool train,
2721
- int64_t idata_in_loop,
2722
- int64_t ndata_in_loop,
2723
- int64_t t_loop_start) {
2724
- GGML_ASSERT(opt_ctx);
2725
- const uint32_t n_ctx = llama_model_n_ctx_train(&model);
2726
- const uint32_t n_batch = std::min(this->n_batch(), n_ctx);
2727
- const uint32_t n_ubatch = std::min(this->n_ubatch(), n_batch);
2728
-
2729
- memory->clear(true);
2730
-
2731
- for (uint32_t pos_ctx = 0; pos_ctx < n_ctx; pos_ctx += n_batch) {
2732
- batch.n_tokens = n_batch;
2733
- for (uint32_t pos_batch = 0; pos_batch < n_batch; ++pos_batch) {
2734
- batch.token [pos_batch] = tokens[pos_ctx + pos_batch];
2735
- batch.pos [pos_batch] = pos_ctx + pos_batch;
2736
- batch.n_seq_id[pos_batch] = 1;
2737
- batch.seq_id [pos_batch][0] = 0;
2738
- batch.logits [pos_batch] = true;
2739
- }
2740
-
2741
- if (!balloc->init(batch, model.vocab, nullptr, model.hparams.n_embd_inp(), cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max, true)) {
2742
- LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__);
2743
- return;
2744
- }
2745
-
2746
- const uint32_t n_tokens_all = balloc->get_n_tokens();
2747
-
2748
- n_queued_tokens += n_tokens_all;
2749
-
2750
- embd_seq.clear();
2751
-
2752
- uint32_t n_outputs_all = n_tokens_all;
2753
-
2754
- auto mctx = memory->init_batch(*balloc, cparams.n_ubatch, true);
2755
- if (!mctx || mctx->get_status() != LLAMA_MEMORY_STATUS_SUCCESS) {
2756
- LLAMA_LOG_ERROR("%s: could not initialize batch\n", __func__);
2757
- break;
2758
- }
2759
-
2760
- // reserve output buffer
2761
- if (output_reserve(n_outputs_all) < n_outputs_all) {
2762
- LLAMA_LOG_ERROR("%s: could not reserve space for batch with %d outputs\n", __func__, n_outputs_all);
2763
- GGML_ABORT("TODO: handle this error");
2764
- };
2765
-
2766
- uint32_t pos_batch = 0;
2767
- do {
2768
- const auto & ubatch = mctx->get_ubatch();
2769
-
2770
- n_outputs = ubatch.n_tokens;
2771
-
2772
- if (!mctx->apply()) {
2773
- LLAMA_LOG_ERROR("%s: failed to update the memory context\n", __func__);
2774
- break;
2775
- }
2776
-
2777
- auto * res = gf_res_prev.get();
2778
-
2779
- const auto gparams = graph_params(res, ubatch, mctx.get(), LLM_GRAPH_TYPE_DEFAULT);
2780
-
2781
- res->reset();
2782
-
2783
- auto * gf = model.build_graph(gparams);
2784
-
2785
- struct ggml_context * ctx_compute_opt;
2786
- {
2787
- const size_t size_gf = ggml_graph_size(gf);
2788
- const size_t size_meta = 4*size_gf*ggml_tensor_overhead() + 2*ggml_graph_overhead_custom(size_gf, /*grads = */ true);
2789
- struct ggml_init_params params = {
2790
- /*.mem_size =*/ size_meta,
2791
- /*.mem_buffer =*/ nullptr,
2792
- /*.no_alloc =*/ true,
2793
- };
2794
- ctx_compute_opt = ggml_init(params);
2795
- }
2796
- ggml_opt_prepare_alloc(opt_ctx, ctx_compute_opt, gf, res->get_inp_tokens(), res->get_logits());
2797
- ggml_opt_alloc(opt_ctx, train);
2798
-
2799
- res->set_inputs(&ubatch);
2800
- {
2801
- struct ggml_tensor * labels = ggml_opt_labels(opt_ctx);
2802
- GGML_ASSERT(labels->ne[1] == n_ubatch);
2803
- ggml_set_zero(labels);
2804
- const float onef = 1.0f;
2805
- for (uint32_t pos_ubatch = 0; pos_ubatch < n_ubatch; ++pos_ubatch) {
2806
- const uint32_t ilabel = pos_ctx + pos_batch + pos_ubatch;
2807
- GGML_ASSERT(labels_sparse[ilabel] < labels->ne[0]);
2808
- ggml_backend_tensor_set(labels, &onef, (pos_ubatch*labels->ne[0] + labels_sparse[ilabel])*sizeof(float), sizeof(float));
2809
- }
2810
- }
2811
- ggml_opt_eval(opt_ctx, result);
2812
- if (callback) {
2813
- callback(train, opt_ctx, dataset, result, idata_in_loop + (pos_ctx + pos_batch)/n_ubatch + 1, ndata_in_loop, t_loop_start);
2814
- }
2815
- ggml_free(ctx_compute_opt);
2816
-
2817
- pos_batch += ubatch.n_tokens;
2818
- } while (mctx->next());
2819
- }
2820
- }
2821
-
2822
- void llama_context::opt_epoch(
2823
- ggml_opt_dataset_t dataset,
2824
- ggml_opt_result_t result_train,
2825
- ggml_opt_result_t result_eval,
2826
- int64_t idata_split,
2827
- ggml_opt_epoch_callback callback_train,
2828
- ggml_opt_epoch_callback callback_eval) {
2829
- const uint32_t n_ctx = this->n_ctx();
2830
- const uint32_t n_batch = std::min(cparams.n_batch, n_ctx);
2831
- const uint32_t n_ubatch = std::min(cparams.n_ubatch, n_batch);
2832
- const int64_t ndata = ggml_opt_dataset_ndata(dataset);
2833
-
2834
- GGML_ASSERT(idata_split >= 0);
2835
- GGML_ASSERT(idata_split <= ndata);
2836
-
2837
- const uint32_t ubatch_per_ctx = n_ctx / n_ubatch;
2838
-
2839
- struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
2840
- std::vector<llama_token> tokens(n_ctx);
2841
- std::vector<llama_token> labels_sparse(n_ctx);
2842
-
2843
- int64_t idata = 0;
2844
-
2845
- int64_t t_loop_start = ggml_time_us();
2846
- int64_t ndata_in_loop = idata_split*ubatch_per_ctx;
2847
- for (; idata < idata_split; ++idata) {
2848
- constexpr bool train = true;
2849
- const int64_t idata_in_loop = idata*ubatch_per_ctx;
2850
-
2851
- ggml_opt_dataset_get_batch_host(dataset, tokens.data(), n_ctx*sizeof(llama_token), labels_sparse.data(), idata);
2852
- opt_epoch_iter(dataset, result_train, tokens, labels_sparse, batch,
2853
- callback_train, train, idata_in_loop, ndata_in_loop, t_loop_start);
2854
- }
2855
-
2856
- t_loop_start = ggml_time_us();
2857
- ndata_in_loop = (ndata - idata_split)*ubatch_per_ctx;
2858
- for (; idata < ndata; ++idata) {
2859
- constexpr bool train = false;
2860
- const int64_t idata_in_loop = (idata - idata_split)*ubatch_per_ctx;
2861
-
2862
- ggml_opt_dataset_get_batch_host(dataset, tokens.data(), n_ctx*sizeof(llama_token), labels_sparse.data(), idata);
2863
- opt_epoch_iter(dataset, result_eval, tokens, labels_sparse, batch,
2864
- callback_eval, train, idata_in_loop, ndata_in_loop, t_loop_start);
2865
- }
2866
-
2867
- llama_batch_free(batch);
2868
- }
2869
-
2870
- //
2871
- // interface implementation
2872
- //
2873
-
2874
- llama_context_params llama_context_default_params() {
2875
- llama_context_params result = {
2876
- /*.n_ctx =*/ 512,
2877
- /*.n_batch =*/ 2048,
2878
- /*.n_ubatch =*/ 512,
2879
- /*.n_seq_max =*/ 1,
2880
- /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
2881
- /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
2882
- /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
2883
- /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
2884
- /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
2885
- /*.flash_attn_type =*/ LLAMA_FLASH_ATTN_TYPE_AUTO,
2886
- /*.rope_freq_base =*/ 0.0f,
2887
- /*.rope_freq_scale =*/ 0.0f,
2888
- /*.yarn_ext_factor =*/ -1.0f,
2889
- /*.yarn_attn_factor =*/ -1.0f,
2890
- /*.yarn_beta_fast =*/ -1.0f,
2891
- /*.yarn_beta_slow =*/ -1.0f,
2892
- /*.yarn_orig_ctx =*/ 0,
2893
- /*.defrag_thold =*/ -1.0f,
2894
- /*.cb_eval =*/ nullptr,
2895
- /*.cb_eval_user_data =*/ nullptr,
2896
- /*.type_k =*/ GGML_TYPE_F16,
2897
- /*.type_v =*/ GGML_TYPE_F16,
2898
- /*.abort_callback =*/ nullptr,
2899
- /*.abort_callback_data =*/ nullptr,
2900
- /*.embeddings =*/ false,
2901
- /*.offload_kqv =*/ true,
2902
- /*.no_perf =*/ true,
2903
- /*.op_offload =*/ true,
2904
- /*.swa_full =*/ true,
2905
- /*.kv_unified =*/ false,
2906
- /*.sampler =*/ nullptr,
2907
- /*.n_sampler =*/ 0,
2908
- };
2909
-
2910
- return result;
2911
- }
2912
-
2913
- llama_context * llama_init_from_model(
2914
- llama_model * model,
2915
- llama_context_params params) {
2916
- if (!model) {
2917
- LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
2918
- return nullptr;
2919
- }
2920
-
2921
- if (params.n_batch == 0 && params.n_ubatch == 0) {
2922
- LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
2923
- return nullptr;
2924
- }
2925
-
2926
- if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
2927
- LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
2928
- return nullptr;
2929
- }
2930
-
2931
- if (params.flash_attn_type != LLAMA_FLASH_ATTN_TYPE_DISABLED && model->arch == LLM_ARCH_GROK) {
2932
- LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
2933
- params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED;
2934
- }
2935
-
2936
- if (params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO && ggml_is_quantized(params.type_k)) {
2937
- const uint32_t blck_size = ggml_blck_size(params.type_k);
2938
- for (uint32_t il = 0; il < model->hparams.n_layer; ++il) {
2939
- if (model->hparams.n_embd_head_k(il) % blck_size != 0) {
2940
- LLAMA_LOG_ERROR("%s: K cache type %s with block size %u does not divide n_embd_head_k=%u\n",
2941
- __func__, ggml_type_name(params.type_k), blck_size, model->hparams.n_embd_head_k(il));
2942
- return nullptr;
2943
- }
2944
- }
2945
- }
2946
-
2947
- if (params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO && ggml_is_quantized(params.type_v)) {
2948
- const uint32_t blck_size = ggml_blck_size(params.type_v);
2949
- for (uint32_t il = 0; il < model->hparams.n_layer; ++il) {
2950
- if (model->hparams.n_embd_head_v(il) % blck_size != 0) {
2951
- LLAMA_LOG_ERROR("%s: V cache type %s with block size %u does not divide n_embd_head_v=%u\n",
2952
- __func__, ggml_type_name(params.type_v), blck_size, model->hparams.n_embd_head_v(il));
2953
- return nullptr;
2954
- }
2955
- }
2956
- }
2957
-
2958
- if (ggml_is_quantized(params.type_v) && params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_DISABLED) {
2959
- LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
2960
- return nullptr;
2961
- }
2962
-
2963
- if (params.pooling_type != LLAMA_POOLING_TYPE_UNSPECIFIED &&
2964
- params.pooling_type != model->hparams.pooling_type) {
2965
- //user-specified pooling-type is different from the model default
2966
- LLAMA_LOG_WARN("%s: model default pooling_type is [%d], but [%d] was specified\n", __func__,
2967
- model->hparams.pooling_type, params.pooling_type);
2968
- }
2969
-
2970
- try {
2971
- auto * ctx = new llama_context(*model, params);
2972
- return ctx;
2973
- } catch (const std::exception & err) {
2974
- LLAMA_LOG_ERROR("%s: failed to initialize the context: %s\n", __func__, err.what());
2975
- }
2976
-
2977
- return nullptr;
2978
- }
2979
-
2980
- // deprecated
2981
- llama_context * llama_new_context_with_model(
2982
- llama_model * model,
2983
- llama_context_params params) {
2984
- return llama_init_from_model(model, params);
2985
- }
2986
-
2987
- void llama_free(llama_context * ctx) {
2988
- delete ctx;
2989
- }
2990
-
2991
- uint32_t llama_n_ctx(const llama_context * ctx) {
2992
- return ctx->n_ctx();
2993
- }
2994
-
2995
- uint32_t llama_n_ctx_seq(const llama_context * ctx) {
2996
- return ctx->n_ctx_seq();
2997
- }
2998
-
2999
- uint32_t llama_n_batch(const llama_context * ctx) {
3000
- return ctx->n_batch();
3001
- }
3002
-
3003
- uint32_t llama_n_ubatch(const llama_context * ctx) {
3004
- return ctx->n_ubatch();
3005
- }
3006
-
3007
- uint32_t llama_n_seq_max(const llama_context * ctx) {
3008
- return ctx->n_seq_max();
3009
- }
3010
-
3011
- const llama_model * llama_get_model(const llama_context * ctx) {
3012
- return &ctx->get_model();
3013
- }
3014
-
3015
- enum llama_pooling_type llama_pooling_type(const llama_context * ctx) {
3016
- return ctx->pooling_type();
3017
- }
3018
-
3019
- void llama_attach_threadpool(
3020
- llama_context * ctx,
3021
- ggml_threadpool_t threadpool,
3022
- ggml_threadpool_t threadpool_batch) {
3023
- ctx->attach_threadpool(threadpool, threadpool_batch);
3024
- }
3025
-
3026
- void llama_detach_threadpool(llama_context * ctx) {
3027
- ctx->detach_threadpool();
3028
- }
3029
-
3030
- void llama_set_n_threads(llama_context * ctx, int32_t n_threads, int32_t n_threads_batch) {
3031
- ctx->set_n_threads(n_threads, n_threads_batch);
3032
- }
3033
-
3034
- int32_t llama_n_threads(llama_context * ctx) {
3035
- return ctx->n_threads();
3036
- }
3037
-
3038
- int32_t llama_n_threads_batch(llama_context * ctx) {
3039
- return ctx->n_threads_batch();
3040
- }
3041
-
3042
- void llama_set_abort_callback(llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
3043
- ctx->set_abort_callback(abort_callback, abort_callback_data);
3044
- }
3045
-
3046
- void llama_set_embeddings(llama_context * ctx, bool embeddings) {
3047
- ctx->set_embeddings(embeddings);
3048
- }
3049
-
3050
- void llama_set_causal_attn(llama_context * ctx, bool causal_attn) {
3051
- ctx->set_causal_attn(causal_attn);
3052
- }
3053
-
3054
- void llama_set_warmup(llama_context * ctx, bool warmup) {
3055
- ctx->set_warmup(warmup);
3056
- }
3057
-
3058
- void llama_synchronize(llama_context * ctx) {
3059
- ctx->synchronize();
3060
- }
3061
-
3062
- float * llama_get_logits(llama_context * ctx) {
3063
- ctx->synchronize();
3064
-
3065
- return ctx->get_logits();
3066
- }
3067
-
3068
- float * llama_get_logits_ith(llama_context * ctx, int32_t i) {
3069
- ctx->synchronize();
3070
-
3071
- float * res = nullptr;
3072
-
3073
- res = ctx->get_sampled_logits_ith(i);
3074
-
3075
- if (!res) {
3076
- res = ctx->get_logits_ith(i);
3077
- }
3078
-
3079
- return res;
3080
- }
3081
-
3082
- float * llama_get_embeddings(llama_context * ctx) {
3083
- ctx->synchronize();
3084
-
3085
- return ctx->get_embeddings();
3086
- }
3087
-
3088
- float * llama_get_embeddings_ith(llama_context * ctx, int32_t i) {
3089
- ctx->synchronize();
3090
-
3091
- return ctx->get_embeddings_ith(i);
3092
- }
3093
-
3094
- float * llama_get_embeddings_seq(llama_context * ctx, llama_seq_id seq_id) {
3095
- ctx->synchronize();
3096
-
3097
- return ctx->get_embeddings_seq(seq_id);
3098
- }
3099
-
3100
- bool llama_set_sampler(llama_context * ctx, llama_seq_id seq_id, llama_sampler * smpl) {
3101
- return ctx->set_sampler(seq_id, smpl);
3102
- }
3103
-
3104
- llama_token llama_get_sampled_token_ith(llama_context * ctx, int32_t i) {
3105
- ctx->synchronize();
3106
-
3107
- return ctx->get_sampled_token_ith(i);
3108
- }
3109
-
3110
- float * llama_get_sampled_probs_ith(llama_context * ctx, int32_t i) {
3111
- ctx->synchronize();
3112
-
3113
- return ctx->get_sampled_probs_ith(i);
3114
- }
3115
-
3116
- float * llama_get_sampled_logits_ith(llama_context * ctx, int32_t i) {
3117
- ctx->synchronize();
3118
-
3119
- return ctx->get_sampled_logits_ith(i);
3120
- }
3121
-
3122
- llama_token * llama_get_sampled_candidates_ith(llama_context * ctx, int32_t i) {
3123
- ctx->synchronize();
3124
-
3125
- return const_cast<llama_token *>(ctx->get_sampled_candidates_ith(i));
3126
- }
3127
-
3128
- uint32_t llama_get_sampled_candidates_count_ith(llama_context * ctx, int32_t i) {
3129
- ctx->synchronize();
3130
-
3131
- return static_cast<uint32_t>(ctx->get_sampled_candidates_count(i));
3132
- }
3133
-
3134
- uint32_t llama_get_sampled_logits_count_ith(llama_context * ctx, int32_t i) {
3135
- ctx->synchronize();
3136
-
3137
- return static_cast<uint32_t>(ctx->get_sampled_logits_count(i));
3138
- }
3139
-
3140
- uint32_t llama_get_sampled_probs_count_ith(llama_context * ctx, int32_t i) {
3141
- ctx->synchronize();
3142
-
3143
- return static_cast<uint32_t>(ctx->get_sampled_probs_count(i));
3144
- }
3145
-
3146
- struct ggml_cgraph * llama_graph_reserve(
3147
- struct llama_context * ctx,
3148
- uint32_t n_tokens,
3149
- uint32_t n_seqs,
3150
- uint32_t n_outputs) {
3151
- auto * memory = ctx->get_memory();
3152
- llama_memory_context_ptr mctx;
3153
- if (memory) {
3154
- mctx = memory->init_full();
3155
- }
3156
- return ctx->graph_reserve(n_tokens, n_seqs, n_outputs, mctx.get());
3157
- }
3158
-
3159
- // llama adapter API
3160
-
3161
- int32_t llama_set_adapters_lora(
3162
- llama_context * ctx,
3163
- llama_adapter_lora ** adapters,
3164
- size_t n_adapters,
3165
- float * scales) {
3166
- if (adapters == nullptr || scales == nullptr) {
3167
- GGML_ASSERT(n_adapters == 0 && "invalid llama_set_adapters_lora call");
3168
- }
3169
-
3170
- ctx->set_adapters_lora(adapters, n_adapters, scales);
3171
-
3172
- return 0;
3173
- }
3174
-
3175
- int32_t llama_set_adapter_cvec(
3176
- llama_context * ctx,
3177
- const float * data,
3178
- size_t len,
3179
- int32_t n_embd,
3180
- int32_t il_start,
3181
- int32_t il_end) {
3182
- bool res = ctx->set_adapter_cvec(data, len, n_embd, il_start, il_end);
3183
-
3184
- return res ? 0 : -1;
3185
- }
3186
-
3187
- //
3188
- // memory
3189
- //
3190
-
3191
- llama_memory_t llama_get_memory(const struct llama_context * ctx) {
3192
- return ctx->get_memory();
3193
- }
3194
-
3195
- void llama_memory_clear(llama_memory_t mem, bool data) {
3196
- if (!mem) {
3197
- return;
3198
- }
3199
-
3200
- mem->clear(data);
3201
- }
3202
-
3203
- bool llama_memory_seq_rm(
3204
- llama_memory_t mem,
3205
- llama_seq_id seq_id,
3206
- llama_pos p0,
3207
- llama_pos p1) {
3208
- if (!mem) {
3209
- return true;
3210
- }
3211
-
3212
- return mem->seq_rm(seq_id, p0, p1);
3213
- }
3214
-
3215
- void llama_memory_seq_cp(
3216
- llama_memory_t mem,
3217
- llama_seq_id seq_id_src,
3218
- llama_seq_id seq_id_dst,
3219
- llama_pos p0,
3220
- llama_pos p1) {
3221
- if (!mem) {
3222
- return;
3223
- }
3224
-
3225
- mem->seq_cp(seq_id_src, seq_id_dst, p0, p1);
3226
- }
3227
-
3228
- void llama_memory_seq_keep(
3229
- llama_memory_t mem,
3230
- llama_seq_id seq_id) {
3231
- if (!mem) {
3232
- return;
3233
- }
3234
-
3235
- mem->seq_keep(seq_id);
3236
- }
3237
-
3238
- void llama_memory_seq_add(
3239
- llama_memory_t mem,
3240
- llama_seq_id seq_id,
3241
- llama_pos p0,
3242
- llama_pos p1,
3243
- llama_pos delta) {
3244
- if (!mem) {
3245
- return;
3246
- }
3247
-
3248
- mem->seq_add(seq_id, p0, p1, delta);
3249
- }
3250
-
3251
- void llama_memory_seq_div(
3252
- llama_memory_t mem,
3253
- llama_seq_id seq_id,
3254
- llama_pos p0,
3255
- llama_pos p1,
3256
- int d) {
3257
- if (!mem) {
3258
- return;
3259
- }
3260
-
3261
- mem->seq_div(seq_id, p0, p1, d);
3262
- }
3263
-
3264
- llama_pos llama_memory_seq_pos_min(
3265
- llama_memory_t mem,
3266
- llama_seq_id seq_id) {
3267
- if (!mem) {
3268
- return -1;
3269
- }
3270
-
3271
- return mem->seq_pos_min(seq_id);
3272
- }
3273
-
3274
- llama_pos llama_memory_seq_pos_max(
3275
- llama_memory_t mem,
3276
- llama_seq_id seq_id) {
3277
- if (!mem) {
3278
- return -1;
3279
- }
3280
-
3281
- return mem->seq_pos_max(seq_id);
3282
- }
3283
-
3284
- bool llama_memory_can_shift(llama_memory_t mem) {
3285
- if (!mem) {
3286
- return false;
3287
- }
3288
-
3289
- return mem->get_can_shift();
3290
- }
3291
-
3292
- // llama state API
3293
-
3294
- // deprecated
3295
- size_t llama_get_state_size(llama_context * ctx) {
3296
- return llama_state_get_size(ctx);
3297
- }
3298
-
3299
- // deprecated
3300
- size_t llama_copy_state_data(llama_context * ctx, uint8_t * dst) {
3301
- return llama_state_get_data(ctx, dst, -1);
3302
- }
3303
-
3304
- // deprecated
3305
- size_t llama_set_state_data(llama_context * ctx, const uint8_t * src) {
3306
- return llama_state_set_data(ctx, src, -1);
3307
- }
3308
-
3309
- // deprecated
3310
- bool llama_load_session_file(llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
3311
- return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
3312
- }
3313
-
3314
- // deprecated
3315
- bool llama_save_session_file(llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
3316
- return llama_state_save_file(ctx, path_session, tokens, n_token_count);
3317
- }
3318
-
3319
- // Returns the *actual* size of the state.
3320
- // Intended to be used when saving to state to a buffer.
3321
- size_t llama_state_get_size(llama_context * ctx) {
3322
- return ctx->state_get_size();
3323
- }
3324
-
3325
- size_t llama_state_get_data(llama_context * ctx, uint8_t * dst, size_t size) {
3326
- ctx->synchronize();
3327
-
3328
- return ctx->state_get_data(dst, size);
3329
- }
3330
-
3331
- // Sets the state reading from the specified source address
3332
- size_t llama_state_set_data(llama_context * ctx, const uint8_t * src, size_t size) {
3333
- ctx->synchronize();
3334
-
3335
- return ctx->state_set_data(src, size);
3336
- }
3337
-
3338
- bool llama_state_load_file(llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
3339
- ctx->synchronize();
3340
-
3341
- try {
3342
- return ctx->state_load_file(path_session, tokens_out, n_token_capacity, n_token_count_out);
3343
- } catch (const std::exception & err) {
3344
- LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
3345
- return false;
3346
- }
3347
- }
3348
-
3349
- bool llama_state_save_file(llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
3350
- ctx->synchronize();
3351
-
3352
- try {
3353
- return ctx->state_save_file(path_session, tokens, n_token_count);
3354
- } catch (const std::exception & err) {
3355
- LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
3356
- return false;
3357
- }
3358
- }
3359
-
3360
- size_t llama_state_seq_get_size(llama_context * ctx, llama_seq_id seq_id) {
3361
- return llama_state_seq_get_size_ext(ctx, seq_id, 0);
3362
- }
3363
-
3364
- size_t llama_state_seq_get_data(llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
3365
- return llama_state_seq_get_data_ext(ctx, dst, size, seq_id, 0);
3366
- }
3367
-
3368
- size_t llama_state_seq_set_data(llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id seq_id) {
3369
- return llama_state_seq_set_data_ext(ctx, src, size, seq_id, 0);
3370
- }
3371
-
3372
- size_t llama_state_seq_get_size_ext(llama_context * ctx, llama_seq_id seq_id, llama_state_seq_flags flags) {
3373
- return ctx->state_seq_get_size(seq_id, flags);
3374
- }
3375
-
3376
- size_t llama_state_seq_get_data_ext(llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags) {
3377
- ctx->synchronize();
3378
-
3379
- return ctx->state_seq_get_data(seq_id, dst, size, flags);
3380
- }
3381
-
3382
- size_t llama_state_seq_set_data_ext(llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags) {
3383
- ctx->synchronize();
3384
-
3385
- return ctx->state_seq_set_data(seq_id, src, size, flags);
3386
- }
3387
-
3388
- size_t llama_state_seq_save_file(llama_context * ctx, const char * filepath, llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count) {
3389
- ctx->synchronize();
3390
-
3391
- try {
3392
- return ctx->state_seq_save_file(seq_id, filepath, tokens, n_token_count);
3393
- } catch (const std::exception & err) {
3394
- LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
3395
- return 0;
3396
- }
3397
- }
3398
-
3399
- size_t llama_state_seq_load_file(llama_context * ctx, const char * filepath, llama_seq_id dest_seq_id, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
3400
- ctx->synchronize();
3401
-
3402
- try {
3403
- return ctx->state_seq_load_file(dest_seq_id, filepath, tokens_out, n_token_capacity, n_token_count_out);
3404
- } catch (const std::exception & err) {
3405
- LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
3406
- return 0;
3407
- }
3408
- }
3409
-
3410
- ///
3411
-
3412
- int32_t llama_encode(
3413
- llama_context * ctx,
3414
- llama_batch batch) {
3415
- const int ret = ctx->encode(batch);
3416
- if (ret != 0) {
3417
- LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
3418
- }
3419
-
3420
- return ret;
3421
- }
3422
-
3423
- int32_t llama_decode(
3424
- llama_context * ctx,
3425
- llama_batch batch) {
3426
- const int ret = ctx->decode(batch);
3427
- if (ret != 0 && ret != 1) {
3428
- LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
3429
- }
3430
-
3431
- return ret;
3432
- }
3433
-
3434
- //
3435
- // perf
3436
- //
3437
-
3438
- llama_perf_context_data llama_perf_context(const llama_context * ctx) {
3439
- llama_perf_context_data data = {};
3440
-
3441
- if (ctx == nullptr) {
3442
- return data;
3443
- }
3444
-
3445
- data = ctx->perf_get_data();
3446
-
3447
- return data;
3448
- }
3449
-
3450
- void llama_perf_context_print(const llama_context * ctx) {
3451
- const auto data = llama_perf_context(ctx);
3452
-
3453
- const double t_end_ms = 1e-3 * ggml_time_us();
3454
-
3455
- LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, data.t_load_ms);
3456
- LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
3457
- __func__, data.t_p_eval_ms, data.n_p_eval, data.t_p_eval_ms / data.n_p_eval, 1e3 / data.t_p_eval_ms * data.n_p_eval);
3458
- LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
3459
- __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
3460
- LLAMA_LOG_INFO("%s: total time = %10.2f ms / %5d tokens\n", __func__, (t_end_ms - data.t_start_ms), (data.n_p_eval + data.n_eval));
3461
- LLAMA_LOG_INFO("%s: graphs reused = %10d\n", __func__, data.n_reused);
3462
- }
3463
-
3464
- void llama_perf_context_reset(llama_context * ctx) {
3465
- ctx->perf_reset();
3466
- }
3467
-
3468
- void llama_memory_breakdown_print(const struct llama_context * ctx) {
3469
- const std::vector<ggml_backend_dev_t> & devices = ctx->get_model().devices;
3470
-
3471
- std::map<ggml_backend_buffer_type_t, llama_memory_breakdown_data> memory_breakdown = ctx->memory_breakdown();
3472
-
3473
- std::vector<std::array<std::string, 9>> table_data;
3474
- table_data.reserve(devices.size());
3475
- const std::string template_header = "%s: | %s | %s %s %s %s %s %s %s |\n";
3476
- const std::string template_gpu = "%s: | %s | %s = %s + (%s = %s + %s + %s) + %s |\n";
3477
- const std::string template_other = "%s: | %s | %s %s %s = %s + %s + %s %s |\n";
3478
-
3479
- table_data.push_back({template_header, "memory breakdown [MiB]", "total", "free", "self", "model", "context", "compute", "unaccounted"});
3480
-
3481
- constexpr size_t MiB = 1024 * 1024;
3482
- const std::vector<std::string> desc_prefixes_strip = {"NVIDIA ", "GeForce ", "Tesla ", "AMD ", "Radeon ", "Instinct "};
3483
-
3484
- // track seen buffer types to avoid double counting:
3485
- std::set<ggml_backend_buffer_type_t> seen_buffer_types;
3486
-
3487
- // accumulative memory breakdown for each device and for host:
3488
- std::vector<llama_memory_breakdown_data> mb_dev(devices.size());
3489
- llama_memory_breakdown_data mb_host;
3490
-
3491
- for (const auto & buft_mb : memory_breakdown) {
3492
- ggml_backend_buffer_type_t buft = buft_mb.first;
3493
- const llama_memory_breakdown_data & mb = buft_mb.second;
3494
- if (ggml_backend_buft_is_host(buft)) {
3495
- mb_host.model += mb.model;
3496
- mb_host.context += mb.context;
3497
- mb_host.compute += mb.compute;
3498
- seen_buffer_types.insert(buft);
3499
- continue;
3500
- }
3501
- ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft);
3502
- if (dev) {
3503
- int i_dev = -1;
3504
- for (size_t i = 0; i < devices.size(); i++) {
3505
- if (devices[i] == dev) {
3506
- i_dev = i;
3507
- break;
3508
- }
3509
- }
3510
- if (i_dev != -1) {
3511
- mb_dev[i_dev].model += mb.model;
3512
- mb_dev[i_dev].context += mb.context;
3513
- mb_dev[i_dev].compute += mb.compute;
3514
- seen_buffer_types.insert(buft);
3515
- continue;
3516
- }
3517
- }
3518
- }
3519
-
3520
- // print memory breakdown for each device:
3521
- for (size_t i = 0; i < devices.size(); i++) {
3522
- ggml_backend_dev_t dev = devices[i];
3523
- llama_memory_breakdown_data mb = mb_dev[i];
3524
-
3525
- const std::string name = ggml_backend_dev_name(dev);
3526
- std::string desc = ggml_backend_dev_description(dev);
3527
- for (const std::string & prefix : desc_prefixes_strip) {
3528
- if (desc.length() >= prefix.length() && desc.substr(0, prefix.length()) == prefix) {
3529
- desc = desc.substr(prefix.length());
3530
- }
3531
- }
3532
-
3533
- size_t free, total;
3534
- ggml_backend_dev_memory(dev, &free, &total);
3535
-
3536
- const size_t self = mb.model + mb.context + mb.compute;
3537
- const size_t unaccounted = total - self - free;
3538
-
3539
- table_data.push_back({
3540
- template_gpu,
3541
- " - " + name + " (" + desc + ")",
3542
- std::to_string(total / MiB),
3543
- std::to_string(free / MiB),
3544
- std::to_string(self / MiB),
3545
- std::to_string(mb.model / MiB),
3546
- std::to_string(mb.context / MiB),
3547
- std::to_string(mb.compute / MiB),
3548
- std::to_string(unaccounted / MiB)});
3549
- }
3550
-
3551
- // print memory breakdown for host:
3552
- {
3553
- const size_t self = mb_host.model + mb_host.context + mb_host.compute;
3554
- table_data.push_back({
3555
- template_other,
3556
- " - Host",
3557
- "", // total
3558
- "", // free
3559
- std::to_string(self / MiB),
3560
- std::to_string(mb_host.model / MiB),
3561
- std::to_string(mb_host.context / MiB),
3562
- std::to_string(mb_host.compute / MiB),
3563
- ""}); // unaccounted
3564
- }
3565
-
3566
- // print memory breakdown for all remaining buffer types:
3567
- for (const auto & buft_mb : memory_breakdown) {
3568
- ggml_backend_buffer_type_t buft = buft_mb.first;
3569
- const llama_memory_breakdown_data & mb = buft_mb.second;
3570
- if (seen_buffer_types.count(buft) == 1) {
3571
- continue;
3572
- }
3573
- const std::string name = ggml_backend_buft_name(buft);
3574
- const size_t self = mb.model + mb.context + mb.compute;
3575
- table_data.push_back({
3576
- template_other,
3577
- " - " + name,
3578
- "", // total
3579
- "", // free
3580
- std::to_string(self / MiB),
3581
- std::to_string(mb.model / MiB),
3582
- std::to_string(mb.context / MiB),
3583
- std::to_string(mb.compute / MiB),
3584
- ""}); // unaccounted
3585
- seen_buffer_types.insert(buft);
3586
- }
3587
-
3588
- for (size_t j = 1; j < table_data[0].size(); j++) {
3589
- size_t max_len = 0;
3590
- for (const auto & td : table_data) {
3591
- max_len = std::max(max_len, td[j].length());
3592
- }
3593
- for (auto & td : table_data) {
3594
- td[j].insert(j == 1 ? td[j].length() : 0, max_len - td[j].length(), ' ');
3595
- }
3596
- }
3597
- for (const auto & td : table_data) {
3598
- LLAMA_LOG_INFO(td[0].c_str(),
3599
- __func__, td[1].c_str(), td[2].c_str(), td[3].c_str(), td[4].c_str(), td[5].c_str(),
3600
- td[6].c_str(), td[7].c_str(), td[8].c_str());
3601
- }
3602
- }
3603
-
3604
- //
3605
- // training
3606
- //
3607
-
3608
- bool llama_opt_param_filter_all(const struct ggml_tensor * tensor, void * userdata) {
3609
- GGML_UNUSED(tensor);
3610
- GGML_UNUSED(userdata);
3611
- return true;
3612
- }
3613
-
3614
- void llama_opt_init(struct llama_context * ctx, struct llama_model * model, struct llama_opt_params lopt_params) {
3615
- ctx->opt_init(model, lopt_params);
3616
- }
3617
-
3618
- void llama_opt_epoch(
3619
- struct llama_context * ctx,
3620
- ggml_opt_dataset_t dataset,
3621
- ggml_opt_result_t result_train,
3622
- ggml_opt_result_t result_eval,
3623
- int64_t idata_split,
3624
- ggml_opt_epoch_callback callback_train,
3625
- ggml_opt_epoch_callback callback_eval) {
3626
- ctx->opt_epoch(
3627
- dataset,
3628
- result_train,
3629
- result_eval,
3630
- idata_split,
3631
- callback_train,
3632
- callback_eval);
3633
- }