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

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