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

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