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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. 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 { get; }
  21. /// <summary>
  22. /// Total number of tokens in the context
  23. /// </summary>
  24. public int ContextSize { get; }
  25. /// <summary>
  26. /// Dimension of embedding vectors
  27. /// </summary>
  28. public int EmbeddingSize { get; }
  29. /// <summary>
  30. /// Get the size of this model in bytes
  31. /// </summary>
  32. public ulong SizeInBytes { get; }
  33. /// <summary>
  34. /// Get the number of parameters in this model
  35. /// </summary>
  36. public ulong ParameterCount { get; }
  37. internal SafeLlamaModelHandle(IntPtr handle)
  38. : base(handle)
  39. {
  40. VocabCount = NativeApi.llama_n_vocab(this);
  41. ContextSize = NativeApi.llama_n_ctx_train(this);
  42. EmbeddingSize = NativeApi.llama_n_embd(this);
  43. SizeInBytes = NativeApi.llama_model_size(this);
  44. ParameterCount = NativeApi.llama_model_n_params(this);
  45. }
  46. /// <inheritdoc />
  47. protected override bool ReleaseHandle()
  48. {
  49. NativeApi.llama_free_model(DangerousGetHandle());
  50. SetHandle(IntPtr.Zero);
  51. return true;
  52. }
  53. /// <summary>
  54. /// Load a model from the given file path into memory
  55. /// </summary>
  56. /// <param name="modelPath"></param>
  57. /// <param name="lparams"></param>
  58. /// <returns></returns>
  59. /// <exception cref="RuntimeError"></exception>
  60. public static SafeLlamaModelHandle LoadFromFile(string modelPath, LLamaModelParams lparams)
  61. {
  62. var model_ptr = NativeApi.llama_load_model_from_file(modelPath, lparams);
  63. if (model_ptr == IntPtr.Zero)
  64. throw new RuntimeError($"Failed to load model {modelPath}.");
  65. return new SafeLlamaModelHandle(model_ptr);
  66. }
  67. #region LoRA
  68. /// <summary>
  69. /// Apply a LoRA adapter to a loaded model
  70. /// </summary>
  71. /// <param name="lora"></param>
  72. /// <param name="scale"></param>
  73. /// <param name="modelBase">A path to a higher quality model to use as a base for the layers modified by the
  74. /// adapter. Can be NULL to use the current loaded model.</param>
  75. /// <param name="threads"></param>
  76. /// <exception cref="RuntimeError"></exception>
  77. public void ApplyLoraFromFile(string lora, float scale, string? modelBase = null, int? threads = null)
  78. {
  79. var err = NativeApi.llama_model_apply_lora_from_file(
  80. this,
  81. lora,
  82. scale,
  83. string.IsNullOrEmpty(modelBase) ? null : modelBase,
  84. threads ?? Math.Max(1, Environment.ProcessorCount / 2)
  85. );
  86. if (err != 0)
  87. throw new RuntimeError("Failed to apply lora adapter.");
  88. }
  89. #endregion
  90. #region tokenize
  91. /// <summary>
  92. /// Convert a single llama token into bytes
  93. /// </summary>
  94. /// <param name="llama_token">Token to decode</param>
  95. /// <param name="dest">A span to attempt to write into. If this is too small nothing will be written</param>
  96. /// <returns>The size of this token. **nothing will be written** if this is larger than `dest`</returns>
  97. public int TokenToSpan(int llama_token, Span<byte> dest)
  98. {
  99. unsafe
  100. {
  101. fixed (byte* destPtr = dest)
  102. {
  103. var length = NativeApi.llama_token_to_piece(this, llama_token, destPtr, dest.Length);
  104. return Math.Abs(length);
  105. }
  106. }
  107. }
  108. /// <summary>
  109. /// Convert a sequence of tokens into characters.
  110. /// </summary>
  111. /// <param name="tokens"></param>
  112. /// <param name="dest"></param>
  113. /// <param name="encoding"></param>
  114. /// <returns>The section of the span which has valid data in it.
  115. /// If there was insufficient space in the output span this will be
  116. /// filled with as many characters as possible, starting from the _last_ token.
  117. /// </returns>
  118. internal Span<char> TokensToSpan(IReadOnlyList<int> tokens, Span<char> dest, Encoding encoding)
  119. {
  120. // Rent an array to detokenize into
  121. var tokenBytesArr = ArrayPool<byte>.Shared.Rent(16);
  122. // Convert all of the tokens into bytes
  123. var bytes = new List<byte>();
  124. foreach (var token in tokens)
  125. {
  126. var tokenBytes = TokenToBytes(ref tokenBytesArr, token, this);
  127. foreach (var tokenByte in tokenBytes)
  128. bytes.Add(tokenByte);
  129. }
  130. // Extract a span from the list
  131. var bytesSpan =
  132. #if NETSTANDARD2_0
  133. bytes.ToArray().AsSpan();
  134. #else
  135. CollectionsMarshal.AsSpan(bytes);
  136. #endif
  137. // Check how many characters these bytes represent. If there's not enough space in the
  138. // output array we need to handle that.
  139. var characterCount = encoding.GetCharCount(bytesSpan);
  140. if (characterCount > dest.Length)
  141. {
  142. var bigChars = ArrayPool<char>.Shared.Rent(characterCount);
  143. try
  144. {
  145. encoding.GetChars(bytesSpan, bigChars);
  146. var charSlice = bigChars
  147. .AsSpan(0, characterCount)
  148. .Slice(characterCount - dest.Length);
  149. charSlice.CopyTo(dest);
  150. return dest;
  151. }
  152. finally
  153. {
  154. ArrayPool<char>.Shared.Return(bigChars);
  155. }
  156. //todo: handle dest span too small
  157. throw new NotImplementedException();
  158. }
  159. else
  160. {
  161. var charCount = encoding.GetChars(bytes.ToArray(), dest);
  162. return dest.Slice(0, charCount);
  163. }
  164. // vvv Local Functions vvv
  165. static Span<byte> TokenToBytes(ref byte[] bytes, int token, SafeLlamaModelHandle model)
  166. {
  167. // Try to get bytes, if that fails we known the length
  168. var l = model.TokenToSpan(token, bytes);
  169. // Array was too small, get a bigger one
  170. if (l < 0)
  171. {
  172. ArrayPool<byte>.Shared.Return(bytes);
  173. bytes = ArrayPool<byte>.Shared.Rent(-l * 2);
  174. // Get bytes, this time it can't fail
  175. l = model.TokenToSpan(token, bytes);
  176. }
  177. Debug.Assert(l >= 0);
  178. return new Span<byte>(bytes, 0, l);
  179. }
  180. }
  181. /// <summary>
  182. /// Convert a string of text into tokens
  183. /// </summary>
  184. /// <param name="text"></param>
  185. /// <param name="add_bos"></param>
  186. /// <param name="encoding"></param>
  187. /// <param name="special">Allow tokenizing special and/or control tokens which otherwise are not exposed and treated as plaintext.</param>
  188. /// <returns></returns>
  189. public int[] Tokenize(string text, bool add_bos, bool special, Encoding encoding)
  190. {
  191. // Convert string to bytes, adding one extra byte to the end (null terminator)
  192. var bytesCount = encoding.GetByteCount(text);
  193. var bytes = new byte[bytesCount + 1];
  194. unsafe
  195. {
  196. fixed (char* charPtr = text)
  197. fixed (byte* bytePtr = &bytes[0])
  198. {
  199. encoding.GetBytes(charPtr, text.Length, bytePtr, bytes.Length);
  200. }
  201. }
  202. unsafe
  203. {
  204. fixed (byte* bytesPtr = &bytes[0])
  205. {
  206. // Tokenize once with no output, to get the token count. Output will be negative (indicating that there was insufficient space)
  207. var count = -NativeApi.llama_tokenize(this, bytesPtr, bytesCount, (int*)IntPtr.Zero, 0, add_bos, special);
  208. // Tokenize again, this time outputting into an array of exactly the right size
  209. var tokens = new int[count];
  210. fixed (int* tokensPtr = &tokens[0])
  211. {
  212. NativeApi.llama_tokenize(this, bytesPtr, bytesCount, tokensPtr, count, add_bos, special);
  213. return tokens;
  214. }
  215. }
  216. }
  217. }
  218. #endregion
  219. #region context
  220. /// <summary>
  221. /// Create a new context for this model
  222. /// </summary>
  223. /// <param name="params"></param>
  224. /// <returns></returns>
  225. public SafeLLamaContextHandle CreateContext(LLamaContextParams @params)
  226. {
  227. return SafeLLamaContextHandle.Create(this, @params);
  228. }
  229. #endregion
  230. }
  231. }