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

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