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

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