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

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