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

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