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 20 kB

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