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

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