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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using LLama.Exceptions;
  5. namespace LLama.Native
  6. {
  7. /// <summary>
  8. /// A reference to a set of llama model weights
  9. /// </summary>
  10. public sealed class SafeLlamaModelHandle
  11. : SafeLLamaHandleBase
  12. {
  13. /// <summary>
  14. /// Total number of tokens in vocabulary of this model
  15. /// </summary>
  16. public int VocabCount { get; }
  17. /// <summary>
  18. /// Total number of tokens in the context
  19. /// </summary>
  20. public int ContextSize { get; }
  21. /// <summary>
  22. /// Dimension of embedding vectors
  23. /// </summary>
  24. public int EmbeddingSize { get; }
  25. /// <summary>
  26. /// Get the size of this model in bytes
  27. /// </summary>
  28. public ulong SizeInBytes { get; }
  29. /// <summary>
  30. /// Get the number of parameters in this model
  31. /// </summary>
  32. public ulong ParameterCount { get; }
  33. internal SafeLlamaModelHandle(IntPtr handle)
  34. : base(handle)
  35. {
  36. VocabCount = NativeApi.llama_n_vocab(this);
  37. ContextSize = NativeApi.llama_n_ctx_train(this);
  38. EmbeddingSize = NativeApi.llama_n_embd(this);
  39. SizeInBytes = NativeApi.llama_model_size(this);
  40. ParameterCount = NativeApi.llama_model_n_params(this);
  41. }
  42. /// <inheritdoc />
  43. protected override bool ReleaseHandle()
  44. {
  45. NativeApi.llama_free_model(DangerousGetHandle());
  46. SetHandle(IntPtr.Zero);
  47. return true;
  48. }
  49. /// <summary>
  50. /// Load a model from the given file path into memory
  51. /// </summary>
  52. /// <param name="modelPath"></param>
  53. /// <param name="lparams"></param>
  54. /// <returns></returns>
  55. /// <exception cref="RuntimeError"></exception>
  56. public static SafeLlamaModelHandle LoadFromFile(string modelPath, LLamaModelParams lparams)
  57. {
  58. var model_ptr = NativeApi.llama_load_model_from_file(modelPath, lparams);
  59. if (model_ptr == IntPtr.Zero)
  60. throw new RuntimeError($"Failed to load model {modelPath}.");
  61. return new SafeLlamaModelHandle(model_ptr);
  62. }
  63. #region LoRA
  64. /// <summary>
  65. /// Apply a LoRA adapter to a loaded model
  66. /// </summary>
  67. /// <param name="lora"></param>
  68. /// <param name="scale"></param>
  69. /// <param name="modelBase">A path to a higher quality model to use as a base for the layers modified by the
  70. /// adapter. Can be NULL to use the current loaded model.</param>
  71. /// <param name="threads"></param>
  72. /// <exception cref="RuntimeError"></exception>
  73. public void ApplyLoraFromFile(string lora, float scale, string? modelBase = null, int? threads = null)
  74. {
  75. var err = NativeApi.llama_model_apply_lora_from_file(
  76. this,
  77. lora,
  78. scale,
  79. string.IsNullOrEmpty(modelBase) ? null : modelBase,
  80. threads ?? Math.Max(1, Environment.ProcessorCount / 2)
  81. );
  82. if (err != 0)
  83. throw new RuntimeError("Failed to apply lora adapter.");
  84. }
  85. #endregion
  86. #region tokenize
  87. /// <summary>
  88. /// Convert a single llama token into bytes
  89. /// </summary>
  90. /// <param name="llama_token">Token to decode</param>
  91. /// <param name="dest">A span to attempt to write into. If this is too small nothing will be written</param>
  92. /// <returns>The size of this token. **nothing will be written** if this is larger than `dest`</returns>
  93. public int TokenToSpan(int llama_token, Span<byte> dest)
  94. {
  95. unsafe
  96. {
  97. fixed (byte* destPtr = dest)
  98. {
  99. var length = NativeApi.llama_token_to_piece(this, llama_token, destPtr, dest.Length);
  100. return Math.Abs(length);
  101. }
  102. }
  103. }
  104. /// <summary>
  105. /// Convert a sequence of tokens into characters.
  106. /// </summary>
  107. /// <param name="tokens"></param>
  108. /// <param name="dest"></param>
  109. /// <param name="encoding"></param>
  110. /// <returns>The section of the span which has valid data in it.
  111. /// If there was insufficient space in the output span this will be
  112. /// filled with as many characters as possible, starting from the _last_ token.
  113. /// </returns>
  114. [Obsolete("Use a StreamingTokenDecoder instead")]
  115. internal Span<char> TokensToSpan(IReadOnlyList<int> tokens, Span<char> dest, Encoding encoding)
  116. {
  117. var decoder = new StreamingTokenDecoder(encoding, this);
  118. foreach (var token in tokens)
  119. decoder.Add(token);
  120. var str = decoder.Read();
  121. if (str.Length < dest.Length)
  122. {
  123. str.AsSpan().CopyTo(dest);
  124. return dest.Slice(0, str.Length);
  125. }
  126. else
  127. {
  128. str.AsSpan().Slice(str.Length - dest.Length).CopyTo(dest);
  129. return dest;
  130. }
  131. }
  132. /// <summary>
  133. /// Convert a string of text into tokens
  134. /// </summary>
  135. /// <param name="text"></param>
  136. /// <param name="add_bos"></param>
  137. /// <param name="encoding"></param>
  138. /// <param name="special">Allow tokenizing special and/or control tokens which otherwise are not exposed and treated as plaintext.</param>
  139. /// <returns></returns>
  140. public int[] Tokenize(string text, bool add_bos, bool special, Encoding encoding)
  141. {
  142. // Convert string to bytes, adding one extra byte to the end (null terminator)
  143. var bytesCount = encoding.GetByteCount(text);
  144. var bytes = new byte[bytesCount + 1];
  145. unsafe
  146. {
  147. fixed (char* charPtr = text)
  148. fixed (byte* bytePtr = &bytes[0])
  149. {
  150. encoding.GetBytes(charPtr, text.Length, bytePtr, bytes.Length);
  151. }
  152. }
  153. unsafe
  154. {
  155. fixed (byte* bytesPtr = &bytes[0])
  156. {
  157. // Tokenize once with no output, to get the token count. Output will be negative (indicating that there was insufficient space)
  158. var count = -NativeApi.llama_tokenize(this, bytesPtr, bytesCount, (int*)IntPtr.Zero, 0, add_bos, special);
  159. // Tokenize again, this time outputting into an array of exactly the right size
  160. var tokens = new int[count];
  161. fixed (int* tokensPtr = &tokens[0])
  162. {
  163. NativeApi.llama_tokenize(this, bytesPtr, bytesCount, tokensPtr, count, add_bos, special);
  164. return tokens;
  165. }
  166. }
  167. }
  168. }
  169. #endregion
  170. #region context
  171. /// <summary>
  172. /// Create a new context for this model
  173. /// </summary>
  174. /// <param name="params"></param>
  175. /// <returns></returns>
  176. public SafeLLamaContextHandle CreateContext(LLamaContextParams @params)
  177. {
  178. return SafeLLamaContextHandle.Create(this, @params);
  179. }
  180. #endregion
  181. }
  182. }