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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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">Token to decode into a string</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. /// Append a single llama token to a string builder
  171. /// </summary>
  172. /// <param name="token">Token to decode</param>
  173. /// <param name="encoding"></param>
  174. /// <param name="dest">string builder to append the result to</param>
  175. public void TokenToString(int token, Encoding encoding, StringBuilder dest)
  176. {
  177. ThrowIfDisposed().TokenToString(token, encoding, dest);
  178. }
  179. /// <summary>
  180. /// Convert a single llama token into bytes
  181. /// </summary>
  182. /// <param name="token">Token to decode</param>
  183. /// <param name="dest">A span to attempt to write into. If this is too small nothing will be written</param>
  184. /// <returns>The size of this token. **nothing will be written** if this is larger than `dest`</returns>
  185. public int TokenToSpan(int token, Span<byte> dest)
  186. {
  187. return ThrowIfDisposed().TokenToSpan(token, dest);
  188. }
  189. /// <summary>
  190. /// Run the llama inference to obtain the logits and probabilities for the next token.
  191. /// </summary>
  192. /// <param name="tokens">The provided batch of new tokens to process</param>
  193. /// <param name="n_past">the number of tokens to use from previous eval calls</param>
  194. /// <param name="n_threads"></param>
  195. /// <returns>Returns true on success</returns>
  196. public bool Eval(ReadOnlySpan<int> tokens, int n_past, int n_threads)
  197. {
  198. unsafe
  199. {
  200. fixed (int* pinned = tokens)
  201. {
  202. return NativeApi.llama_eval_with_pointer(this, pinned, tokens.Length, n_past, n_threads) == 0;
  203. }
  204. }
  205. }
  206. #region state
  207. /// <summary>
  208. /// Get the size of the state, when saved as bytes
  209. /// </summary>
  210. public ulong GetStateSize()
  211. {
  212. return NativeApi.llama_get_state_size(this);
  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 unsafe ulong GetState(byte* dest, ulong size)
  222. {
  223. return GetState(new IntPtr(dest), size);
  224. }
  225. /// <summary>
  226. /// Get the raw state of this context, encoded as bytes. Data is written into the `dest` pointer.
  227. /// </summary>
  228. /// <param name="dest">Destination to write to</param>
  229. /// <param name="size">Number of bytes available to write to in dest (check required size with `GetStateSize()`)</param>
  230. /// <returns>The number of bytes written to dest</returns>
  231. /// <exception cref="ArgumentOutOfRangeException">Thrown if dest is too small</exception>
  232. public ulong GetState(IntPtr dest, ulong size)
  233. {
  234. var required = GetStateSize();
  235. if (size < required)
  236. throw new ArgumentOutOfRangeException(nameof(size), $"Allocated space is too small, {size} < {required}");
  237. unsafe
  238. {
  239. return NativeApi.llama_copy_state_data(this, (byte*)dest.ToPointer());
  240. }
  241. }
  242. /// <summary>
  243. /// Set the raw state of this context
  244. /// </summary>
  245. /// <param name="src">The pointer to read the state from</param>
  246. /// <returns>Number of bytes read from the src pointer</returns>
  247. public unsafe ulong SetState(byte* src)
  248. {
  249. return SetState(new IntPtr(src));
  250. }
  251. /// <summary>
  252. /// Set the raw state of this context
  253. /// </summary>
  254. /// <param name="src">The pointer to read the state from</param>
  255. /// <returns>Number of bytes read from the src pointer</returns>
  256. public ulong SetState(IntPtr src)
  257. {
  258. unsafe
  259. {
  260. return NativeApi.llama_set_state_data(this, (byte*)src.ToPointer());
  261. }
  262. }
  263. #endregion
  264. }
  265. }