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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. using System;
  2. using System.Buffers;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. using LLama.Common;
  6. using LLama.Exceptions;
  7. #pragma warning disable IDE1006 // Naming Styles
  8. namespace LLama.Native
  9. {
  10. using llama_token = Int32;
  11. public delegate void LLamaLogCallback(ILLamaLogger.LogLevel level, string message);
  12. public unsafe partial class NativeApi
  13. {
  14. static NativeApi()
  15. {
  16. try
  17. {
  18. llama_empty_call();
  19. }
  20. catch (DllNotFoundException)
  21. {
  22. throw new RuntimeError("The native library cannot be found. It could be one of the following reasons: \n" +
  23. "1. No LLamaSharp backend was installed. Please search LLamaSharp.Backend and install one of them. \n" +
  24. "2. You are using a device with only CPU but installed cuda backend. Please install cpu backend instead. \n" +
  25. "3. The backend is not compatible with your system cuda environment. Please check and fix it. If the environment is " +
  26. "expected not to be changed, then consider build llama.cpp from source or submit an issue to LLamaSharp.\n" +
  27. "4. One of the dependency of the native library is missed.\n");
  28. }
  29. NativeApi.llama_backend_init(false);
  30. }
  31. private const string libraryName = "libllama";
  32. /// <summary>
  33. /// A method that does nothing. This is a native method, calling it will force the llama native dependencies to be loaded.
  34. /// </summary>
  35. /// <returns></returns>
  36. [DllImport(libraryName, EntryPoint = "llama_mmap_supported", CallingConvention = CallingConvention.Cdecl)]
  37. public static extern bool llama_empty_call();
  38. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  39. public static extern LLamaContextParams llama_context_default_params();
  40. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  41. public static extern LLamaModelQuantizeParams llama_model_quantize_default_params();
  42. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  43. public static extern bool llama_mmap_supported();
  44. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  45. public static extern bool llama_mlock_supported();
  46. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  47. public static extern int llama_eval_export(SafeLLamaContextHandle ctx, string fname);
  48. /// <summary>
  49. /// Various functions for loading a ggml llama model.
  50. /// Allocate (almost) all memory needed for the model.
  51. /// Return NULL on failure
  52. /// </summary>
  53. /// <param name="path_model"></param>
  54. /// <param name="params"></param>
  55. /// <returns></returns>
  56. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  57. public static extern IntPtr llama_load_model_from_file(string path_model, LLamaContextParams @params);
  58. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  59. public static extern IntPtr llama_new_context_with_model(SafeLlamaModelHandle model, LLamaContextParams @params);
  60. /// <summary>
  61. /// not great API - very likely to change.
  62. /// Initialize the llama + ggml backend
  63. /// Call once at the start of the program
  64. /// </summary>
  65. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  66. public static extern void llama_backend_init(bool numa);
  67. /// <summary>
  68. /// Frees all allocated memory
  69. /// </summary>
  70. /// <param name="ctx"></param>
  71. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  72. public static extern void llama_free(IntPtr ctx);
  73. /// <summary>
  74. /// Frees all allocated memory associated with a model
  75. /// </summary>
  76. /// <param name="model"></param>
  77. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  78. public static extern void llama_free_model(IntPtr model);
  79. /// <summary>
  80. /// Apply a LoRA adapter to a loaded model
  81. /// path_base_model is the path to a higher quality model to use as a base for
  82. /// the layers modified by the adapter. Can be NULL to use the current loaded model.
  83. /// The model needs to be reloaded before applying a new adapter, otherwise the adapter
  84. /// will be applied on top of the previous one
  85. /// </summary>
  86. /// <param name="model_ptr"></param>
  87. /// <param name="path_lora"></param>
  88. /// <param name="path_base_model"></param>
  89. /// <param name="n_threads"></param>
  90. /// <returns>Returns 0 on success</returns>
  91. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  92. public static extern int llama_model_apply_lora_from_file(SafeLlamaModelHandle model_ptr, string path_lora, string? path_base_model, int n_threads);
  93. /// <summary>
  94. /// Returns the number of tokens in the KV cache
  95. /// </summary>
  96. /// <param name="ctx"></param>
  97. /// <returns></returns>
  98. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  99. public static extern int llama_get_kv_cache_token_count(SafeLLamaContextHandle ctx);
  100. /// <summary>
  101. /// Sets the current rng seed.
  102. /// </summary>
  103. /// <param name="ctx"></param>
  104. /// <param name="seed"></param>
  105. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  106. public static extern void llama_set_rng_seed(SafeLLamaContextHandle ctx, int seed);
  107. /// <summary>
  108. /// Returns the maximum size in bytes of the state (rng, logits, embedding
  109. /// and kv_cache) - will often be smaller after compacting tokens
  110. /// </summary>
  111. /// <param name="ctx"></param>
  112. /// <returns></returns>
  113. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  114. public static extern ulong llama_get_state_size(SafeLLamaContextHandle ctx);
  115. /// <summary>
  116. /// Copies the state to the specified destination address.
  117. /// Destination needs to have allocated enough memory.
  118. /// </summary>
  119. /// <param name="ctx"></param>
  120. /// <param name="dest"></param>
  121. /// <returns>the number of bytes copied</returns>
  122. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  123. public static extern ulong llama_copy_state_data(SafeLLamaContextHandle ctx, byte* dest);
  124. /// <summary>
  125. /// Copies the state to the specified destination address.
  126. /// Destination needs to have allocated enough memory (see llama_get_state_size)
  127. /// </summary>
  128. /// <param name="ctx"></param>
  129. /// <param name="dest"></param>
  130. /// <returns>the number of bytes copied</returns>
  131. public static ulong llama_copy_state_data(SafeLLamaContextHandle ctx, byte[] dest)
  132. {
  133. fixed (byte* dstPtr = &dest[0])
  134. {
  135. return llama_copy_state_data(ctx, dstPtr);
  136. }
  137. }
  138. /// <summary>
  139. /// Set the state reading from the specified address
  140. /// </summary>
  141. /// <param name="ctx"></param>
  142. /// <param name="src"></param>
  143. /// <returns>the number of bytes read</returns>
  144. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  145. public static extern ulong llama_set_state_data(SafeLLamaContextHandle ctx, byte* src);
  146. /// <summary>
  147. /// Set the state reading from the specified address
  148. /// </summary>
  149. /// <param name="ctx"></param>
  150. /// <param name="src"></param>
  151. /// <returns>the number of bytes read</returns>
  152. public static ulong llama_set_state_data(SafeLLamaContextHandle ctx, byte[] src)
  153. {
  154. fixed (byte* srcPtr = &src[0])
  155. {
  156. return llama_set_state_data(ctx, srcPtr);
  157. }
  158. }
  159. /// <summary>
  160. /// Load session file
  161. /// </summary>
  162. /// <param name="ctx"></param>
  163. /// <param name="path_session"></param>
  164. /// <param name="tokens_out"></param>
  165. /// <param name="n_token_capacity"></param>
  166. /// <param name="n_token_count_out"></param>
  167. /// <returns></returns>
  168. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  169. public static extern bool llama_load_session_file(SafeLLamaContextHandle ctx, string path_session, llama_token[] tokens_out, ulong n_token_capacity, ulong* n_token_count_out);
  170. /// <summary>
  171. /// Save session file
  172. /// </summary>
  173. /// <param name="ctx"></param>
  174. /// <param name="path_session"></param>
  175. /// <param name="tokens"></param>
  176. /// <param name="n_token_count"></param>
  177. /// <returns></returns>
  178. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  179. public static extern bool llama_save_session_file(SafeLLamaContextHandle ctx, string path_session, llama_token[] tokens, ulong n_token_count);
  180. /// <summary>
  181. /// Run the llama inference to obtain the logits and probabilities for the next token.
  182. /// tokens + n_tokens is the provided batch of new tokens to process
  183. /// n_past is the number of tokens to use from previous eval calls
  184. /// </summary>
  185. /// <param name="ctx"></param>
  186. /// <param name="tokens"></param>
  187. /// <param name="n_tokens"></param>
  188. /// <param name="n_past"></param>
  189. /// <param name="n_threads"></param>
  190. /// <returns>Returns 0 on success</returns>
  191. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  192. public static extern int llama_eval(SafeLLamaContextHandle ctx, llama_token[] tokens, int n_tokens, int n_past, int n_threads);
  193. /// <summary>
  194. /// Run the llama inference to obtain the logits and probabilities for the next token.
  195. /// tokens + n_tokens is the provided batch of new tokens to process
  196. /// n_past is the number of tokens to use from previous eval calls
  197. /// </summary>
  198. /// <param name="ctx"></param>
  199. /// <param name="tokens"></param>
  200. /// <param name="n_tokens"></param>
  201. /// <param name="n_past"></param>
  202. /// <param name="n_threads"></param>
  203. /// <returns>Returns 0 on success</returns>
  204. [DllImport(libraryName, EntryPoint = "llama_eval", CallingConvention = CallingConvention.Cdecl)]
  205. public static extern int llama_eval_with_pointer(SafeLLamaContextHandle ctx, llama_token* tokens, int n_tokens, int n_past, int n_threads);
  206. /// <summary>
  207. /// Convert the provided text into tokens.
  208. /// </summary>
  209. /// <param name="ctx"></param>
  210. /// <param name="text"></param>
  211. /// <param name="encoding"></param>
  212. /// <param name="tokens"></param>
  213. /// <param name="n_max_tokens"></param>
  214. /// <param name="add_bos"></param>
  215. /// <returns>Returns the number of tokens on success, no more than n_max_tokens.
  216. /// Returns a negative number on failure - the number of tokens that would have been returned
  217. /// </returns>
  218. public static int llama_tokenize(SafeLLamaContextHandle ctx, string text, Encoding encoding, llama_token[] tokens, int n_max_tokens, bool add_bos)
  219. {
  220. // Calculate number of bytes in text and borrow an array that large (+1 for nul byte)
  221. var byteCount = encoding.GetByteCount(text);
  222. var array = ArrayPool<byte>.Shared.Rent(byteCount + 1);
  223. try
  224. {
  225. // Convert to bytes
  226. fixed (char* textPtr = text)
  227. fixed (byte* arrayPtr = array)
  228. {
  229. encoding.GetBytes(textPtr, text.Length, arrayPtr, array.Length);
  230. }
  231. // Add a zero byte to the end to terminate the string
  232. array[byteCount] = 0;
  233. // Do the actual tokenization
  234. fixed (byte* arrayPtr = array)
  235. fixed (llama_token* tokensPtr = tokens)
  236. return llama_tokenize_native(ctx, arrayPtr, tokensPtr, n_max_tokens, add_bos);
  237. }
  238. finally
  239. {
  240. ArrayPool<byte>.Shared.Return(array);
  241. }
  242. }
  243. /// <summary>
  244. /// Convert the provided text into tokens.
  245. /// </summary>
  246. /// <param name="ctx"></param>
  247. /// <param name="text"></param>
  248. /// <param name="tokens"></param>
  249. /// <param name="n_max_tokens"></param>
  250. /// <param name="add_bos"></param>
  251. /// <returns>Returns the number of tokens on success, no more than n_max_tokens.
  252. /// Returns a negative number on failure - the number of tokens that would have been returned
  253. /// </returns>
  254. [DllImport(libraryName, EntryPoint = "llama_tokenize", CallingConvention = CallingConvention.Cdecl)]
  255. public static extern int llama_tokenize_native(SafeLLamaContextHandle ctx, byte* text, llama_token* tokens, int n_max_tokens, bool add_bos);
  256. /// <summary>
  257. /// Get the number of tokens in the model vocabulary for this context
  258. /// </summary>
  259. /// <param name="ctx"></param>
  260. /// <returns></returns>
  261. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  262. public static extern int llama_n_vocab(SafeLLamaContextHandle ctx);
  263. /// <summary>
  264. /// Get the size of the context window for the model for this context
  265. /// </summary>
  266. /// <param name="ctx"></param>
  267. /// <returns></returns>
  268. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  269. public static extern int llama_n_ctx(SafeLLamaContextHandle ctx);
  270. /// <summary>
  271. /// Get the dimension of embedding vectors from the model for this context
  272. /// </summary>
  273. /// <param name="ctx"></param>
  274. /// <returns></returns>
  275. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  276. public static extern int llama_n_embd(SafeLLamaContextHandle ctx);
  277. /// <summary>
  278. /// Token logits obtained from the last call to llama_eval()
  279. /// The logits for the last token are stored in the last row
  280. /// Can be mutated in order to change the probabilities of the next token.<br />
  281. /// Rows: n_tokens<br />
  282. /// Cols: n_vocab
  283. /// </summary>
  284. /// <param name="ctx"></param>
  285. /// <returns></returns>
  286. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  287. public static extern float* llama_get_logits(SafeLLamaContextHandle ctx);
  288. /// <summary>
  289. /// Get the embeddings for the input
  290. /// shape: [n_embd] (1-dimensional)
  291. /// </summary>
  292. /// <param name="ctx"></param>
  293. /// <returns></returns>
  294. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  295. public static extern float* llama_get_embeddings(SafeLLamaContextHandle ctx);
  296. /// <summary>
  297. /// Token Id -> String. Uses the vocabulary in the provided context
  298. /// </summary>
  299. /// <param name="ctx"></param>
  300. /// <param name="token"></param>
  301. /// <returns>Pointer to a string.</returns>
  302. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  303. public static extern IntPtr llama_token_to_str(SafeLLamaContextHandle ctx, llama_token token);
  304. /// <summary>
  305. /// Get the "Beginning of sentence" token
  306. /// </summary>
  307. /// <returns></returns>
  308. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  309. public static extern llama_token llama_token_bos(SafeLLamaContextHandle ctx);
  310. /// <summary>
  311. /// Get the "End of sentence" token
  312. /// </summary>
  313. /// <returns></returns>
  314. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  315. public static extern llama_token llama_token_eos(SafeLLamaContextHandle ctx);
  316. /// <summary>
  317. /// Get the "new line" token
  318. /// </summary>
  319. /// <returns></returns>
  320. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  321. public static extern llama_token llama_token_nl(SafeLLamaContextHandle ctx);
  322. /// <summary>
  323. /// Print out timing information for this context
  324. /// </summary>
  325. /// <param name="ctx"></param>
  326. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  327. public static extern void llama_print_timings(SafeLLamaContextHandle ctx);
  328. /// <summary>
  329. /// Reset all collected timing information for this context
  330. /// </summary>
  331. /// <param name="ctx"></param>
  332. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  333. public static extern void llama_reset_timings(SafeLLamaContextHandle ctx);
  334. /// <summary>
  335. /// Print system information
  336. /// </summary>
  337. /// <returns></returns>
  338. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  339. public static extern IntPtr llama_print_system_info();
  340. /// <summary>
  341. /// Get the number of tokens in the model vocabulary
  342. /// </summary>
  343. /// <param name="model"></param>
  344. /// <returns></returns>
  345. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  346. public static extern int llama_model_n_vocab(SafeLlamaModelHandle model);
  347. /// <summary>
  348. /// Get the size of the context window for the model
  349. /// </summary>
  350. /// <param name="model"></param>
  351. /// <returns></returns>
  352. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  353. public static extern int llama_model_n_ctx(SafeLlamaModelHandle model);
  354. /// <summary>
  355. /// Get the dimension of embedding vectors from this model
  356. /// </summary>
  357. /// <param name="model"></param>
  358. /// <returns></returns>
  359. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  360. public static extern int llama_model_n_embd(SafeLlamaModelHandle model);
  361. /// <summary>
  362. /// Convert a single token into text
  363. /// </summary>
  364. /// <param name="model"></param>
  365. /// <param name="llamaToken"></param>
  366. /// <param name="buffer">buffer to write string into</param>
  367. /// <param name="length">size of the buffer</param>
  368. /// <returns>The length writte, or if the buffer is too small a negative that indicates the length required</returns>
  369. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  370. public static extern int llama_token_to_piece_with_model(SafeLlamaModelHandle model, int llamaToken, byte* buffer, int length);
  371. /// <summary>
  372. /// Convert text into tokens
  373. /// </summary>
  374. /// <param name="model"></param>
  375. /// <param name="text"></param>
  376. /// <param name="tokens"></param>
  377. /// <param name="n_max_tokens"></param>
  378. /// <param name="add_bos"></param>
  379. /// <returns>Returns the number of tokens on success, no more than n_max_tokens.
  380. /// Returns a negative number on failure - the number of tokens that would have been returned
  381. /// </returns>
  382. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  383. public static extern int llama_tokenize_with_model(SafeLlamaModelHandle model, byte* text, int* tokens, int n_max_tokens, bool add_bos);
  384. /// <summary>
  385. /// Register a callback to receive llama log messages
  386. /// </summary>
  387. /// <param name="logCallback"></param>
  388. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  389. public static extern void llama_log_set(LLamaLogCallback logCallback);
  390. }
  391. }