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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. using System;
  2. using System.Buffers;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  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. public sealed class SafeLlamaModelHandle
  14. : SafeLLamaHandleBase
  15. {
  16. /// <summary>
  17. /// Total number of tokens in vocabulary of this model
  18. /// </summary>
  19. public int VocabCount { get; }
  20. /// <summary>
  21. /// Total number of tokens in the context
  22. /// </summary>
  23. public int ContextSize { get; }
  24. /// <summary>
  25. /// Dimension of embedding vectors
  26. /// </summary>
  27. public int EmbeddingSize { get; }
  28. /// <summary>
  29. /// Get the size of this model in bytes
  30. /// </summary>
  31. public ulong SizeInBytes { get; }
  32. /// <summary>
  33. /// Get the number of parameters in this model
  34. /// </summary>
  35. public ulong ParameterCount { get; }
  36. internal SafeLlamaModelHandle(IntPtr handle)
  37. : base(handle)
  38. {
  39. VocabCount = NativeApi.llama_n_vocab(this);
  40. ContextSize = NativeApi.llama_n_ctx_train(this);
  41. EmbeddingSize = NativeApi.llama_n_embd(this);
  42. SizeInBytes = NativeApi.llama_model_size(this);
  43. ParameterCount = NativeApi.llama_model_n_params(this);
  44. }
  45. /// <inheritdoc />
  46. protected override bool ReleaseHandle()
  47. {
  48. NativeApi.llama_free_model(DangerousGetHandle());
  49. SetHandle(IntPtr.Zero);
  50. return true;
  51. }
  52. /// <summary>
  53. /// Load a model from the given file path into memory
  54. /// </summary>
  55. /// <param name="modelPath"></param>
  56. /// <param name="lparams"></param>
  57. /// <returns></returns>
  58. /// <exception cref="RuntimeError"></exception>
  59. public static SafeLlamaModelHandle LoadFromFile(string modelPath, LLamaModelParams lparams)
  60. {
  61. var model_ptr = NativeApi.llama_load_model_from_file(modelPath, lparams);
  62. if (model_ptr == IntPtr.Zero)
  63. throw new RuntimeError($"Failed to load model {modelPath}.");
  64. return new SafeLlamaModelHandle(model_ptr);
  65. }
  66. #region LoRA
  67. /// <summary>
  68. /// Apply a LoRA adapter to a loaded model
  69. /// </summary>
  70. /// <param name="lora"></param>
  71. /// <param name="scale"></param>
  72. /// <param name="modelBase">A path to a higher quality model to use as a base for the layers modified by the
  73. /// adapter. Can be NULL to use the current loaded model.</param>
  74. /// <param name="threads"></param>
  75. /// <exception cref="RuntimeError"></exception>
  76. public void ApplyLoraFromFile(string lora, float scale, string? modelBase = null, int threads = -1)
  77. {
  78. var err = NativeApi.llama_model_apply_lora_from_file(
  79. this,
  80. lora,
  81. scale,
  82. string.IsNullOrEmpty(modelBase) ? null : modelBase,
  83. threads
  84. );
  85. if (err != 0)
  86. throw new RuntimeError("Failed to apply lora adapter.");
  87. }
  88. #endregion
  89. #region tokenize
  90. /// <summary>
  91. /// Convert a single llama token into bytes
  92. /// </summary>
  93. /// <param name="llama_token">Token to decode</param>
  94. /// <param name="dest">A span to attempt to write into. If this is too small nothing will be written</param>
  95. /// <returns>The size of this token. **nothing will be written** if this is larger than `dest`</returns>
  96. public int TokenToSpan(int llama_token, Span<byte> dest)
  97. {
  98. unsafe
  99. {
  100. fixed (byte* destPtr = dest)
  101. {
  102. var length = NativeApi.llama_token_to_piece(this, llama_token, destPtr, dest.Length);
  103. return Math.Abs(length);
  104. }
  105. }
  106. }
  107. /// <summary>
  108. /// Convert a single llama token into a string
  109. /// </summary>
  110. /// <param name="llama_token"></param>
  111. /// <param name="encoding">Encoding to use to decode the bytes into a string</param>
  112. /// <returns></returns>
  113. public string TokenToString(int llama_token, Encoding encoding)
  114. {
  115. unsafe
  116. {
  117. var length = NativeApi.llama_token_to_piece(this, llama_token, null, 0);
  118. if (length == 0)
  119. return "";
  120. Span<byte> bytes = stackalloc byte[-length];
  121. fixed (byte* bytePtr = bytes)
  122. {
  123. var written = NativeApi.llama_token_to_piece(this, llama_token, bytePtr, bytes.Length);
  124. Debug.Assert(written == bytes.Length);
  125. return encoding.GetString(bytePtr, bytes.Length);
  126. }
  127. }
  128. }
  129. /// <summary>
  130. /// Append a single llama token to a string builder
  131. /// </summary>
  132. /// <param name="llama_token">Token to decode</param>
  133. /// <param name="encoding"></param>
  134. /// <param name="dest">string builder to append the result to</param>
  135. public void TokenToString(int llama_token, Encoding encoding, StringBuilder dest)
  136. {
  137. unsafe
  138. {
  139. var length = NativeApi.llama_token_to_piece(this, llama_token, null, 0);
  140. if (length == 0)
  141. return;
  142. Span<byte> bytes = stackalloc byte[-length];
  143. fixed (byte* bytePtr = bytes)
  144. {
  145. // Decode into bytes
  146. var written = NativeApi.llama_token_to_piece(this, llama_token, bytePtr, bytes.Length);
  147. Debug.Assert(written == bytes.Length);
  148. // Decode into chars
  149. var charCount = encoding.GetCharCount(bytePtr, bytes.Length);
  150. Span<char> chars = stackalloc char[charCount];
  151. fixed (char* charPtr = chars)
  152. encoding.GetChars(bytePtr, bytes.Length, charPtr, chars.Length);
  153. // Write it to the output
  154. for (var i = 0; i < chars.Length; i++)
  155. dest.Append(chars[i]);
  156. }
  157. }
  158. }
  159. /// <summary>
  160. /// Convert a sequence of tokens into characters. If there
  161. /// </summary>
  162. /// <param name="tokens"></param>
  163. /// <param name="dest"></param>
  164. /// <param name="encoding"></param>
  165. /// <returns>The section of the span which has valid data in it.
  166. /// If there was insufficient space in the output span this will be
  167. /// filled with as many characters as possible, starting from the _last_ token.
  168. /// </returns>
  169. internal Span<char> TokensToSpan(IReadOnlyList<int> tokens, Span<char> dest, Encoding encoding)
  170. {
  171. // Rent an array to detokenize into
  172. var tokenBytesArr = ArrayPool<byte>.Shared.Rent(16);
  173. var tokenCharsArr = ArrayPool<char>.Shared.Rent(16);
  174. try
  175. {
  176. var totalCharacters = 0;
  177. var unused = dest;
  178. for (var i = tokens.Count - 1; i >= 0; i--)
  179. {
  180. var token = tokens[i];
  181. // Get bytes for this token
  182. var tokenBytes = TokenToBytes(ref tokenBytesArr, token, this);
  183. // Get chars for this token
  184. var tokenChars = BytesToChars(ref tokenCharsArr, tokenBytes, encoding);
  185. // Trim down number of characters if there are too many
  186. if (tokenChars.Length > unused.Length)
  187. tokenChars = tokenChars.Slice(tokenChars.Length - unused.Length, unused.Length);
  188. // Copy characters
  189. tokenChars.CopyTo(unused.Slice(unused.Length - tokenChars.Length, tokenChars.Length));
  190. unused = unused.Slice(0, unused.Length - tokenChars.Length);
  191. totalCharacters += tokenChars.Length;
  192. // Break out if we've run out of space
  193. if (unused.Length == 0)
  194. break;
  195. }
  196. return dest.Slice(dest.Length - totalCharacters, totalCharacters);
  197. }
  198. finally
  199. {
  200. ArrayPool<byte>.Shared.Return(tokenBytesArr);
  201. ArrayPool<char>.Shared.Return(tokenCharsArr);
  202. }
  203. // vvv Local Functions vvv
  204. static Span<byte> TokenToBytes(ref byte[] bytes, int token, SafeLlamaModelHandle model)
  205. {
  206. // Try to get bytes, if that fails we known the length
  207. var l = model.TokenToSpan(token, bytes);
  208. // Array was too small, get a bigger one
  209. if (l < 0)
  210. {
  211. ArrayPool<byte>.Shared.Return(bytes);
  212. bytes = ArrayPool<byte>.Shared.Rent(-l * 2);
  213. // Get bytes, this time it can't fail
  214. l = model.TokenToSpan(token, bytes);
  215. }
  216. Debug.Assert(l >= 0);
  217. return new Span<byte>(bytes, 0, l);
  218. }
  219. static Span<char> BytesToChars(ref char[] chars, ReadOnlySpan<byte> bytes, Encoding encoding)
  220. {
  221. var count = encoding.GetCharCount(bytes);
  222. if (count > chars.Length)
  223. {
  224. ArrayPool<char>.Shared.Return(chars);
  225. chars = ArrayPool<char>.Shared.Rent(count * 2);
  226. }
  227. encoding.GetChars(bytes, chars);
  228. return chars.AsSpan(0, count);
  229. }
  230. }
  231. /// <summary>
  232. /// Convert a string of text into tokens
  233. /// </summary>
  234. /// <param name="text"></param>
  235. /// <param name="add_bos"></param>
  236. /// <param name="encoding"></param>
  237. /// <returns></returns>
  238. public int[] Tokenize(string text, bool add_bos, Encoding encoding)
  239. {
  240. // Convert string to bytes, adding one extra byte to the end (null terminator)
  241. var bytesCount = encoding.GetByteCount(text);
  242. var bytes = new byte[bytesCount + 1];
  243. unsafe
  244. {
  245. fixed (char* charPtr = text)
  246. fixed (byte* bytePtr = &bytes[0])
  247. {
  248. encoding.GetBytes(charPtr, text.Length, bytePtr, bytes.Length);
  249. }
  250. }
  251. unsafe
  252. {
  253. fixed (byte* bytesPtr = &bytes[0])
  254. {
  255. // Tokenize once with no output, to get the token count. Output will be negative (indicating that there was insufficient space)
  256. var count = -NativeApi.llama_tokenize(this, bytesPtr, bytesCount, (int*)IntPtr.Zero, 0, add_bos);
  257. // Tokenize again, this time outputting into an array of exactly the right size
  258. var tokens = new int[count];
  259. fixed (int* tokensPtr = &tokens[0])
  260. {
  261. NativeApi.llama_tokenize(this, bytesPtr, bytesCount, tokensPtr, count, add_bos);
  262. return tokens;
  263. }
  264. }
  265. }
  266. }
  267. #endregion
  268. #region context
  269. /// <summary>
  270. /// Create a new context for this model
  271. /// </summary>
  272. /// <param name="params"></param>
  273. /// <returns></returns>
  274. public SafeLLamaContextHandle CreateContext(LLamaContextParams @params)
  275. {
  276. return SafeLLamaContextHandle.Create(this, @params);
  277. }
  278. #endregion
  279. }
  280. }