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

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