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.

SafeLlamaModelHandle.cs 19 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. using System;
  2. using System.Buffers;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using LLama.Exceptions;
  9. using LLama.Extensions;
  10. namespace LLama.Native
  11. {
  12. /// <summary>
  13. /// A reference to a set of llama model weights
  14. /// </summary>
  15. // ReSharper disable once ClassNeverInstantiated.Global (used implicitly in native API)
  16. public sealed class SafeLlamaModelHandle
  17. : SafeLLamaHandleBase
  18. {
  19. /// <summary>
  20. /// Total number of tokens in vocabulary of this model
  21. /// </summary>
  22. public int VocabCount => llama_n_vocab(this);
  23. /// <summary>
  24. /// Total number of tokens in the context
  25. /// </summary>
  26. public int ContextSize => llama_n_ctx_train(this);
  27. /// <summary>
  28. /// Get the rope frequency this model was trained with
  29. /// </summary>
  30. public float RopeFrequency => llama_rope_freq_scale_train(this);
  31. /// <summary>
  32. /// Dimension of embedding vectors
  33. /// </summary>
  34. public int EmbeddingSize => llama_n_embd(this);
  35. /// <summary>
  36. /// Get the size of this model in bytes
  37. /// </summary>
  38. public ulong SizeInBytes => llama_model_size(this);
  39. /// <summary>
  40. /// Get the number of parameters in this model
  41. /// </summary>
  42. public ulong ParameterCount => llama_model_n_params(this);
  43. /// <summary>
  44. /// Get a description of this model
  45. /// </summary>
  46. public string Description
  47. {
  48. get
  49. {
  50. unsafe
  51. {
  52. // Get description length
  53. var size = llama_model_desc(this, null, 0);
  54. var buf = new byte[size + 1];
  55. fixed (byte* bufPtr = buf)
  56. {
  57. size = llama_model_desc(this, bufPtr, buf.Length);
  58. return Encoding.UTF8.GetString(buf, 0, size);
  59. }
  60. }
  61. }
  62. }
  63. /// <summary>
  64. /// Get the number of metadata key/value pairs
  65. /// </summary>
  66. /// <returns></returns>
  67. public int MetadataCount => llama_model_meta_count(this);
  68. /// <inheritdoc />
  69. protected override bool ReleaseHandle()
  70. {
  71. llama_free_model(handle);
  72. return true;
  73. }
  74. /// <summary>
  75. /// Load a model from the given file path into memory
  76. /// </summary>
  77. /// <param name="modelPath"></param>
  78. /// <param name="lparams"></param>
  79. /// <returns></returns>
  80. /// <exception cref="RuntimeError"></exception>
  81. public static SafeLlamaModelHandle LoadFromFile(string modelPath, LLamaModelParams lparams)
  82. {
  83. // Try to open the model file, this will check:
  84. // - File exists (automatically throws FileNotFoundException)
  85. // - File is readable (explicit check)
  86. // This provides better error messages that llama.cpp, which would throw an access violation exception in both cases.
  87. using (var fs = new FileStream(modelPath, FileMode.Open))
  88. if (!fs.CanRead)
  89. throw new InvalidOperationException($"Model file '{modelPath}' is not readable");
  90. return llama_load_model_from_file(modelPath, lparams)
  91. ?? throw new LoadWeightsFailedException($"Failed to load model {modelPath}.");
  92. }
  93. #region native API
  94. static SafeLlamaModelHandle()
  95. {
  96. // This ensures that `NativeApi` has been loaded before calling the two native methods below
  97. NativeApi.llama_empty_call();
  98. }
  99. /// <summary>
  100. /// Load all of the weights of a model into memory.
  101. /// </summary>
  102. /// <param name="path_model"></param>
  103. /// <param name="params"></param>
  104. /// <returns>The loaded model, or null on failure.</returns>
  105. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  106. private static extern SafeLlamaModelHandle llama_load_model_from_file(string path_model, LLamaModelParams @params);
  107. /// <summary>
  108. /// Apply a LoRA adapter to a loaded model
  109. /// path_base_model is the path to a higher quality model to use as a base for
  110. /// the layers modified by the adapter. Can be NULL to use the current loaded model.
  111. /// The model needs to be reloaded before applying a new adapter, otherwise the adapter
  112. /// will be applied on top of the previous one
  113. /// </summary>
  114. /// <param name="model_ptr"></param>
  115. /// <param name="path_lora"></param>
  116. /// <param name="scale"></param>
  117. /// <param name="path_base_model"></param>
  118. /// <param name="n_threads"></param>
  119. /// <returns>Returns 0 on success</returns>
  120. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  121. 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);
  122. /// <summary>
  123. /// Frees all allocated memory associated with a model
  124. /// </summary>
  125. /// <param name="model"></param>
  126. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  127. private static extern void llama_free_model(IntPtr model);
  128. /// <summary>
  129. /// Get the number of metadata key/value pairs
  130. /// </summary>
  131. /// <param name="model"></param>
  132. /// <returns></returns>
  133. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  134. private static extern int llama_model_meta_count(SafeLlamaModelHandle model);
  135. /// <summary>
  136. /// Get metadata key name by index
  137. /// </summary>
  138. /// <param name="model">Model to fetch from</param>
  139. /// <param name="index">Index of key to fetch</param>
  140. /// <param name="dest">buffer to write result into</param>
  141. /// <returns>The length of the string on success (even if the buffer is too small). -1 is the key does not exist.</returns>
  142. private static int llama_model_meta_key_by_index(SafeLlamaModelHandle model, int index, Span<byte> dest)
  143. {
  144. unsafe
  145. {
  146. fixed (byte* destPtr = dest)
  147. {
  148. return llama_model_meta_key_by_index_native(model, index, destPtr, dest.Length);
  149. }
  150. }
  151. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "llama_model_meta_key_by_index")]
  152. static extern unsafe int llama_model_meta_key_by_index_native(SafeLlamaModelHandle model, int index, byte* buf, long buf_size);
  153. }
  154. /// <summary>
  155. /// Get metadata value as a string by index
  156. /// </summary>
  157. /// <param name="model">Model to fetch from</param>
  158. /// <param name="index">Index of val to fetch</param>
  159. /// <param name="dest">Buffer to write result into</param>
  160. /// <returns>The length of the string on success (even if the buffer is too small). -1 is the key does not exist.</returns>
  161. private static int llama_model_meta_val_str_by_index(SafeLlamaModelHandle model, int index, Span<byte> dest)
  162. {
  163. unsafe
  164. {
  165. fixed (byte* destPtr = dest)
  166. {
  167. return llama_model_meta_val_str_by_index_native(model, index, destPtr, dest.Length);
  168. }
  169. }
  170. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "llama_model_meta_val_str_by_index")]
  171. static extern unsafe int llama_model_meta_val_str_by_index_native(SafeLlamaModelHandle model, int index, byte* buf, long buf_size);
  172. }
  173. /// <summary>
  174. /// Get metadata value as a string by key name
  175. /// </summary>
  176. /// <param name="model"></param>
  177. /// <param name="key"></param>
  178. /// <param name="buf"></param>
  179. /// <param name="buf_size"></param>
  180. /// <returns>The length of the string on success, or -1 on failure</returns>
  181. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  182. public static extern unsafe int llama_model_meta_val_str(SafeLlamaModelHandle model, byte* key, byte* buf, long buf_size);
  183. /// <summary>
  184. /// Get the number of tokens in the model vocabulary
  185. /// </summary>
  186. /// <param name="model"></param>
  187. /// <returns></returns>
  188. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  189. private static extern int llama_n_vocab(SafeLlamaModelHandle model);
  190. /// <summary>
  191. /// Get the size of the context window for the model
  192. /// </summary>
  193. /// <param name="model"></param>
  194. /// <returns></returns>
  195. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  196. private static extern int llama_n_ctx_train(SafeLlamaModelHandle model);
  197. /// <summary>
  198. /// Get the dimension of embedding vectors from this model
  199. /// </summary>
  200. /// <param name="model"></param>
  201. /// <returns></returns>
  202. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  203. private static extern int llama_n_embd(SafeLlamaModelHandle model);
  204. /// <summary>
  205. /// Get a string describing the model type
  206. /// </summary>
  207. /// <param name="model"></param>
  208. /// <param name="buf"></param>
  209. /// <param name="buf_size"></param>
  210. /// <returns>The length of the string on success (even if the buffer is too small)., or -1 on failure</returns>
  211. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  212. private static extern unsafe int llama_model_desc(SafeLlamaModelHandle model, byte* buf, long buf_size);
  213. /// <summary>
  214. /// Get the size of the model in bytes
  215. /// </summary>
  216. /// <param name="model"></param>
  217. /// <returns>The size of the model</returns>
  218. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  219. private static extern ulong llama_model_size(SafeLlamaModelHandle model);
  220. /// <summary>
  221. /// Get the number of parameters in this model
  222. /// </summary>
  223. /// <param name="model"></param>
  224. /// <returns>The functions return the length of the string on success, or -1 on failure</returns>
  225. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  226. private static extern ulong llama_model_n_params(SafeLlamaModelHandle model);
  227. /// <summary>
  228. /// Get the model's RoPE frequency scaling factor
  229. /// </summary>
  230. /// <param name="model"></param>
  231. /// <returns></returns>
  232. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  233. private static extern float llama_rope_freq_scale_train(SafeLlamaModelHandle model);
  234. #endregion
  235. #region LoRA
  236. /// <summary>
  237. /// Apply a LoRA adapter to a loaded model
  238. /// </summary>
  239. /// <param name="lora"></param>
  240. /// <param name="scale"></param>
  241. /// <param name="modelBase">A path to a higher quality model to use as a base for the layers modified by the
  242. /// adapter. Can be NULL to use the current loaded model.</param>
  243. /// <param name="threads"></param>
  244. /// <exception cref="RuntimeError"></exception>
  245. public void ApplyLoraFromFile(string lora, float scale, string? modelBase = null, int? threads = null)
  246. {
  247. var err = llama_model_apply_lora_from_file(
  248. this,
  249. lora,
  250. scale,
  251. string.IsNullOrEmpty(modelBase) ? null : modelBase,
  252. threads ?? Math.Max(1, Environment.ProcessorCount / 2)
  253. );
  254. if (err != 0)
  255. throw new RuntimeError("Failed to apply lora adapter.");
  256. }
  257. #endregion
  258. #region tokenize
  259. /// <summary>
  260. /// Convert a single llama token into bytes
  261. /// </summary>
  262. /// <param name="token">Token to decode</param>
  263. /// <param name="dest">A span to attempt to write into. If this is too small nothing will be written</param>
  264. /// <returns>The size of this token. **nothing will be written** if this is larger than `dest`</returns>
  265. public uint TokenToSpan(LLamaToken token, Span<byte> dest)
  266. {
  267. var length = NativeApi.llama_token_to_piece(this, token, dest);
  268. return (uint)Math.Abs(length);
  269. }
  270. /// <summary>
  271. /// Convert a sequence of tokens into characters.
  272. /// </summary>
  273. /// <param name="tokens"></param>
  274. /// <param name="dest"></param>
  275. /// <param name="encoding"></param>
  276. /// <returns>The section of the span which has valid data in it.
  277. /// If there was insufficient space in the output span this will be
  278. /// filled with as many characters as possible, starting from the _last_ token.
  279. /// </returns>
  280. [Obsolete("Use a StreamingTokenDecoder instead")]
  281. internal Span<char> TokensToSpan(IReadOnlyList<LLamaToken> tokens, Span<char> dest, Encoding encoding)
  282. {
  283. var decoder = new StreamingTokenDecoder(encoding, this);
  284. decoder.AddRange(tokens);
  285. var str = decoder.Read();
  286. if (str.Length < dest.Length)
  287. {
  288. str.AsSpan().CopyTo(dest);
  289. return dest.Slice(0, str.Length);
  290. }
  291. else
  292. {
  293. str.AsSpan().Slice(str.Length - dest.Length).CopyTo(dest);
  294. return dest;
  295. }
  296. }
  297. /// <summary>
  298. /// Convert a string of text into tokens
  299. /// </summary>
  300. /// <param name="text"></param>
  301. /// <param name="add_bos"></param>
  302. /// <param name="encoding"></param>
  303. /// <param name="special">Allow tokenizing special and/or control tokens which otherwise are not exposed and treated as plaintext.</param>
  304. /// <returns></returns>
  305. public LLamaToken[] Tokenize(string text, bool add_bos, bool special, Encoding encoding)
  306. {
  307. // Early exit if there's no work to do
  308. if (text == "" && !add_bos)
  309. return Array.Empty<LLamaToken>();
  310. // Convert string to bytes, adding one extra byte to the end (null terminator)
  311. var bytesCount = encoding.GetByteCount(text);
  312. var bytes = ArrayPool<byte>.Shared.Rent(bytesCount + 1);
  313. try
  314. {
  315. unsafe
  316. {
  317. fixed (char* textPtr = text)
  318. fixed (byte* bytesPtr = bytes)
  319. {
  320. // Convert text into bytes
  321. encoding.GetBytes(textPtr, text.Length, bytesPtr, bytes.Length);
  322. // Tokenize once with no output, to get the token count. Output will be negative (indicating that there was insufficient space)
  323. var count = -NativeApi.llama_tokenize(this, bytesPtr, bytesCount, (LLamaToken*)IntPtr.Zero, 0, add_bos, special);
  324. // Tokenize again, this time outputting into an array of exactly the right size
  325. var tokens = new LLamaToken[count];
  326. fixed (LLamaToken* tokensPtr = tokens)
  327. {
  328. NativeApi.llama_tokenize(this, bytesPtr, bytesCount, tokensPtr, count, add_bos, special);
  329. return tokens;
  330. }
  331. }
  332. }
  333. }
  334. finally
  335. {
  336. ArrayPool<byte>.Shared.Return(bytes, true);
  337. }
  338. }
  339. #endregion
  340. #region context
  341. /// <summary>
  342. /// Create a new context for this model
  343. /// </summary>
  344. /// <param name="params"></param>
  345. /// <returns></returns>
  346. public SafeLLamaContextHandle CreateContext(LLamaContextParams @params)
  347. {
  348. return SafeLLamaContextHandle.Create(this, @params);
  349. }
  350. #endregion
  351. #region metadata
  352. /// <summary>
  353. /// Get the metadata key for the given index
  354. /// </summary>
  355. /// <param name="index">The index to get</param>
  356. /// <returns>The key, null if there is no such key or if the buffer was too small</returns>
  357. public Memory<byte>? MetadataKeyByIndex(int index)
  358. {
  359. // Check if the key exists, without getting any bytes of data
  360. var keyLength = llama_model_meta_key_by_index(this, index, Array.Empty<byte>());
  361. if (keyLength < 0)
  362. return null;
  363. // get a buffer large enough to hold it
  364. var buffer = new byte[keyLength + 1];
  365. keyLength = llama_model_meta_key_by_index(this, index, buffer);
  366. Debug.Assert(keyLength >= 0);
  367. return buffer.AsMemory().Slice(0, keyLength);
  368. }
  369. /// <summary>
  370. /// Get the metadata value for the given index
  371. /// </summary>
  372. /// <param name="index">The index to get</param>
  373. /// <returns>The value, null if there is no such value or if the buffer was too small</returns>
  374. public Memory<byte>? MetadataValueByIndex(int index)
  375. {
  376. // Check if the key exists, without getting any bytes of data
  377. var valueLength = llama_model_meta_val_str_by_index(this, index, Array.Empty<byte>());
  378. if (valueLength < 0)
  379. return null;
  380. // get a buffer large enough to hold it
  381. var buffer = new byte[valueLength + 1];
  382. valueLength = llama_model_meta_val_str_by_index(this, index, buffer);
  383. Debug.Assert(valueLength >= 0);
  384. return buffer.AsMemory().Slice(0, valueLength);
  385. }
  386. internal IReadOnlyDictionary<string, string> ReadMetadata()
  387. {
  388. var result = new Dictionary<string, string>();
  389. for (var i = 0; i < MetadataCount; i++)
  390. {
  391. var keyBytes = MetadataKeyByIndex(i);
  392. if (keyBytes == null)
  393. continue;
  394. var key = Encoding.UTF8.GetStringFromSpan(keyBytes.Value.Span);
  395. var valBytes = MetadataValueByIndex(i);
  396. if (valBytes == null)
  397. continue;
  398. var val = Encoding.UTF8.GetStringFromSpan(valBytes.Value.Span);
  399. result[key] = val;
  400. }
  401. return result;
  402. }
  403. #endregion
  404. }
  405. }