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

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