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

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