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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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="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 uint TokenToSpan(LLamaToken token, Span<byte> dest)
  114. {
  115. var length = NativeApi.llama_token_to_piece(this, token, dest);
  116. return (uint)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<LLamaToken> tokens, Span<char> dest, Encoding encoding)
  130. {
  131. var decoder = new StreamingTokenDecoder(encoding, this);
  132. decoder.AddRange(tokens);
  133. var str = decoder.Read();
  134. if (str.Length < dest.Length)
  135. {
  136. str.AsSpan().CopyTo(dest);
  137. return dest.Slice(0, str.Length);
  138. }
  139. else
  140. {
  141. str.AsSpan().Slice(str.Length - dest.Length).CopyTo(dest);
  142. return dest;
  143. }
  144. }
  145. /// <summary>
  146. /// Convert a string of text into tokens
  147. /// </summary>
  148. /// <param name="text"></param>
  149. /// <param name="add_bos"></param>
  150. /// <param name="encoding"></param>
  151. /// <param name="special">Allow tokenizing special and/or control tokens which otherwise are not exposed and treated as plaintext.</param>
  152. /// <returns></returns>
  153. public LLamaToken[] Tokenize(string text, bool add_bos, bool special, Encoding encoding)
  154. {
  155. // Convert string to bytes, adding one extra byte to the end (null terminator)
  156. var bytesCount = encoding.GetByteCount(text);
  157. var bytes = new byte[bytesCount + 1];
  158. unsafe
  159. {
  160. fixed (char* charPtr = text)
  161. fixed (byte* bytePtr = &bytes[0])
  162. {
  163. encoding.GetBytes(charPtr, text.Length, bytePtr, bytes.Length);
  164. }
  165. }
  166. unsafe
  167. {
  168. fixed (byte* bytesPtr = &bytes[0])
  169. {
  170. // Tokenize once with no output, to get the token count. Output will be negative (indicating that there was insufficient space)
  171. var count = -NativeApi.llama_tokenize(this, bytesPtr, bytesCount, (LLamaToken*)IntPtr.Zero, 0, add_bos, special);
  172. // Tokenize again, this time outputting into an array of exactly the right size
  173. var tokens = new LLamaToken[count];
  174. fixed (LLamaToken* tokensPtr = &tokens[0])
  175. {
  176. NativeApi.llama_tokenize(this, bytesPtr, bytesCount, tokensPtr, count, add_bos, special);
  177. return tokens;
  178. }
  179. }
  180. }
  181. }
  182. #endregion
  183. #region context
  184. /// <summary>
  185. /// Create a new context for this model
  186. /// </summary>
  187. /// <param name="params"></param>
  188. /// <returns></returns>
  189. public SafeLLamaContextHandle CreateContext(LLamaContextParams @params)
  190. {
  191. return SafeLLamaContextHandle.Create(this, @params);
  192. }
  193. #endregion
  194. #region metadata
  195. /// <summary>
  196. /// Get the metadata key for the given index
  197. /// </summary>
  198. /// <param name="index">The index to get</param>
  199. /// <returns>The key, null if there is no such key or if the buffer was too small</returns>
  200. public Memory<byte>? MetadataKeyByIndex(int index)
  201. {
  202. int keyLength;
  203. unsafe
  204. {
  205. // Check if the key exists, without getting any bytes of data
  206. keyLength = NativeApi.llama_model_meta_key_by_index(this, index, Array.Empty<byte>());
  207. if (keyLength < 0)
  208. return null;
  209. }
  210. // get a buffer large enough to hold it
  211. var buffer = new byte[keyLength + 1];
  212. keyLength = NativeApi.llama_model_meta_key_by_index(this, index, buffer);
  213. Debug.Assert(keyLength >= 0);
  214. return buffer.AsMemory().Slice(0, keyLength);
  215. }
  216. /// <summary>
  217. /// Get the metadata value for the given index
  218. /// </summary>
  219. /// <param name="index">The index to get</param>
  220. /// <returns>The value, null if there is no such value or if the buffer was too small</returns>
  221. public Memory<byte>? MetadataValueByIndex(int index)
  222. {
  223. // Check if the key exists, without getting any bytes of data
  224. var valueLength = NativeApi.llama_model_meta_val_str_by_index(this, index, Array.Empty<byte>());
  225. if (valueLength < 0)
  226. return null;
  227. // get a buffer large enough to hold it
  228. var buffer = new byte[valueLength + 1];
  229. valueLength = NativeApi.llama_model_meta_val_str_by_index(this, index, buffer);
  230. Debug.Assert(valueLength >= 0);
  231. return buffer.AsMemory().Slice(0, valueLength);
  232. }
  233. internal IReadOnlyDictionary<string, string> ReadMetadata()
  234. {
  235. var result = new Dictionary<string, string>();
  236. for (var i = 0; i < MetadataCount; i++)
  237. {
  238. var keyBytes = MetadataKeyByIndex(i);
  239. if (keyBytes == null)
  240. continue;
  241. var key = Encoding.UTF8.GetStringFromSpan(keyBytes.Value.Span);
  242. var valBytes = MetadataValueByIndex(i);
  243. if (valBytes == null)
  244. continue;
  245. var val = Encoding.UTF8.GetStringFromSpan(valBytes.Value.Span);
  246. result[key] = val;
  247. }
  248. return result;
  249. }
  250. #endregion
  251. }
  252. }