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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. /// <summary>
  153. /// Get the batch size for this context
  154. /// </summary>
  155. /// <param name="ctx"></param>
  156. /// <returns></returns>
  157. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  158. public static extern uint llama_n_batch(SafeLLamaContextHandle ctx);
  159. /// <summary>
  160. /// Token logits obtained from the last call to llama_eval()
  161. /// The logits for the last token are stored in the last row
  162. /// Can be mutated in order to change the probabilities of the next token.<br />
  163. /// Rows: n_tokens<br />
  164. /// Cols: n_vocab
  165. /// </summary>
  166. /// <param name="ctx"></param>
  167. /// <returns></returns>
  168. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  169. public static extern unsafe float* llama_get_logits(SafeLLamaContextHandle ctx);
  170. /// <summary>
  171. /// Logits for the ith token. Equivalent to: llama_get_logits(ctx) + i*n_vocab
  172. /// </summary>
  173. /// <param name="ctx"></param>
  174. /// <param name="i"></param>
  175. /// <returns></returns>
  176. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  177. public static extern unsafe float* llama_get_logits_ith(SafeLLamaContextHandle ctx, int i);
  178. /// <summary>
  179. /// Get the embeddings for the input
  180. /// </summary>
  181. /// <param name="ctx"></param>
  182. /// <returns></returns>
  183. public static Span<float> llama_get_embeddings(SafeLLamaContextHandle ctx)
  184. {
  185. unsafe
  186. {
  187. var ptr = llama_get_embeddings_native(ctx);
  188. return new Span<float>(ptr, ctx.EmbeddingSize);
  189. }
  190. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "llama_get_embeddings")]
  191. static extern unsafe float* llama_get_embeddings_native(SafeLLamaContextHandle ctx);
  192. }
  193. /// <summary>
  194. /// Get the "Beginning of sentence" token
  195. /// </summary>
  196. /// <returns></returns>
  197. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  198. public static extern LLamaToken llama_token_bos(SafeLlamaModelHandle model);
  199. /// <summary>
  200. /// Get the "End of sentence" token
  201. /// </summary>
  202. /// <returns></returns>
  203. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  204. public static extern LLamaToken llama_token_eos(SafeLlamaModelHandle model);
  205. /// <summary>
  206. /// Get the "new line" token
  207. /// </summary>
  208. /// <returns></returns>
  209. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  210. public static extern LLamaToken llama_token_nl(SafeLlamaModelHandle model);
  211. /// <summary>
  212. /// Returns -1 if unknown, 1 for true or 0 for false.
  213. /// </summary>
  214. /// <returns></returns>
  215. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  216. public static extern int llama_add_bos_token(SafeLlamaModelHandle model);
  217. /// <summary>
  218. /// Returns -1 if unknown, 1 for true or 0 for false.
  219. /// </summary>
  220. /// <returns></returns>
  221. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  222. public static extern int llama_add_eos_token(SafeLlamaModelHandle model);
  223. /// <summary>
  224. /// codellama infill tokens, Beginning of infill prefix
  225. /// </summary>
  226. /// <returns></returns>
  227. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  228. public static extern int llama_token_prefix(SafeLlamaModelHandle model);
  229. /// <summary>
  230. /// codellama infill tokens, Beginning of infill middle
  231. /// </summary>
  232. /// <returns></returns>
  233. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  234. public static extern int llama_token_middle(SafeLlamaModelHandle model);
  235. /// <summary>
  236. /// codellama infill tokens, Beginning of infill suffix
  237. /// </summary>
  238. /// <returns></returns>
  239. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  240. public static extern int llama_token_suffix(SafeLlamaModelHandle model);
  241. /// <summary>
  242. /// codellama infill tokens, End of infill middle
  243. /// </summary>
  244. /// <returns></returns>
  245. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  246. public static extern int llama_token_eot(SafeLlamaModelHandle model);
  247. /// <summary>
  248. /// Print out timing information for this context
  249. /// </summary>
  250. /// <param name="ctx"></param>
  251. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  252. public static extern void llama_print_timings(SafeLLamaContextHandle ctx);
  253. /// <summary>
  254. /// Reset all collected timing information for this context
  255. /// </summary>
  256. /// <param name="ctx"></param>
  257. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  258. public static extern void llama_reset_timings(SafeLLamaContextHandle ctx);
  259. /// <summary>
  260. /// Print system information
  261. /// </summary>
  262. /// <returns></returns>
  263. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  264. public static extern IntPtr llama_print_system_info();
  265. /// <summary>
  266. /// Convert a single token into text
  267. /// </summary>
  268. /// <param name="model"></param>
  269. /// <param name="llamaToken"></param>
  270. /// <param name="buffer">buffer to write string into</param>
  271. /// <returns>The length written, or if the buffer is too small a negative that indicates the length required</returns>
  272. public static int llama_token_to_piece(SafeLlamaModelHandle model, LLamaToken llamaToken, Span<byte> buffer)
  273. {
  274. unsafe
  275. {
  276. fixed (byte* bufferPtr = buffer)
  277. {
  278. return llama_token_to_piece_native(model, llamaToken, bufferPtr, buffer.Length);
  279. }
  280. }
  281. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "llama_token_to_piece")]
  282. static extern unsafe int llama_token_to_piece_native(SafeLlamaModelHandle model, LLamaToken llamaToken, byte* buffer, int length);
  283. }
  284. /// <summary>
  285. /// Convert text into tokens
  286. /// </summary>
  287. /// <param name="model"></param>
  288. /// <param name="text"></param>
  289. /// <param name="text_len"></param>
  290. /// <param name="tokens"></param>
  291. /// <param name="n_max_tokens"></param>
  292. /// <param name="add_bos"></param>
  293. /// <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>
  294. /// <returns>Returns the number of tokens on success, no more than n_max_tokens.
  295. /// Returns a negative number on failure - the number of tokens that would have been returned
  296. /// </returns>
  297. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  298. 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);
  299. /// <summary>
  300. /// Register a callback to receive llama log messages
  301. /// </summary>
  302. /// <param name="logCallback"></param>
  303. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  304. public static extern void llama_log_set(LLamaLogCallback logCallback);
  305. /// <summary>
  306. /// Clear the KV cache
  307. /// </summary>
  308. /// <param name="ctx"></param>
  309. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  310. public static extern void llama_kv_cache_clear(SafeLLamaContextHandle ctx);
  311. /// <summary>
  312. /// Removes all tokens that belong to the specified sequence and have positions in [p0, p1)
  313. /// </summary>
  314. /// <param name="ctx"></param>
  315. /// <param name="seq"></param>
  316. /// <param name="p0"></param>
  317. /// <param name="p1"></param>
  318. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  319. public static extern void llama_kv_cache_seq_rm(SafeLLamaContextHandle ctx, LLamaSeqId seq, LLamaPos p0, LLamaPos p1);
  320. /// <summary>
  321. /// Copy all tokens that belong to the specified sequence to another sequence
  322. /// Note that this does not allocate extra KV cache memory - it simply assigns the tokens to the new sequence
  323. /// </summary>
  324. /// <param name="ctx"></param>
  325. /// <param name="src"></param>
  326. /// <param name="dest"></param>
  327. /// <param name="p0"></param>
  328. /// <param name="p1"></param>
  329. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  330. public static extern void llama_kv_cache_seq_cp(SafeLLamaContextHandle ctx, LLamaSeqId src, LLamaSeqId dest, LLamaPos p0, LLamaPos p1);
  331. /// <summary>
  332. /// Removes all tokens that do not belong to the specified sequence
  333. /// </summary>
  334. /// <param name="ctx"></param>
  335. /// <param name="seq"></param>
  336. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  337. public static extern void llama_kv_cache_seq_keep(SafeLLamaContextHandle ctx, LLamaSeqId seq);
  338. /// <summary>
  339. /// Adds relative position "delta" to all tokens that belong to the specified sequence and have positions in [p0, p1)
  340. /// If the KV cache is RoPEd, the KV data is updated accordingly
  341. /// </summary>
  342. /// <param name="ctx"></param>
  343. /// <param name="seq"></param>
  344. /// <param name="p0"></param>
  345. /// <param name="p1"></param>
  346. /// <param name="delta"></param>
  347. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  348. public static extern void llama_kv_cache_seq_shift(SafeLLamaContextHandle ctx, LLamaSeqId seq, LLamaPos p0, LLamaPos p1, int delta);
  349. /// <summary>
  350. /// Integer division of the positions by factor of `d > 1`
  351. /// If the KV cache is RoPEd, the KV data is updated accordingly
  352. /// p0 &lt; 0 : [0, p1]
  353. /// p1 &lt; 0 : [p0, inf)
  354. /// </summary>
  355. /// <param name="ctx"></param>
  356. /// <param name="seq"></param>
  357. /// <param name="p0"></param>
  358. /// <param name="p1"></param>
  359. /// <param name="d"></param>
  360. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  361. public static extern void llama_kv_cache_seq_div(SafeLLamaContextHandle ctx, LLamaSeqId seq, LLamaPos p0, LLamaPos p1, int d);
  362. /// <summary>
  363. /// Allocates a batch of tokens on the heap
  364. /// Each token can be assigned up to n_seq_max sequence ids
  365. /// The batch has to be freed with llama_batch_free()
  366. /// If embd != 0, llama_batch.embd will be allocated with size of n_tokens * embd * sizeof(float)
  367. /// Otherwise, llama_batch.token will be allocated to store n_tokens llama_token
  368. /// The rest of the llama_batch members are allocated with size n_tokens
  369. /// All members are left uninitialized
  370. /// </summary>
  371. /// <param name="n_tokens"></param>
  372. /// <param name="embd"></param>
  373. /// <param name="n_seq_max">Each token can be assigned up to n_seq_max sequence ids</param>
  374. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  375. public static extern LLamaNativeBatch llama_batch_init(int n_tokens, int embd, int n_seq_max);
  376. /// <summary>
  377. /// Frees a batch of tokens allocated with llama_batch_init()
  378. /// </summary>
  379. /// <param name="batch"></param>
  380. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  381. public static extern void llama_batch_free(LLamaNativeBatch batch);
  382. /// <summary>
  383. /// </summary>
  384. /// <param name="ctx"></param>
  385. /// <param name="batch"></param>
  386. /// <returns>Positive return values does not mean a fatal error, but rather a warning:<br />
  387. /// - 0: success<br />
  388. /// - 1: could not find a KV slot for the batch (try reducing the size of the batch or increase the context)<br />
  389. /// - &lt; 0: error<br />
  390. /// </returns>
  391. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  392. public static extern int llama_decode(SafeLLamaContextHandle ctx, LLamaNativeBatch batch);
  393. /// <summary>
  394. /// Set the number of threads used for decoding
  395. /// </summary>
  396. /// <param name="ctx"></param>
  397. /// <param name="n_threads">n_threads is the number of threads used for generation (single token)</param>
  398. /// <param name="n_threads_batch">n_threads_batch is the number of threads used for prompt and batch processing (multiple tokens)</param>
  399. /// <returns></returns>
  400. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  401. public static extern void llama_set_n_threads(SafeLLamaContextHandle ctx, uint n_threads, uint n_threads_batch);
  402. }
  403. }