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

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