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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Text;
  4. using LLama.Exceptions;
  5. namespace LLama.Native
  6. {
  7. using llama_token = Int32;
  8. public unsafe partial class NativeApi
  9. {
  10. public static readonly int LLAMA_MAX_DEVICES = 1;
  11. static NativeApi()
  12. {
  13. try
  14. {
  15. llama_empty_call();
  16. }
  17. catch (DllNotFoundException)
  18. {
  19. throw new RuntimeError("The native library cannot be found. It could be one of the following reasons: \n" +
  20. "1. No LLamaSharp backend was installed. Please search LLamaSharp.Backend and install one of them. \n" +
  21. "2. You are using a device with only CPU but installed cuda backend. Please install cpu backend instead. \n" +
  22. "3. The backend is not compatible with your system cuda environment. Please check and fix it. If the environment is " +
  23. "expected not to be changed, then consider build llama.cpp from source or submit an issue to LLamaSharp.\n" +
  24. "4. One of the dependency of the native library is missed.\n");
  25. }
  26. NativeApi.llama_backend_init(false);
  27. }
  28. private const string libraryName = "libllama";
  29. [DllImport(libraryName, EntryPoint = "llama_mmap_supported", CallingConvention = CallingConvention.Cdecl)]
  30. public static extern bool llama_empty_call();
  31. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  32. public static extern LLamaContextParams llama_context_default_params();
  33. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  34. public static extern LLamaModelQuantizeParams llama_model_quantize_default_params();
  35. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  36. public static extern bool llama_mmap_supported();
  37. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  38. public static extern bool llama_mlock_supported();
  39. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  40. public static extern int llama_eval_export(SafeLLamaContextHandle ctx, string fname);
  41. /// <summary>
  42. /// Various functions for loading a ggml llama model.
  43. /// Allocate (almost) all memory needed for the model.
  44. /// Return NULL on failure
  45. /// </summary>
  46. /// <param name="path_model"></param>
  47. /// <param name="params_"></param>
  48. /// <returns></returns>
  49. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  50. public static extern IntPtr llama_load_model_from_file(string path_model, LLamaContextParams params_);
  51. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  52. public static extern IntPtr llama_new_context_with_model(SafeLlamaModelHandle model, LLamaContextParams params_);
  53. /// <summary>
  54. /// not great API - very likely to change.
  55. /// Initialize the llama + ggml backend
  56. /// Call once at the start of the program
  57. /// </summary>
  58. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  59. public static extern void llama_backend_init(bool numa);
  60. /// <summary>
  61. /// Frees all allocated memory
  62. /// </summary>
  63. /// <param name="ctx"></param>
  64. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  65. public static extern void llama_free(IntPtr ctx);
  66. /// <summary>
  67. /// Frees all allocated memory associated with a model
  68. /// </summary>
  69. /// <param name="model"></param>
  70. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  71. public static extern void llama_free_model(IntPtr model);
  72. /// <summary>
  73. /// Apply a LoRA adapter to a loaded model
  74. /// path_base_model is the path to a higher quality model to use as a base for
  75. /// the layers modified by the adapter. Can be NULL to use the current loaded model.
  76. /// The model needs to be reloaded before applying a new adapter, otherwise the adapter
  77. /// will be applied on top of the previous one
  78. /// </summary>
  79. /// <param name="model_ptr"></param>
  80. /// <param name="path_lora"></param>
  81. /// <param name="path_base_model"></param>
  82. /// <param name="n_threads"></param>
  83. /// <returns>Returns 0 on success</returns>
  84. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  85. public static extern int llama_model_apply_lora_from_file(SafeLlamaModelHandle model_ptr, string path_lora, string? path_base_model, int n_threads);
  86. /// <summary>
  87. /// Returns the number of tokens in the KV cache
  88. /// </summary>
  89. /// <param name="ctx"></param>
  90. /// <returns></returns>
  91. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  92. public static extern int llama_get_kv_cache_token_count(SafeLLamaContextHandle ctx);
  93. /// <summary>
  94. /// Sets the current rng seed.
  95. /// </summary>
  96. /// <param name="ctx"></param>
  97. /// <param name="seed"></param>
  98. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  99. public static extern void llama_set_rng_seed(SafeLLamaContextHandle ctx, int seed);
  100. /// <summary>
  101. /// Returns the maximum size in bytes of the state (rng, logits, embedding
  102. /// and kv_cache) - will often be smaller after compacting tokens
  103. /// </summary>
  104. /// <param name="ctx"></param>
  105. /// <returns></returns>
  106. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  107. public static extern ulong llama_get_state_size(SafeLLamaContextHandle ctx);
  108. /// <summary>
  109. /// Copies the state to the specified destination address.
  110. /// Destination needs to have allocated enough memory.
  111. /// </summary>
  112. /// <param name="ctx"></param>
  113. /// <param name="dest"></param>
  114. /// <returns>the number of bytes copied</returns>
  115. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  116. public static extern ulong llama_copy_state_data(SafeLLamaContextHandle ctx, byte* dest);
  117. /// <summary>
  118. /// Copies the state to the specified destination address.
  119. /// Destination needs to have allocated enough memory (see llama_get_state_size)
  120. /// </summary>
  121. /// <param name="ctx"></param>
  122. /// <param name="dest"></param>
  123. /// <returns>the number of bytes copied</returns>
  124. public static ulong llama_copy_state_data(SafeLLamaContextHandle ctx, byte[] dest)
  125. {
  126. fixed (byte* dstPtr = &dest[0])
  127. {
  128. return llama_copy_state_data(ctx, dstPtr);
  129. }
  130. }
  131. /// <summary>
  132. /// Set the state reading from the specified address
  133. /// </summary>
  134. /// <param name="ctx"></param>
  135. /// <param name="src"></param>
  136. /// <returns>the number of bytes read</returns>
  137. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  138. public static extern ulong llama_set_state_data(SafeLLamaContextHandle ctx, byte* src);
  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. public static ulong llama_set_state_data(SafeLLamaContextHandle ctx, byte[] src)
  146. {
  147. fixed (byte* srcPtr = &src[0])
  148. {
  149. return llama_set_state_data(ctx, srcPtr);
  150. }
  151. }
  152. /// <summary>
  153. /// Load session file
  154. /// </summary>
  155. /// <param name="ctx"></param>
  156. /// <param name="path_session"></param>
  157. /// <param name="tokens_out"></param>
  158. /// <param name="n_token_capacity"></param>
  159. /// <param name="n_token_count_out"></param>
  160. /// <returns></returns>
  161. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  162. 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);
  163. /// <summary>
  164. /// Save session file
  165. /// </summary>
  166. /// <param name="ctx"></param>
  167. /// <param name="path_session"></param>
  168. /// <param name="tokens"></param>
  169. /// <param name="n_token_count"></param>
  170. /// <returns></returns>
  171. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  172. public static extern bool llama_save_session_file(SafeLLamaContextHandle ctx, string path_session, llama_token[] tokens, ulong n_token_count);
  173. /// <summary>
  174. /// Run the llama inference to obtain the logits and probabilities for the next token.
  175. /// tokens + n_tokens is the provided batch of new tokens to process
  176. /// n_past is the number of tokens to use from previous eval calls
  177. /// </summary>
  178. /// <param name="ctx"></param>
  179. /// <param name="tokens"></param>
  180. /// <param name="n_tokens"></param>
  181. /// <param name="n_past"></param>
  182. /// <param name="n_threads"></param>
  183. /// <returns>Returns 0 on success</returns>
  184. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  185. public static extern int llama_eval(SafeLLamaContextHandle ctx, llama_token[] tokens, int n_tokens, int n_past, int n_threads);
  186. [DllImport(libraryName, EntryPoint = "llama_eval", CallingConvention = CallingConvention.Cdecl)]
  187. public static extern int llama_eval_with_pointer(SafeLLamaContextHandle ctx, llama_token* tokens, int n_tokens, int n_past, int n_threads);
  188. /// <summary>
  189. /// Convert the provided text into tokens.
  190. /// The tokens pointer must be large enough to hold the resulting tokens.
  191. /// Returns the number of tokens on success, no more than n_max_tokens
  192. /// Returns a negative number on failure - the number of tokens that would have been returned
  193. /// </summary>
  194. /// <param name="ctx"></param>
  195. /// <param name="text"></param>
  196. /// <param name="encoding"></param>
  197. /// <param name="tokens"></param>
  198. /// <param name="n_max_tokens"></param>
  199. /// <param name="add_bos"></param>
  200. /// <returns></returns>
  201. public static int llama_tokenize(SafeLLamaContextHandle ctx, string text, Encoding encoding, llama_token[] tokens, int n_max_tokens, bool add_bos)
  202. {
  203. var bytes = encoding.GetBytes(text);
  204. sbyte[] data = new sbyte[bytes.Length];
  205. for(int i = 0; i < bytes.Length; i++)
  206. {
  207. data[i] = (sbyte)bytes[i];
  208. //if (bytes[i] < 128)
  209. //{
  210. // data[i] = (sbyte)bytes[i];
  211. //}
  212. //else
  213. //{
  214. // data[i] = (sbyte)(~((sbyte)(~bytes[i] + 1)) + 1);
  215. //}
  216. }
  217. return llama_tokenize_native(ctx, data, tokens, n_max_tokens, add_bos);
  218. }
  219. [DllImport(libraryName, EntryPoint = "llama_tokenize", CallingConvention = CallingConvention.Cdecl)]
  220. public static extern int llama_tokenize_native(SafeLLamaContextHandle ctx, sbyte[] text, llama_token[] tokens, int n_max_tokens, bool add_bos);
  221. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  222. public static extern int llama_n_vocab(SafeLLamaContextHandle ctx);
  223. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  224. public static extern int llama_n_ctx(SafeLLamaContextHandle ctx);
  225. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  226. public static extern int llama_n_embd(SafeLLamaContextHandle ctx);
  227. /// <summary>
  228. /// Token logits obtained from the last call to llama_eval()
  229. /// The logits for the last token are stored in the last row
  230. /// Can be mutated in order to change the probabilities of the next token
  231. /// Rows: n_tokens
  232. /// Cols: n_vocab
  233. /// </summary>
  234. /// <param name="ctx"></param>
  235. /// <returns></returns>
  236. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  237. public static extern float* llama_get_logits(SafeLLamaContextHandle ctx);
  238. /// <summary>
  239. /// Get the embeddings for the input
  240. /// shape: [n_embd] (1-dimensional)
  241. /// </summary>
  242. /// <param name="ctx"></param>
  243. /// <returns></returns>
  244. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  245. public static extern float* llama_get_embeddings(SafeLLamaContextHandle ctx);
  246. /// <summary>
  247. /// Token Id -> String. Uses the vocabulary in the provided context
  248. /// </summary>
  249. /// <param name="ctx"></param>
  250. /// <param name="token"></param>
  251. /// <returns>Pointer to a string.</returns>
  252. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  253. public static extern IntPtr llama_token_to_str(SafeLLamaContextHandle ctx, llama_token token);
  254. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  255. public static extern llama_token llama_token_bos();
  256. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  257. public static extern llama_token llama_token_eos();
  258. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  259. public static extern llama_token llama_token_nl();
  260. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  261. public static extern void llama_print_timings(SafeLLamaContextHandle ctx);
  262. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  263. public static extern void llama_reset_timings(SafeLLamaContextHandle ctx);
  264. /// <summary>
  265. /// Print system information
  266. /// </summary>
  267. /// <returns></returns>
  268. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  269. public static extern IntPtr llama_print_system_info();
  270. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  271. public static extern int llama_n_vocab_from_model(SafeLlamaModelHandle model);
  272. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  273. public static extern int llama_n_ctx_from_model(SafeLlamaModelHandle model);
  274. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  275. public static extern int llama_n_embd_from_model(SafeLlamaModelHandle model);
  276. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  277. public static extern byte* llama_token_to_str_with_model(SafeLlamaModelHandle model, int llamaToken);
  278. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  279. public static extern int llama_tokenize_with_model(SafeLlamaModelHandle model, byte* text, int* tokens, int n_max_tokens, bool add_bos);
  280. }
  281. }