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

2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. using System;
  2. using System.Buffers;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Text.Json;
  8. using LLama.Exceptions;
  9. #pragma warning disable IDE1006 // Naming Styles
  10. namespace LLama.Native
  11. {
  12. using llama_token = Int32;
  13. /// <summary>
  14. /// Callback from llama.cpp with log messages
  15. /// </summary>
  16. /// <param name="level"></param>
  17. /// <param name="message"></param>
  18. public delegate void LLamaLogCallback(LLamaLogLevel level, string message);
  19. /// <summary>
  20. /// Direct translation of the llama.cpp API
  21. /// </summary>
  22. public unsafe partial class NativeApi
  23. {
  24. static NativeApi()
  25. {
  26. // Try to load a preferred library, based on CPU feature detection
  27. TryLoadLibrary();
  28. try
  29. {
  30. llama_empty_call();
  31. }
  32. catch (DllNotFoundException)
  33. {
  34. throw new RuntimeError("The native library cannot be found. It could be one of the following reasons: \n" +
  35. "1. No LLamaSharp backend was installed. Please search LLamaSharp.Backend and install one of them. \n" +
  36. "2. You are using a device with only CPU but installed cuda backend. Please install cpu backend instead. \n" +
  37. "3. The backend is not compatible with your system cuda environment. Please check and fix it. If the environment is " +
  38. "expected not to be changed, then consider build llama.cpp from source or submit an issue to LLamaSharp.\n" +
  39. "4. One of the dependency of the native library is missed.\n");
  40. }
  41. llama_backend_init(false);
  42. }
  43. private static int GetCudaMajorVersion()
  44. {
  45. string? cudaPath;
  46. string version = "";
  47. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  48. {
  49. cudaPath = Environment.GetEnvironmentVariable("CUDA_PATH");
  50. if(cudaPath is null)
  51. {
  52. return -1;
  53. }
  54. version = GetCudaVersionFromPath(cudaPath);
  55. }
  56. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  57. {
  58. // Try the default first
  59. cudaPath = "/usr/local/bin/cuda";
  60. version = GetCudaVersionFromPath(cudaPath);
  61. if (string.IsNullOrEmpty(version))
  62. {
  63. cudaPath = Environment.GetEnvironmentVariable("LD_LIBRARY_PATH");
  64. if(cudaPath is null)
  65. {
  66. return -1;
  67. }
  68. foreach(var path in cudaPath.Split(':'))
  69. {
  70. version = GetCudaVersionFromPath(Path.Combine(path, ".."));
  71. if (string.IsNullOrEmpty(version))
  72. {
  73. break;
  74. }
  75. }
  76. }
  77. }
  78. if (string.IsNullOrEmpty(version))
  79. {
  80. return -1;
  81. }
  82. else
  83. {
  84. version = version.Split('.')[0];
  85. bool success = int.TryParse(version, out var majorVersion);
  86. if (success)
  87. {
  88. return majorVersion;
  89. }
  90. else
  91. {
  92. return -1;
  93. }
  94. }
  95. }
  96. private static string GetCudaVersionFromPath(string cudaPath)
  97. {
  98. try
  99. {
  100. string json = File.ReadAllText(Path.Combine(cudaPath, cudaVersionFile));
  101. using (JsonDocument document = JsonDocument.Parse(json))
  102. {
  103. JsonElement root = document.RootElement;
  104. JsonElement cublasNode = root.GetProperty("libcublas");
  105. JsonElement versionNode = cublasNode.GetProperty("version");
  106. if (versionNode.ValueKind == JsonValueKind.Undefined)
  107. {
  108. return string.Empty;
  109. }
  110. return versionNode.GetString();
  111. }
  112. }
  113. catch (Exception)
  114. {
  115. return string.Empty;
  116. }
  117. }
  118. #if NET6_0_OR_GREATER
  119. private static string GetAvxLibraryPath(NativeLibraryConfig.AvxLevel avxLevel, string prefix, string suffix)
  120. {
  121. var avxStr = NativeLibraryConfig.AvxLevelToString(avxLevel);
  122. if (!string.IsNullOrEmpty(avxStr))
  123. {
  124. avxStr += "/";
  125. }
  126. return $"{prefix}{avxStr}{libraryName}{suffix}";
  127. }
  128. private static List<string> GetLibraryTryOrder(NativeLibraryConfig.Description configuration)
  129. {
  130. OSPlatform platform;
  131. string prefix, suffix;
  132. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  133. {
  134. platform = OSPlatform.Windows;
  135. prefix = "runtimes/win-x64/native/";
  136. suffix = ".dll";
  137. }
  138. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  139. {
  140. platform = OSPlatform.Linux;
  141. prefix = "runtimes/linux-x64/native/";
  142. suffix = ".so";
  143. }
  144. else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  145. {
  146. platform = OSPlatform.OSX;
  147. suffix = ".dylib";
  148. if (System.Runtime.Intrinsics.Arm.ArmBase.Arm64.IsSupported)
  149. {
  150. prefix = "runtimes/osx-arm64/native/";
  151. }
  152. else
  153. {
  154. prefix = "runtimes/osx-x64/native/";
  155. }
  156. }
  157. else
  158. {
  159. throw new RuntimeError($"Your system plarform is not supported, please open an issue in LLamaSharp.");
  160. }
  161. List<string> result = new();
  162. if (configuration.UseCuda && (platform == OSPlatform.Windows || platform == OSPlatform.Linux)) // no cuda on macos
  163. {
  164. int cudaVersion = GetCudaMajorVersion();
  165. // TODO: load cuda library with avx
  166. if (cudaVersion == -1 && !configuration.AllowFallback)
  167. {
  168. // if check skipped, we just try to load cuda libraries one by one.
  169. if (configuration.SkipCheck)
  170. {
  171. result.Add($"{prefix}cuda12/{libraryName}{suffix}");
  172. result.Add($"{prefix}cuda11/{libraryName}{suffix}");
  173. }
  174. else
  175. {
  176. throw new RuntimeError("Configured to load a cuda library but no cuda detected on your device.");
  177. }
  178. }
  179. else if (cudaVersion == 11)
  180. {
  181. result.Add($"{prefix}cuda11/{libraryName}{suffix}");
  182. }
  183. else if (cudaVersion == 12)
  184. {
  185. result.Add($"{prefix}cuda12/{libraryName}{suffix}");
  186. }
  187. else if (cudaVersion > 0)
  188. {
  189. throw new RuntimeError($"Cuda version {cudaVersion} hasn't been supported by LLamaSharp, please open an issue for it.");
  190. }
  191. // otherwise no cuda detected but allow fallback
  192. }
  193. // use cpu (or mac possibly with metal)
  194. if (!configuration.AllowFallback && platform != OSPlatform.OSX)
  195. {
  196. result.Add(GetAvxLibraryPath(configuration.AvxLevel, prefix, suffix));
  197. }
  198. else if(platform != OSPlatform.OSX) // in macos there's absolutely no avx
  199. {
  200. #if NET8_0_OR_GREATER
  201. if (configuration.AvxLevel == NativeLibraryConfig.AvxLevel.Avx512)
  202. {
  203. result.Add(GetAvxLibraryPath(NativeLibraryConfig.AvxLevel.Avx512, prefix, suffix)));
  204. result.Add(GetAvxLibraryPath(NativeLibraryConfig.AvxLevel.Avx2, prefix, suffix)));
  205. result.Add(GetAvxLibraryPath(NativeLibraryConfig.AvxLevel.Avx, prefix, suffix)));
  206. }
  207. else
  208. #endif
  209. if (configuration.AvxLevel == NativeLibraryConfig.AvxLevel.Avx2)
  210. {
  211. result.Add(GetAvxLibraryPath(NativeLibraryConfig.AvxLevel.Avx2, prefix, suffix));
  212. result.Add(GetAvxLibraryPath(NativeLibraryConfig.AvxLevel.Avx, prefix, suffix));
  213. }
  214. else if (configuration.AvxLevel == NativeLibraryConfig.AvxLevel.Avx)
  215. {
  216. result.Add(GetAvxLibraryPath(NativeLibraryConfig.AvxLevel.Avx, prefix, suffix));
  217. }
  218. result.Add(GetAvxLibraryPath(NativeLibraryConfig.AvxLevel.None, prefix, suffix));
  219. }
  220. if(platform == OSPlatform.OSX)
  221. {
  222. result.Add($"{prefix}{libraryName}{suffix}");
  223. }
  224. return result;
  225. }
  226. #endif
  227. /// <summary>
  228. /// Try to load libllama, using CPU feature detection to try and load a more specialised DLL if possible
  229. /// </summary>
  230. /// <returns>The library handle to unload later, or IntPtr.Zero if no library was loaded</returns>
  231. private static IntPtr TryLoadLibrary()
  232. {
  233. #if NET6_0_OR_GREATER
  234. var configuration = NativeLibraryConfig.GetInstance().Desc;
  235. if (!string.IsNullOrEmpty(configuration.Path))
  236. {
  237. // When loading the user specified library, there's no fallback.
  238. var result = TryLoad(configuration.Path, true);
  239. if (result is null || result == IntPtr.Zero)
  240. {
  241. throw new RuntimeError($"Failed to load the native library [{configuration.Path}] you specified.");
  242. }
  243. return result ?? IntPtr.Zero;
  244. }
  245. var libraryTryLoadOrder = GetLibraryTryOrder(configuration);
  246. foreach(var libraryPath in libraryTryLoadOrder)
  247. {
  248. var result = TryLoad(libraryPath, true);
  249. if(result is not null && result != IntPtr.Zero)
  250. {
  251. Console.ForegroundColor = ConsoleColor.Red;
  252. Console.WriteLine($"[Native Library] {libraryPath} is loaded.");
  253. Console.ResetColor();
  254. return result ?? IntPtr.Zero;
  255. }
  256. else
  257. {
  258. Console.WriteLine($"Tried to load {libraryPath}");
  259. }
  260. }
  261. if (!configuration.AllowFallback)
  262. {
  263. throw new RuntimeError("Failed to load the library that match your rule, please" +
  264. " 1) check your rule." +
  265. " 2) try to allow fallback." +
  266. " 3) or open an issue if it's expected to be successful.");
  267. }
  268. #endif
  269. return IntPtr.Zero;
  270. #if NET6_0_OR_GREATER
  271. // Try to load a DLL from the path if supported. Returns null if nothing is loaded.
  272. static IntPtr? TryLoad(string path, bool supported = true)
  273. {
  274. if (!supported)
  275. return null;
  276. if (NativeLibrary.TryLoad(path, out var handle))
  277. return handle;
  278. return null;
  279. }
  280. #endif
  281. }
  282. private const string libraryName = "libllama";
  283. private const string cudaVersionFile = "version.json";
  284. /// <summary>
  285. /// A method that does nothing. This is a native method, calling it will force the llama native dependencies to be loaded.
  286. /// </summary>
  287. /// <returns></returns>
  288. [DllImport(libraryName, EntryPoint = "llama_mmap_supported", CallingConvention = CallingConvention.Cdecl)]
  289. public static extern bool llama_empty_call();
  290. /// <summary>
  291. /// Get the maximum number of devices supported by llama.cpp
  292. /// </summary>
  293. /// <returns></returns>
  294. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  295. public static extern int llama_max_devices();
  296. /// <summary>
  297. /// Create a LLamaModelParams with default values
  298. /// </summary>
  299. /// <returns></returns>
  300. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  301. public static extern LLamaModelParams llama_model_default_params();
  302. /// <summary>
  303. /// Create a LLamaContextParams with default values
  304. /// </summary>
  305. /// <returns></returns>
  306. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  307. public static extern LLamaContextParams llama_context_default_params();
  308. /// <summary>
  309. /// Create a LLamaModelQuantizeParams with default values
  310. /// </summary>
  311. /// <returns></returns>
  312. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  313. public static extern LLamaModelQuantizeParams llama_model_quantize_default_params();
  314. /// <summary>
  315. /// Check if memory mapping is supported
  316. /// </summary>
  317. /// <returns></returns>
  318. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  319. public static extern bool llama_mmap_supported();
  320. /// <summary>
  321. /// Check if memory lockingis supported
  322. /// </summary>
  323. /// <returns></returns>
  324. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  325. public static extern bool llama_mlock_supported();
  326. /// <summary>
  327. /// Various functions for loading a ggml llama model.
  328. /// Allocate (almost) all memory needed for the model.
  329. /// Return NULL on failure
  330. /// </summary>
  331. /// <param name="path_model"></param>
  332. /// <param name="params"></param>
  333. /// <returns></returns>
  334. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  335. public static extern IntPtr llama_load_model_from_file(string path_model, LLamaModelParams @params);
  336. /// <summary>
  337. /// Create a new llama_context with the given model.
  338. /// Return value should always be wrapped in SafeLLamaContextHandle!
  339. /// </summary>
  340. /// <param name="model"></param>
  341. /// <param name="params"></param>
  342. /// <returns></returns>
  343. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  344. public static extern IntPtr llama_new_context_with_model(SafeLlamaModelHandle model, LLamaContextParams @params);
  345. /// <summary>
  346. /// not great API - very likely to change.
  347. /// Initialize the llama + ggml backend
  348. /// Call once at the start of the program
  349. /// </summary>
  350. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  351. public static extern void llama_backend_init(bool numa);
  352. /// <summary>
  353. /// Frees all allocated memory in the given llama_context
  354. /// </summary>
  355. /// <param name="ctx"></param>
  356. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  357. public static extern void llama_free(IntPtr ctx);
  358. /// <summary>
  359. /// Frees all allocated memory associated with a model
  360. /// </summary>
  361. /// <param name="model"></param>
  362. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  363. public static extern void llama_free_model(IntPtr model);
  364. /// <summary>
  365. /// Apply a LoRA adapter to a loaded model
  366. /// path_base_model is the path to a higher quality model to use as a base for
  367. /// the layers modified by the adapter. Can be NULL to use the current loaded model.
  368. /// The model needs to be reloaded before applying a new adapter, otherwise the adapter
  369. /// will be applied on top of the previous one
  370. /// </summary>
  371. /// <param name="model_ptr"></param>
  372. /// <param name="path_lora"></param>
  373. /// <param name="scale"></param>
  374. /// <param name="path_base_model"></param>
  375. /// <param name="n_threads"></param>
  376. /// <returns>Returns 0 on success</returns>
  377. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  378. 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);
  379. /// <summary>
  380. /// Sets the current rng seed.
  381. /// </summary>
  382. /// <param name="ctx"></param>
  383. /// <param name="seed"></param>
  384. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  385. public static extern void llama_set_rng_seed(SafeLLamaContextHandle ctx, uint seed);
  386. /// <summary>
  387. /// Returns the maximum size in bytes of the state (rng, logits, embedding
  388. /// and kv_cache) - will often be smaller after compacting tokens
  389. /// </summary>
  390. /// <param name="ctx"></param>
  391. /// <returns></returns>
  392. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  393. public static extern ulong llama_get_state_size(SafeLLamaContextHandle ctx);
  394. /// <summary>
  395. /// Copies the state to the specified destination address.
  396. /// Destination needs to have allocated enough memory.
  397. /// </summary>
  398. /// <param name="ctx"></param>
  399. /// <param name="dest"></param>
  400. /// <returns>the number of bytes copied</returns>
  401. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  402. public static extern ulong llama_copy_state_data(SafeLLamaContextHandle ctx, byte* dest);
  403. /// <summary>
  404. /// Set the state reading from the specified address
  405. /// </summary>
  406. /// <param name="ctx"></param>
  407. /// <param name="src"></param>
  408. /// <returns>the number of bytes read</returns>
  409. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  410. public static extern ulong llama_set_state_data(SafeLLamaContextHandle ctx, byte* src);
  411. /// <summary>
  412. /// Load session file
  413. /// </summary>
  414. /// <param name="ctx"></param>
  415. /// <param name="path_session"></param>
  416. /// <param name="tokens_out"></param>
  417. /// <param name="n_token_capacity"></param>
  418. /// <param name="n_token_count_out"></param>
  419. /// <returns></returns>
  420. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  421. 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);
  422. /// <summary>
  423. /// Save session file
  424. /// </summary>
  425. /// <param name="ctx"></param>
  426. /// <param name="path_session"></param>
  427. /// <param name="tokens"></param>
  428. /// <param name="n_token_count"></param>
  429. /// <returns></returns>
  430. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  431. public static extern bool llama_save_session_file(SafeLLamaContextHandle ctx, string path_session, llama_token[] tokens, ulong n_token_count);
  432. /// <summary>
  433. /// Run the llama inference to obtain the logits and probabilities for the next token.
  434. /// tokens + n_tokens is the provided batch of new tokens to process
  435. /// n_past is the number of tokens to use from previous eval calls
  436. /// </summary>
  437. /// <param name="ctx"></param>
  438. /// <param name="tokens"></param>
  439. /// <param name="n_tokens"></param>
  440. /// <param name="n_past"></param>
  441. /// <returns>Returns 0 on success</returns>
  442. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  443. [Obsolete("use llama_decode() instead")]
  444. public static extern int llama_eval(SafeLLamaContextHandle ctx, llama_token* tokens, int n_tokens, int n_past);
  445. /// <summary>
  446. /// Convert the provided text into tokens.
  447. /// </summary>
  448. /// <param name="ctx"></param>
  449. /// <param name="text"></param>
  450. /// <param name="encoding"></param>
  451. /// <param name="tokens"></param>
  452. /// <param name="n_max_tokens"></param>
  453. /// <param name="add_bos"></param>
  454. /// <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>
  455. /// <returns>Returns the number of tokens on success, no more than n_max_tokens.
  456. /// Returns a negative number on failure - the number of tokens that would have been returned
  457. /// </returns>
  458. public static int llama_tokenize(SafeLLamaContextHandle ctx, string text, Encoding encoding, llama_token[] tokens, int n_max_tokens, bool add_bos, bool special)
  459. {
  460. // Calculate number of bytes in text and borrow an array that large (+1 for nul byte)
  461. var byteCount = encoding.GetByteCount(text);
  462. var array = ArrayPool<byte>.Shared.Rent(byteCount + 1);
  463. try
  464. {
  465. // Convert to bytes
  466. fixed (char* textPtr = text)
  467. fixed (byte* arrayPtr = array)
  468. {
  469. encoding.GetBytes(textPtr, text.Length, arrayPtr, array.Length);
  470. }
  471. // Add a zero byte to the end to terminate the string
  472. array[byteCount] = 0;
  473. // Do the actual tokenization
  474. fixed (byte* arrayPtr = array)
  475. fixed (llama_token* tokensPtr = tokens)
  476. return llama_tokenize(ctx.ModelHandle, arrayPtr, byteCount, tokensPtr, n_max_tokens, add_bos, special);
  477. }
  478. finally
  479. {
  480. ArrayPool<byte>.Shared.Return(array);
  481. }
  482. }
  483. /// <summary>
  484. /// Get the size of the context window for the model for this context
  485. /// </summary>
  486. /// <param name="ctx"></param>
  487. /// <returns></returns>
  488. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  489. public static extern int llama_n_ctx(SafeLLamaContextHandle ctx);
  490. /// <summary>
  491. /// Token logits obtained from the last call to llama_eval()
  492. /// The logits for the last token are stored in the last row
  493. /// Can be mutated in order to change the probabilities of the next token.<br />
  494. /// Rows: n_tokens<br />
  495. /// Cols: n_vocab
  496. /// </summary>
  497. /// <param name="ctx"></param>
  498. /// <returns></returns>
  499. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  500. public static extern float* llama_get_logits(SafeLLamaContextHandle ctx);
  501. /// <summary>
  502. /// Logits for the ith token. Equivalent to: llama_get_logits(ctx) + i*n_vocab
  503. /// </summary>
  504. /// <param name="ctx"></param>
  505. /// <param name="i"></param>
  506. /// <returns></returns>
  507. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  508. public static extern float* llama_get_logits_ith(SafeLLamaContextHandle ctx, int i);
  509. /// <summary>
  510. /// Get the embeddings for the input
  511. /// shape: [n_embd] (1-dimensional)
  512. /// </summary>
  513. /// <param name="ctx"></param>
  514. /// <returns></returns>
  515. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  516. public static extern float* llama_get_embeddings(SafeLLamaContextHandle ctx);
  517. /// <summary>
  518. /// Get the "Beginning of sentence" token
  519. /// </summary>
  520. /// <returns></returns>
  521. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  522. public static extern llama_token llama_token_bos(SafeLlamaModelHandle model);
  523. /// <summary>
  524. /// Get the "End of sentence" token
  525. /// </summary>
  526. /// <returns></returns>
  527. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  528. public static extern llama_token llama_token_eos(SafeLlamaModelHandle model);
  529. /// <summary>
  530. /// Get the "new line" token
  531. /// </summary>
  532. /// <returns></returns>
  533. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  534. public static extern llama_token llama_token_nl(SafeLlamaModelHandle model);
  535. /// <summary>
  536. /// Print out timing information for this context
  537. /// </summary>
  538. /// <param name="ctx"></param>
  539. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  540. public static extern void llama_print_timings(SafeLLamaContextHandle ctx);
  541. /// <summary>
  542. /// Reset all collected timing information for this context
  543. /// </summary>
  544. /// <param name="ctx"></param>
  545. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  546. public static extern void llama_reset_timings(SafeLLamaContextHandle ctx);
  547. /// <summary>
  548. /// Print system information
  549. /// </summary>
  550. /// <returns></returns>
  551. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  552. public static extern IntPtr llama_print_system_info();
  553. /// <summary>
  554. /// Get the number of tokens in the model vocabulary
  555. /// </summary>
  556. /// <param name="model"></param>
  557. /// <returns></returns>
  558. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  559. public static extern int llama_n_vocab(SafeLlamaModelHandle model);
  560. /// <summary>
  561. /// Get the size of the context window for the model
  562. /// </summary>
  563. /// <param name="model"></param>
  564. /// <returns></returns>
  565. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  566. public static extern int llama_n_ctx_train(SafeLlamaModelHandle model);
  567. /// <summary>
  568. /// Get the dimension of embedding vectors from this model
  569. /// </summary>
  570. /// <param name="model"></param>
  571. /// <returns></returns>
  572. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  573. public static extern int llama_n_embd(SafeLlamaModelHandle model);
  574. /// <summary>
  575. /// Get the size of the model in bytes
  576. /// </summary>
  577. /// <param name="model"></param>
  578. /// <returns></returns>
  579. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  580. public static extern ulong llama_model_size(SafeLlamaModelHandle model);
  581. /// <summary>
  582. /// Get the number of parameters in this model
  583. /// </summary>
  584. /// <param name="model"></param>
  585. /// <returns></returns>
  586. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  587. public static extern ulong llama_model_n_params(SafeLlamaModelHandle model);
  588. /// <summary>
  589. /// Convert a single token into text
  590. /// </summary>
  591. /// <param name="model"></param>
  592. /// <param name="llamaToken"></param>
  593. /// <param name="buffer">buffer to write string into</param>
  594. /// <param name="length">size of the buffer</param>
  595. /// <returns>The length writte, or if the buffer is too small a negative that indicates the length required</returns>
  596. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  597. public static extern int llama_token_to_piece(SafeLlamaModelHandle model, int llamaToken, byte* buffer, int length);
  598. /// <summary>
  599. /// Convert text into tokens
  600. /// </summary>
  601. /// <param name="model"></param>
  602. /// <param name="text"></param>
  603. /// <param name="text_len"></param>
  604. /// <param name="tokens"></param>
  605. /// <param name="n_max_tokens"></param>
  606. /// <param name="add_bos"></param>
  607. /// <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>
  608. /// <returns>Returns the number of tokens on success, no more than n_max_tokens.
  609. /// Returns a negative number on failure - the number of tokens that would have been returned
  610. /// </returns>
  611. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  612. public static extern int llama_tokenize(SafeLlamaModelHandle model, byte* text, int text_len, int* tokens, int n_max_tokens, bool add_bos, bool special);
  613. /// <summary>
  614. /// Register a callback to receive llama log messages
  615. /// </summary>
  616. /// <param name="logCallback"></param>
  617. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  618. public static extern void llama_log_set(LLamaLogCallback logCallback);
  619. /// <summary>
  620. /// Remove all tokens data of cells in [c0, c1)
  621. /// </summary>
  622. /// <param name="ctx"></param>
  623. /// <param name="c0"></param>
  624. /// <param name="c1"></param>
  625. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  626. public static extern void llama_kv_cache_tokens_rm(SafeLLamaContextHandle ctx, int c0, int c1);
  627. /// <summary>
  628. /// Removes all tokens that belong to the specified sequence and have positions in [p0, p1)
  629. /// </summary>
  630. /// <param name="ctx"></param>
  631. /// <param name="seq"></param>
  632. /// <param name="p0"></param>
  633. /// <param name="p1"></param>
  634. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  635. public static extern void llama_kv_cache_seq_rm(SafeLLamaContextHandle ctx, LLamaSeqId seq, LLamaPos p0, LLamaPos p1);
  636. /// <summary>
  637. /// Copy all tokens that belong to the specified sequence to another sequence
  638. /// Note that this does not allocate extra KV cache memory - it simply assigns the tokens to the new sequence
  639. /// </summary>
  640. /// <param name="ctx"></param>
  641. /// <param name="src"></param>
  642. /// <param name="dest"></param>
  643. /// <param name="p0"></param>
  644. /// <param name="p1"></param>
  645. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  646. public static extern void llama_kv_cache_seq_cp(SafeLLamaContextHandle ctx, LLamaSeqId src, LLamaSeqId dest, LLamaPos p0, LLamaPos p1);
  647. /// <summary>
  648. /// Removes all tokens that do not belong to the specified sequence
  649. /// </summary>
  650. /// <param name="ctx"></param>
  651. /// <param name="seq"></param>
  652. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  653. public static extern void llama_kv_cache_seq_keep(SafeLLamaContextHandle ctx, LLamaSeqId seq);
  654. /// <summary>
  655. /// Adds relative position "delta" to all tokens that belong to the specified sequence and have positions in [p0, p1)
  656. /// If the KV cache is RoPEd, the KV data is updated accordingly
  657. /// </summary>
  658. /// <param name="ctx"></param>
  659. /// <param name="seq"></param>
  660. /// <param name="p0"></param>
  661. /// <param name="p1"></param>
  662. /// <param name="delta"></param>
  663. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  664. public static extern void llama_kv_cache_seq_shift(SafeLLamaContextHandle ctx, LLamaSeqId seq, LLamaPos p0, LLamaPos p1, LLamaPos delta);
  665. /// <summary>
  666. /// Allocates a batch of tokens on the heap
  667. /// Each token can be assigned up to n_seq_max sequence ids
  668. /// The batch has to be freed with llama_batch_free()
  669. /// If embd != 0, llama_batch.embd will be allocated with size of n_tokens * embd * sizeof(float)
  670. /// Otherwise, llama_batch.token will be allocated to store n_tokens llama_token
  671. /// The rest of the llama_batch members are allocated with size n_tokens
  672. /// All members are left uninitialized
  673. /// </summary>
  674. /// <param name="n_tokens"></param>
  675. /// <param name="embd"></param>
  676. /// <param name="n_seq_max">Each token can be assigned up to n_seq_max sequence ids</param>
  677. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  678. public static extern LLamaNativeBatch llama_batch_init(int n_tokens, int embd, int n_seq_max);
  679. /// <summary>
  680. /// Frees a batch of tokens allocated with llama_batch_init()
  681. /// </summary>
  682. /// <param name="batch"></param>
  683. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  684. public static extern void llama_batch_free(LLamaNativeBatch batch);
  685. /// <summary>
  686. /// </summary>
  687. /// <param name="ctx"></param>
  688. /// <param name="batch"></param>
  689. /// <returns>Positive return values does not mean a fatal error, but rather a warning:<br />
  690. /// - 0: success<br />
  691. /// - 1: could not find a KV slot for the batch (try reducing the size of the batch or increase the context)<br />
  692. /// - &lt; 0: error<br />
  693. /// </returns>
  694. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  695. public static extern int llama_decode(SafeLLamaContextHandle ctx, LLamaNativeBatch batch);
  696. /// <summary>
  697. /// Set the number of threads used for decoding
  698. /// </summary>
  699. /// <param name="ctx"></param>
  700. /// <param name="n_threads">n_threads is the number of threads used for generation (single token)</param>
  701. /// <param name="n_threads_batch">n_threads_batch is the number of threads used for prompt and batch processing (multiple tokens)</param>
  702. /// <returns></returns>
  703. [DllImport(libraryName, CallingConvention = CallingConvention.Cdecl)]
  704. public static extern int llama_set_n_threads(SafeLLamaContextHandle ctx, uint n_threads, uint n_threads_batch);
  705. }
  706. }