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

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