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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 => NativeApi.llama_n_vocab(this);
  22. /// <summary>
  23. /// Total number of tokens in the context
  24. /// </summary>
  25. public int ContextSize => NativeApi.llama_n_ctx_train(this);
  26. /// <summary>
  27. /// Dimension of embedding vectors
  28. /// </summary>
  29. public int EmbeddingSize => NativeApi.llama_n_embd(this);
  30. /// <summary>
  31. /// Get the size of this model in bytes
  32. /// </summary>
  33. public ulong SizeInBytes => NativeApi.llama_model_size(this);
  34. /// <summary>
  35. /// Get the number of parameters in this model
  36. /// </summary>
  37. public ulong ParameterCount => NativeApi.llama_model_n_params(this);
  38. /// <summary>
  39. /// Get the number of metadata key/value pairs
  40. /// </summary>
  41. /// <returns></returns>
  42. public int MetadataCount => NativeApi.llama_model_meta_count(this);
  43. /// <inheritdoc />
  44. protected override bool ReleaseHandle()
  45. {
  46. llama_free_model(handle);
  47. return true;
  48. }
  49. /// <summary>
  50. /// Load a model from the given file path into memory
  51. /// </summary>
  52. /// <param name="modelPath"></param>
  53. /// <param name="lparams"></param>
  54. /// <returns></returns>
  55. /// <exception cref="RuntimeError"></exception>
  56. public static SafeLlamaModelHandle LoadFromFile(string modelPath, LLamaModelParams lparams)
  57. {
  58. var model = llama_load_model_from_file(modelPath, lparams);
  59. if (model == null)
  60. throw new RuntimeError($"Failed to load model {modelPath}.");
  61. return model;
  62. }
  63. #region native API
  64. static SafeLlamaModelHandle()
  65. {
  66. // This ensures that `NativeApi` has been loaded before calling the two native methods below
  67. NativeApi.llama_empty_call();
  68. }
  69. /// <summary>
  70. /// Load all of the weights of a model into memory.
  71. /// </summary>
  72. /// <param name="path_model"></param>
  73. /// <param name="params"></param>
  74. /// <returns>The loaded model, or null on failure.</returns>
  75. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  76. private static extern SafeLlamaModelHandle llama_load_model_from_file(string path_model, LLamaModelParams @params);
  77. /// <summary>
  78. /// Frees all allocated memory associated with a model
  79. /// </summary>
  80. /// <param name="model"></param>
  81. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  82. private static extern void llama_free_model(IntPtr model);
  83. #endregion
  84. #region LoRA
  85. /// <summary>
  86. /// Apply a LoRA adapter to a loaded model
  87. /// </summary>
  88. /// <param name="lora"></param>
  89. /// <param name="scale"></param>
  90. /// <param name="modelBase">A path to a higher quality model to use as a base for the layers modified by the
  91. /// adapter. Can be NULL to use the current loaded model.</param>
  92. /// <param name="threads"></param>
  93. /// <exception cref="RuntimeError"></exception>
  94. public void ApplyLoraFromFile(string lora, float scale, string? modelBase = null, int? threads = null)
  95. {
  96. var err = NativeApi.llama_model_apply_lora_from_file(
  97. this,
  98. lora,
  99. scale,
  100. string.IsNullOrEmpty(modelBase) ? null : modelBase,
  101. threads ?? Math.Max(1, Environment.ProcessorCount / 2)
  102. );
  103. if (err != 0)
  104. throw new RuntimeError("Failed to apply lora adapter.");
  105. }
  106. #endregion
  107. #region tokenize
  108. /// <summary>
  109. /// Convert a single llama token into bytes
  110. /// </summary>
  111. /// <param name="token">Token to decode</param>
  112. /// <param name="dest">A span to attempt to write into. If this is too small nothing will be written</param>
  113. /// <returns>The size of this token. **nothing will be written** if this is larger than `dest`</returns>
  114. public uint TokenToSpan(LLamaToken token, Span<byte> dest)
  115. {
  116. var length = NativeApi.llama_token_to_piece(this, token, dest);
  117. return (uint)Math.Abs(length);
  118. }
  119. /// <summary>
  120. /// Convert a sequence of tokens into characters.
  121. /// </summary>
  122. /// <param name="tokens"></param>
  123. /// <param name="dest"></param>
  124. /// <param name="encoding"></param>
  125. /// <returns>The section of the span which has valid data in it.
  126. /// If there was insufficient space in the output span this will be
  127. /// filled with as many characters as possible, starting from the _last_ token.
  128. /// </returns>
  129. [Obsolete("Use a StreamingTokenDecoder instead")]
  130. internal Span<char> TokensToSpan(IReadOnlyList<LLamaToken> tokens, Span<char> dest, Encoding encoding)
  131. {
  132. var decoder = new StreamingTokenDecoder(encoding, this);
  133. decoder.AddRange(tokens);
  134. var str = decoder.Read();
  135. if (str.Length < dest.Length)
  136. {
  137. str.AsSpan().CopyTo(dest);
  138. return dest.Slice(0, str.Length);
  139. }
  140. else
  141. {
  142. str.AsSpan().Slice(str.Length - dest.Length).CopyTo(dest);
  143. return dest;
  144. }
  145. }
  146. /// <summary>
  147. /// Convert a string of text into tokens
  148. /// </summary>
  149. /// <param name="text"></param>
  150. /// <param name="add_bos"></param>
  151. /// <param name="encoding"></param>
  152. /// <param name="special">Allow tokenizing special and/or control tokens which otherwise are not exposed and treated as plaintext.</param>
  153. /// <returns></returns>
  154. public LLamaToken[] Tokenize(string text, bool add_bos, bool special, Encoding encoding)
  155. {
  156. // Early exit if there's no work to do
  157. if (text == "" && !add_bos)
  158. return Array.Empty<LLamaToken>();
  159. // Convert string to bytes, adding one extra byte to the end (null terminator)
  160. var bytesCount = encoding.GetByteCount(text);
  161. var bytes = ArrayPool<byte>.Shared.Rent(bytesCount + 1);
  162. try
  163. {
  164. unsafe
  165. {
  166. fixed (char* textPtr = text)
  167. fixed (byte* bytesPtr = bytes)
  168. {
  169. // Convert text into bytes
  170. encoding.GetBytes(textPtr, text.Length, bytesPtr, bytes.Length);
  171. // Tokenize once with no output, to get the token count. Output will be negative (indicating that there was insufficient space)
  172. var count = -NativeApi.llama_tokenize(this, bytesPtr, bytesCount, (LLamaToken*)IntPtr.Zero, 0, add_bos, special);
  173. // Tokenize again, this time outputting into an array of exactly the right size
  174. var tokens = new LLamaToken[count];
  175. fixed (LLamaToken* tokensPtr = tokens)
  176. {
  177. NativeApi.llama_tokenize(this, bytesPtr, bytesCount, tokensPtr, count, add_bos, special);
  178. return tokens;
  179. }
  180. }
  181. }
  182. }
  183. finally
  184. {
  185. ArrayPool<byte>.Shared.Return(bytes, true);
  186. }
  187. }
  188. #endregion
  189. #region context
  190. /// <summary>
  191. /// Create a new context for this model
  192. /// </summary>
  193. /// <param name="params"></param>
  194. /// <returns></returns>
  195. public SafeLLamaContextHandle CreateContext(LLamaContextParams @params)
  196. {
  197. return SafeLLamaContextHandle.Create(this, @params);
  198. }
  199. #endregion
  200. #region metadata
  201. /// <summary>
  202. /// Get the metadata key for the given index
  203. /// </summary>
  204. /// <param name="index">The index to get</param>
  205. /// <returns>The key, null if there is no such key or if the buffer was too small</returns>
  206. public Memory<byte>? MetadataKeyByIndex(int index)
  207. {
  208. // Check if the key exists, without getting any bytes of data
  209. var keyLength = NativeApi.llama_model_meta_key_by_index(this, index, Array.Empty<byte>());
  210. if (keyLength < 0)
  211. return null;
  212. // get a buffer large enough to hold it
  213. var buffer = new byte[keyLength + 1];
  214. keyLength = NativeApi.llama_model_meta_key_by_index(this, index, buffer);
  215. Debug.Assert(keyLength >= 0);
  216. return buffer.AsMemory().Slice(0, keyLength);
  217. }
  218. /// <summary>
  219. /// Get the metadata value for the given index
  220. /// </summary>
  221. /// <param name="index">The index to get</param>
  222. /// <returns>The value, null if there is no such value or if the buffer was too small</returns>
  223. public Memory<byte>? MetadataValueByIndex(int index)
  224. {
  225. // Check if the key exists, without getting any bytes of data
  226. var valueLength = NativeApi.llama_model_meta_val_str_by_index(this, index, Array.Empty<byte>());
  227. if (valueLength < 0)
  228. return null;
  229. // get a buffer large enough to hold it
  230. var buffer = new byte[valueLength + 1];
  231. valueLength = NativeApi.llama_model_meta_val_str_by_index(this, index, buffer);
  232. Debug.Assert(valueLength >= 0);
  233. return buffer.AsMemory().Slice(0, valueLength);
  234. }
  235. internal IReadOnlyDictionary<string, string> ReadMetadata()
  236. {
  237. var result = new Dictionary<string, string>();
  238. for (var i = 0; i < MetadataCount; i++)
  239. {
  240. var keyBytes = MetadataKeyByIndex(i);
  241. if (keyBytes == null)
  242. continue;
  243. var key = Encoding.UTF8.GetStringFromSpan(keyBytes.Value.Span);
  244. var valBytes = MetadataValueByIndex(i);
  245. if (valBytes == null)
  246. continue;
  247. var val = Encoding.UTF8.GetStringFromSpan(valBytes.Value.Span);
  248. result[key] = val;
  249. }
  250. return result;
  251. }
  252. #endregion
  253. }
  254. }