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.

SafeLLamaContextHandle.cs 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. using System;
  2. using System.Buffers;
  3. using System.Text;
  4. using LLama.Exceptions;
  5. namespace LLama.Native
  6. {
  7. /// <summary>
  8. /// A safe wrapper around a llama_context
  9. /// </summary>
  10. public sealed class SafeLLamaContextHandle
  11. : SafeLLamaHandleBase
  12. {
  13. #region properties and fields
  14. /// <summary>
  15. /// Total number of tokens in vocabulary of this model
  16. /// </summary>
  17. public int VocabCount => ThrowIfDisposed().VocabCount;
  18. /// <summary>
  19. /// Total number of tokens in the context
  20. /// </summary>
  21. public int ContextSize => NativeApi.llama_n_ctx(this);
  22. /// <summary>
  23. /// Dimension of embedding vectors
  24. /// </summary>
  25. public int EmbeddingSize => ThrowIfDisposed().EmbeddingSize;
  26. /// <summary>
  27. /// Get the model which this context is using
  28. /// </summary>
  29. public SafeLlamaModelHandle ModelHandle => ThrowIfDisposed();
  30. private SafeLlamaModelHandle? _model;
  31. #endregion
  32. #region construction/destruction
  33. /// <summary>
  34. /// Create a new SafeLLamaContextHandle
  35. /// </summary>
  36. /// <param name="handle">pointer to an allocated llama_context</param>
  37. /// <param name="model">the model which this context was created from</param>
  38. public SafeLLamaContextHandle(IntPtr handle, SafeLlamaModelHandle model)
  39. : base(handle)
  40. {
  41. // Increment the model reference count while this context exists
  42. _model = model;
  43. var success = false;
  44. _model.DangerousAddRef(ref success);
  45. if (!success)
  46. throw new RuntimeError("Failed to increment model refcount");
  47. }
  48. /// <inheritdoc />
  49. protected override bool ReleaseHandle()
  50. {
  51. NativeApi.llama_free(DangerousGetHandle());
  52. SetHandle(IntPtr.Zero);
  53. // Decrement refcount on model
  54. _model?.DangerousRelease();
  55. _model = null!;
  56. return true;
  57. }
  58. private SafeLlamaModelHandle ThrowIfDisposed()
  59. {
  60. if (IsClosed)
  61. throw new ObjectDisposedException("Cannot use this `SafeLLamaContextHandle` - it has been disposed");
  62. if (_model == null || _model.IsClosed)
  63. throw new ObjectDisposedException("Cannot use this `SafeLLamaContextHandle` - `SafeLlamaModelHandle` has been disposed");
  64. return _model!;
  65. }
  66. /// <summary>
  67. /// Create a new llama_state for the given model
  68. /// </summary>
  69. /// <param name="model"></param>
  70. /// <param name="lparams"></param>
  71. /// <returns></returns>
  72. /// <exception cref="RuntimeError"></exception>
  73. public static SafeLLamaContextHandle Create(SafeLlamaModelHandle model, LLamaContextParams lparams)
  74. {
  75. var ctx_ptr = NativeApi.llama_new_context_with_model(model, lparams);
  76. if (ctx_ptr == IntPtr.Zero)
  77. throw new RuntimeError("Failed to create context from model");
  78. return new(ctx_ptr, model);
  79. }
  80. #endregion
  81. /// <summary>
  82. /// Token logits obtained from the last call to llama_eval()
  83. /// The logits for the last token are stored in the last row
  84. /// Can be mutated in order to change the probabilities of the next token.<br />
  85. /// Rows: n_tokens<br />
  86. /// Cols: n_vocab
  87. /// </summary>
  88. /// <returns></returns>
  89. public Span<float> GetLogits()
  90. {
  91. var model = ThrowIfDisposed();
  92. unsafe
  93. {
  94. var logits = NativeApi.llama_get_logits(this);
  95. return new Span<float>(logits, model.VocabCount);
  96. }
  97. }
  98. #region tokens
  99. /// <summary>
  100. /// Convert the given text into tokens
  101. /// </summary>
  102. /// <param name="text">The text to tokenize</param>
  103. /// <param name="add_bos">Whether the "BOS" token should be added</param>
  104. /// <param name="encoding">Encoding to use for the text</param>
  105. /// <param name="special">Allow tokenizing special and/or control tokens which otherwise are not exposed and treated as plaintext.</param>
  106. /// <returns></returns>
  107. /// <exception cref="RuntimeError"></exception>
  108. public int[] Tokenize(string text, bool add_bos, bool special, Encoding encoding)
  109. {
  110. ThrowIfDisposed();
  111. if (string.IsNullOrEmpty(text) && !add_bos)
  112. return Array.Empty<int>();
  113. // Calculate number of bytes in string, this is a pessimistic estimate of token count. It can't
  114. // possibly be more than this.
  115. var count = encoding.GetByteCount(text) + (add_bos ? 1 : 0);
  116. // "Rent" an array to write results into (avoiding an allocation of a large array)
  117. var temporaryArray = ArrayPool<int>.Shared.Rent(count);
  118. try
  119. {
  120. // Do the actual conversion
  121. var n = NativeApi.llama_tokenize(this, text, encoding, temporaryArray, count, add_bos, special);
  122. if (n < 0)
  123. {
  124. throw new RuntimeError("Error happened during tokenization. It's possibly caused by wrong encoding. Please try to " +
  125. "specify the encoding.");
  126. }
  127. // Copy the results from the rented into an array which is exactly the right size
  128. var result = new int[n];
  129. Array.ConstrainedCopy(temporaryArray, 0, result, 0, n);
  130. return result;
  131. }
  132. finally
  133. {
  134. ArrayPool<int>.Shared.Return(temporaryArray);
  135. }
  136. }
  137. /// <summary>
  138. /// Convert a token into a string
  139. /// </summary>
  140. /// <param name="token">Token to decode into a string</param>
  141. /// <param name="encoding"></param>
  142. /// <returns></returns>
  143. public string TokenToString(int token, Encoding encoding)
  144. {
  145. return ThrowIfDisposed().TokenToString(token, encoding);
  146. }
  147. /// <summary>
  148. /// Append a single llama token to a string builder
  149. /// </summary>
  150. /// <param name="token">Token to decode</param>
  151. /// <param name="encoding"></param>
  152. /// <param name="dest">string builder to append the result to</param>
  153. public void TokenToString(int token, Encoding encoding, StringBuilder dest)
  154. {
  155. ThrowIfDisposed().TokenToString(token, encoding, dest);
  156. }
  157. /// <summary>
  158. /// Convert a single llama token into bytes
  159. /// </summary>
  160. /// <param name="token">Token to decode</param>
  161. /// <param name="dest">A span to attempt to write into. If this is too small nothing will be written</param>
  162. /// <returns>The size of this token. **nothing will be written** if this is larger than `dest`</returns>
  163. public int TokenToSpan(int token, Span<byte> dest)
  164. {
  165. return ThrowIfDisposed().TokenToSpan(token, dest);
  166. }
  167. #endregion
  168. /// <summary>
  169. /// Run the llama inference to obtain the logits and probabilities for the next token.
  170. /// </summary>
  171. /// <param name="tokens">The provided batch of new tokens to process</param>
  172. /// <param name="n_past">the number of tokens to use from previous eval calls</param>
  173. /// <returns>Returns true on success</returns>
  174. public bool Eval(ReadOnlySpan<int> tokens, int n_past)
  175. {
  176. unsafe
  177. {
  178. fixed (int* pinned = tokens)
  179. {
  180. // the entire `eval` system needs replacing with the new batch system!
  181. var ret = NativeApi.llama_eval(this, pinned, tokens.Length, n_past);
  182. return ret == 0;
  183. }
  184. }
  185. }
  186. /// <summary>
  187. /// </summary>
  188. /// <param name="batch"></param>
  189. /// <returns>Positive return values does not mean a fatal error, but rather a warning:<br />
  190. /// - 0: success<br />
  191. /// - 1: could not find a KV slot for the batch (try reducing the size of the batch or increase the context)<br />
  192. /// - &lt; 0: error<br />
  193. /// </returns>
  194. public int Decode(LLamaBatchSafeHandle batch)
  195. {
  196. return NativeApi.llama_decode(this, batch.NativeBatch);
  197. }
  198. #region state
  199. /// <summary>
  200. /// Get the size of the state, when saved as bytes
  201. /// </summary>
  202. public ulong GetStateSize()
  203. {
  204. return NativeApi.llama_get_state_size(this);
  205. }
  206. /// <summary>
  207. /// Get the raw state of this context, encoded as bytes. Data is written into the `dest` pointer.
  208. /// </summary>
  209. /// <param name="dest">Destination to write to</param>
  210. /// <param name="size">Number of bytes available to write to in dest (check required size with `GetStateSize()`)</param>
  211. /// <returns>The number of bytes written to dest</returns>
  212. /// <exception cref="ArgumentOutOfRangeException">Thrown if dest is too small</exception>
  213. public unsafe ulong GetState(byte* dest, ulong size)
  214. {
  215. return GetState(new IntPtr(dest), size);
  216. }
  217. /// <summary>
  218. /// Get the raw state of this context, encoded as bytes. Data is written into the `dest` pointer.
  219. /// </summary>
  220. /// <param name="dest">Destination to write to</param>
  221. /// <param name="size">Number of bytes available to write to in dest (check required size with `GetStateSize()`)</param>
  222. /// <returns>The number of bytes written to dest</returns>
  223. /// <exception cref="ArgumentOutOfRangeException">Thrown if dest is too small</exception>
  224. public ulong GetState(IntPtr dest, ulong size)
  225. {
  226. var required = GetStateSize();
  227. if (size < required)
  228. throw new ArgumentOutOfRangeException(nameof(size), $"Allocated space is too small, {size} < {required}");
  229. unsafe
  230. {
  231. return NativeApi.llama_copy_state_data(this, (byte*)dest.ToPointer());
  232. }
  233. }
  234. /// <summary>
  235. /// Set the raw state of this context
  236. /// </summary>
  237. /// <param name="src">The pointer to read the state from</param>
  238. /// <returns>Number of bytes read from the src pointer</returns>
  239. public unsafe ulong SetState(byte* src)
  240. {
  241. return SetState(new IntPtr(src));
  242. }
  243. /// <summary>
  244. /// Set the raw state of this context
  245. /// </summary>
  246. /// <param name="src">The pointer to read the state from</param>
  247. /// <returns>Number of bytes read from the src pointer</returns>
  248. public ulong SetState(IntPtr src)
  249. {
  250. unsafe
  251. {
  252. return NativeApi.llama_set_state_data(this, (byte*)src.ToPointer());
  253. }
  254. }
  255. #endregion
  256. }
  257. }