You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

NativeApi.cs 21 kB

2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. using System;
  2. using System.Runtime.InteropServices;
  3. #pragma warning disable IDE1006 // Naming Styles
  4. namespace LLama.Native
  5. {
  6. /// <summary>
  7. /// Callback from llama.cpp with log messages
  8. /// </summary>
  9. /// <param name="level"></param>
  10. /// <param name="message"></param>
  11. public delegate void LLamaLogCallback(LLamaLogLevel level, string message);
  12. /// <summary>
  13. /// Direct translation of the llama.cpp API
  14. /// </summary>
  15. public static partial class NativeApi
  16. {
  17. /// <summary>
  18. /// A method that does nothing. This is a native method, calling it will force the llama native dependencies to be loaded.
  19. /// </summary>
  20. /// <returns></returns>
  21. public static void llama_empty_call()
  22. {
  23. llama_max_devices();
  24. }
  25. /// <summary>
  26. /// Get the maximum number of devices supported by llama.cpp
  27. /// </summary>
  28. /// <returns></returns>
  29. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  30. public static extern long llama_max_devices();
  31. /// <summary>
  32. /// Create a LLamaModelParams with default values
  33. /// </summary>
  34. /// <returns></returns>
  35. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  36. public static extern LLamaModelParams llama_model_default_params();
  37. /// <summary>
  38. /// Create a LLamaContextParams with default values
  39. /// </summary>
  40. /// <returns></returns>
  41. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  42. public static extern LLamaContextParams llama_context_default_params();
  43. /// <summary>
  44. /// Create a LLamaModelQuantizeParams with default values
  45. /// </summary>
  46. /// <returns></returns>
  47. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  48. public static extern LLamaModelQuantizeParams llama_model_quantize_default_params();
  49. /// <summary>
  50. /// Check if memory mapping is supported
  51. /// </summary>
  52. /// <returns></returns>
  53. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  54. public static extern bool llama_supports_mmap();
  55. /// <summary>
  56. /// Check if memory locking is supported
  57. /// </summary>
  58. /// <returns></returns>
  59. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  60. public static extern bool llama_supports_mlock();
  61. /// <summary>
  62. /// Check if GPU offload is supported
  63. /// </summary>
  64. /// <returns></returns>
  65. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  66. public static extern bool llama_supports_gpu_offload();
  67. /// <summary>
  68. /// Initialize the llama + ggml backend
  69. /// Call once at the start of the program
  70. /// </summary>
  71. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  72. private static extern void llama_backend_init(bool numa);
  73. /// <summary>
  74. /// Sets the current rng seed.
  75. /// </summary>
  76. /// <param name="ctx"></param>
  77. /// <param name="seed"></param>
  78. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  79. public static extern void llama_set_rng_seed(SafeLLamaContextHandle ctx, uint seed);
  80. /// <summary>
  81. /// Returns the maximum size in bytes of the state (rng, logits, embedding
  82. /// and kv_cache) - will often be smaller after compacting tokens
  83. /// </summary>
  84. /// <param name="ctx"></param>
  85. /// <returns></returns>
  86. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  87. public static extern ulong llama_get_state_size(SafeLLamaContextHandle ctx);
  88. /// <summary>
  89. /// Copies the state to the specified destination address.
  90. /// Destination needs to have allocated enough memory.
  91. /// </summary>
  92. /// <param name="ctx"></param>
  93. /// <param name="dest"></param>
  94. /// <returns>the number of bytes copied</returns>
  95. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  96. public static extern unsafe ulong llama_copy_state_data(SafeLLamaContextHandle ctx, byte* dest);
  97. /// <summary>
  98. /// Set the state reading from the specified address
  99. /// </summary>
  100. /// <param name="ctx"></param>
  101. /// <param name="src"></param>
  102. /// <returns>the number of bytes read</returns>
  103. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  104. public static extern unsafe ulong llama_set_state_data(SafeLLamaContextHandle ctx, byte* src);
  105. /// <summary>
  106. /// Load session file
  107. /// </summary>
  108. /// <param name="ctx"></param>
  109. /// <param name="path_session"></param>
  110. /// <param name="tokens_out"></param>
  111. /// <param name="n_token_capacity"></param>
  112. /// <param name="n_token_count_out"></param>
  113. /// <returns></returns>
  114. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  115. public static extern bool llama_load_session_file(SafeLLamaContextHandle ctx, string path_session, LLamaToken[] tokens_out, ulong n_token_capacity, out ulong n_token_count_out);
  116. /// <summary>
  117. /// Save session file
  118. /// </summary>
  119. /// <param name="ctx"></param>
  120. /// <param name="path_session"></param>
  121. /// <param name="tokens"></param>
  122. /// <param name="n_token_count"></param>
  123. /// <returns></returns>
  124. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  125. public static extern bool llama_save_session_file(SafeLLamaContextHandle ctx, string path_session, LLamaToken[] tokens, ulong n_token_count);
  126. /// <summary>
  127. /// Run the llama inference to obtain the logits and probabilities for the next token.
  128. /// tokens + n_tokens is the provided batch of new tokens to process
  129. /// n_past is the number of tokens to use from previous eval calls
  130. /// </summary>
  131. /// <param name="ctx"></param>
  132. /// <param name="tokens"></param>
  133. /// <param name="n_tokens"></param>
  134. /// <param name="n_past"></param>
  135. /// <returns>Returns 0 on success</returns>
  136. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  137. [Obsolete("use llama_decode() instead")]
  138. public static extern unsafe int llama_eval(SafeLLamaContextHandle ctx, LLamaToken* tokens, int n_tokens, int n_past);
  139. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  140. public static extern unsafe byte* llama_token_get_text(SafeLlamaModelHandle model, LLamaToken token);
  141. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  142. public static extern float llama_token_get_score(SafeLlamaModelHandle model, LLamaToken token);
  143. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  144. public static extern LLamaTokenType llama_token_get_type(SafeLlamaModelHandle model, LLamaToken token);
  145. /// <summary>
  146. /// Get the size of the context window for the model for this context
  147. /// </summary>
  148. /// <param name="ctx"></param>
  149. /// <returns></returns>
  150. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  151. public static extern uint llama_n_ctx(SafeLLamaContextHandle ctx);
  152. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  153. public static extern uint llama_n_batch(SafeLLamaContextHandle ctx);
  154. /// <summary>
  155. /// Token logits obtained from the last call to llama_eval()
  156. /// The logits for the last token are stored in the last row
  157. /// Can be mutated in order to change the probabilities of the next token.<br />
  158. /// Rows: n_tokens<br />
  159. /// Cols: n_vocab
  160. /// </summary>
  161. /// <param name="ctx"></param>
  162. /// <returns></returns>
  163. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  164. public static extern unsafe float* llama_get_logits(SafeLLamaContextHandle ctx);
  165. /// <summary>
  166. /// Logits for the ith token. Equivalent to: llama_get_logits(ctx) + i*n_vocab
  167. /// </summary>
  168. /// <param name="ctx"></param>
  169. /// <param name="i"></param>
  170. /// <returns></returns>
  171. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  172. public static extern unsafe float* llama_get_logits_ith(SafeLLamaContextHandle ctx, int i);
  173. /// <summary>
  174. /// Get the embeddings for the input
  175. /// </summary>
  176. /// <param name="ctx"></param>
  177. /// <returns></returns>
  178. public static Span<float> llama_get_embeddings(SafeLLamaContextHandle ctx)
  179. {
  180. unsafe
  181. {
  182. var ptr = llama_get_embeddings_native(ctx);
  183. return new Span<float>(ptr, ctx.EmbeddingSize);
  184. }
  185. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "llama_get_embeddings")]
  186. static extern unsafe float* llama_get_embeddings_native(SafeLLamaContextHandle ctx);
  187. }
  188. /// <summary>
  189. /// Get the "Beginning of sentence" token
  190. /// </summary>
  191. /// <returns></returns>
  192. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  193. public static extern LLamaToken llama_token_bos(SafeLlamaModelHandle model);
  194. /// <summary>
  195. /// Get the "End of sentence" token
  196. /// </summary>
  197. /// <returns></returns>
  198. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  199. public static extern LLamaToken llama_token_eos(SafeLlamaModelHandle model);
  200. /// <summary>
  201. /// Get the "new line" token
  202. /// </summary>
  203. /// <returns></returns>
  204. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  205. public static extern LLamaToken llama_token_nl(SafeLlamaModelHandle model);
  206. /// <summary>
  207. /// Returns -1 if unknown, 1 for true or 0 for false.
  208. /// </summary>
  209. /// <returns></returns>
  210. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  211. public static extern int llama_add_bos_token(SafeLlamaModelHandle model);
  212. /// <summary>
  213. /// Returns -1 if unknown, 1 for true or 0 for false.
  214. /// </summary>
  215. /// <returns></returns>
  216. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  217. public static extern int llama_add_eos_token(SafeLlamaModelHandle model);
  218. /// <summary>
  219. /// codellama infill tokens, Beginning of infill prefix
  220. /// </summary>
  221. /// <returns></returns>
  222. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  223. public static extern int llama_token_prefix(SafeLlamaModelHandle model);
  224. /// <summary>
  225. /// codellama infill tokens, Beginning of infill middle
  226. /// </summary>
  227. /// <returns></returns>
  228. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  229. public static extern int llama_token_middle(SafeLlamaModelHandle model);
  230. /// <summary>
  231. /// codellama infill tokens, Beginning of infill suffix
  232. /// </summary>
  233. /// <returns></returns>
  234. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  235. public static extern int llama_token_suffix(SafeLlamaModelHandle model);
  236. /// <summary>
  237. /// codellama infill tokens, End of infill middle
  238. /// </summary>
  239. /// <returns></returns>
  240. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  241. public static extern int llama_token_eot(SafeLlamaModelHandle model);
  242. /// <summary>
  243. /// Print out timing information for this context
  244. /// </summary>
  245. /// <param name="ctx"></param>
  246. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  247. public static extern void llama_print_timings(SafeLLamaContextHandle ctx);
  248. /// <summary>
  249. /// Reset all collected timing information for this context
  250. /// </summary>
  251. /// <param name="ctx"></param>
  252. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  253. public static extern void llama_reset_timings(SafeLLamaContextHandle ctx);
  254. /// <summary>
  255. /// Print system information
  256. /// </summary>
  257. /// <returns></returns>
  258. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  259. public static extern IntPtr llama_print_system_info();
  260. /// <summary>
  261. /// Convert a single token into text
  262. /// </summary>
  263. /// <param name="model"></param>
  264. /// <param name="llamaToken"></param>
  265. /// <param name="buffer">buffer to write string into</param>
  266. /// <returns>The length written, or if the buffer is too small a negative that indicates the length required</returns>
  267. public static int llama_token_to_piece(SafeLlamaModelHandle model, LLamaToken llamaToken, Span<byte> buffer)
  268. {
  269. unsafe
  270. {
  271. fixed (byte* bufferPtr = buffer)
  272. {
  273. return llama_token_to_piece_native(model, llamaToken, bufferPtr, buffer.Length);
  274. }
  275. }
  276. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "llama_token_to_piece")]
  277. static extern unsafe int llama_token_to_piece_native(SafeLlamaModelHandle model, LLamaToken llamaToken, byte* buffer, int length);
  278. }
  279. /// <summary>
  280. /// Convert text into tokens
  281. /// </summary>
  282. /// <param name="model"></param>
  283. /// <param name="text"></param>
  284. /// <param name="text_len"></param>
  285. /// <param name="tokens"></param>
  286. /// <param name="n_max_tokens"></param>
  287. /// <param name="add_bos"></param>
  288. /// <param name="special">Allow tokenizing special and/or control tokens which otherwise are not exposed and treated as plaintext. Does not insert a leading space.</param>
  289. /// <returns>Returns the number of tokens on success, no more than n_max_tokens.
  290. /// Returns a negative number on failure - the number of tokens that would have been returned
  291. /// </returns>
  292. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  293. public static extern unsafe int llama_tokenize(SafeLlamaModelHandle model, byte* text, int text_len, LLamaToken* tokens, int n_max_tokens, bool add_bos, bool special);
  294. /// <summary>
  295. /// Register a callback to receive llama log messages
  296. /// </summary>
  297. /// <param name="logCallback"></param>
  298. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  299. public static extern void llama_log_set(LLamaLogCallback logCallback);
  300. /// <summary>
  301. /// Clear the KV cache
  302. /// </summary>
  303. /// <param name="ctx"></param>
  304. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  305. public static extern void llama_kv_cache_clear(SafeLLamaContextHandle ctx);
  306. /// <summary>
  307. /// Removes all tokens that belong to the specified sequence and have positions in [p0, p1)
  308. /// </summary>
  309. /// <param name="ctx"></param>
  310. /// <param name="seq"></param>
  311. /// <param name="p0"></param>
  312. /// <param name="p1"></param>
  313. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  314. public static extern void llama_kv_cache_seq_rm(SafeLLamaContextHandle ctx, LLamaSeqId seq, LLamaPos p0, LLamaPos p1);
  315. /// <summary>
  316. /// Copy all tokens that belong to the specified sequence to another sequence
  317. /// Note that this does not allocate extra KV cache memory - it simply assigns the tokens to the new sequence
  318. /// </summary>
  319. /// <param name="ctx"></param>
  320. /// <param name="src"></param>
  321. /// <param name="dest"></param>
  322. /// <param name="p0"></param>
  323. /// <param name="p1"></param>
  324. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  325. public static extern void llama_kv_cache_seq_cp(SafeLLamaContextHandle ctx, LLamaSeqId src, LLamaSeqId dest, LLamaPos p0, LLamaPos p1);
  326. /// <summary>
  327. /// Removes all tokens that do not belong to the specified sequence
  328. /// </summary>
  329. /// <param name="ctx"></param>
  330. /// <param name="seq"></param>
  331. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  332. public static extern void llama_kv_cache_seq_keep(SafeLLamaContextHandle ctx, LLamaSeqId seq);
  333. /// <summary>
  334. /// Adds relative position "delta" to all tokens that belong to the specified sequence and have positions in [p0, p1)
  335. /// If the KV cache is RoPEd, the KV data is updated accordingly
  336. /// </summary>
  337. /// <param name="ctx"></param>
  338. /// <param name="seq"></param>
  339. /// <param name="p0"></param>
  340. /// <param name="p1"></param>
  341. /// <param name="delta"></param>
  342. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  343. public static extern void llama_kv_cache_seq_shift(SafeLLamaContextHandle ctx, LLamaSeqId seq, LLamaPos p0, LLamaPos p1, int delta);
  344. /// <summary>
  345. /// Integer division of the positions by factor of `d > 1`
  346. /// If the KV cache is RoPEd, the KV data is updated accordingly
  347. /// p0 &lt; 0 : [0, p1]
  348. /// p1 &lt; 0 : [p0, inf)
  349. /// </summary>
  350. /// <param name="ctx"></param>
  351. /// <param name="seq"></param>
  352. /// <param name="p0"></param>
  353. /// <param name="p1"></param>
  354. /// <param name="d"></param>
  355. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  356. public static extern void llama_kv_cache_seq_div(SafeLLamaContextHandle ctx, LLamaSeqId seq, LLamaPos p0, LLamaPos p1, int d);
  357. /// <summary>
  358. /// Allocates a batch of tokens on the heap
  359. /// Each token can be assigned up to n_seq_max sequence ids
  360. /// The batch has to be freed with llama_batch_free()
  361. /// If embd != 0, llama_batch.embd will be allocated with size of n_tokens * embd * sizeof(float)
  362. /// Otherwise, llama_batch.token will be allocated to store n_tokens llama_token
  363. /// The rest of the llama_batch members are allocated with size n_tokens
  364. /// All members are left uninitialized
  365. /// </summary>
  366. /// <param name="n_tokens"></param>
  367. /// <param name="embd"></param>
  368. /// <param name="n_seq_max">Each token can be assigned up to n_seq_max sequence ids</param>
  369. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  370. public static extern LLamaNativeBatch llama_batch_init(int n_tokens, int embd, int n_seq_max);
  371. /// <summary>
  372. /// Frees a batch of tokens allocated with llama_batch_init()
  373. /// </summary>
  374. /// <param name="batch"></param>
  375. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  376. public static extern void llama_batch_free(LLamaNativeBatch batch);
  377. /// <summary>
  378. /// </summary>
  379. /// <param name="ctx"></param>
  380. /// <param name="batch"></param>
  381. /// <returns>Positive return values does not mean a fatal error, but rather a warning:<br />
  382. /// - 0: success<br />
  383. /// - 1: could not find a KV slot for the batch (try reducing the size of the batch or increase the context)<br />
  384. /// - &lt; 0: error<br />
  385. /// </returns>
  386. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  387. public static extern int llama_decode(SafeLLamaContextHandle ctx, LLamaNativeBatch batch);
  388. /// <summary>
  389. /// Set the number of threads used for decoding
  390. /// </summary>
  391. /// <param name="ctx"></param>
  392. /// <param name="n_threads">n_threads is the number of threads used for generation (single token)</param>
  393. /// <param name="n_threads_batch">n_threads_batch is the number of threads used for prompt and batch processing (multiple tokens)</param>
  394. /// <returns></returns>
  395. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  396. public static extern void llama_set_n_threads(SafeLLamaContextHandle ctx, uint n_threads, uint n_threads_batch);
  397. }
  398. }