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

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