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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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 => ThrowIfDisposed().ContextSize;
  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. // Decrement refcount on model
  52. _model?.DangerousRelease();
  53. _model = null!;
  54. NativeApi.llama_free(handle);
  55. SetHandle(IntPtr.Zero);
  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. /// Convert the given text into tokens
  83. /// </summary>
  84. /// <param name="text">The text to tokenize</param>
  85. /// <param name="add_bos">Whether the "BOS" token should be added</param>
  86. /// <param name="encoding">Encoding to use for the text</param>
  87. /// <returns></returns>
  88. /// <exception cref="RuntimeError"></exception>
  89. public int[] Tokenize(string text, bool add_bos, Encoding encoding)
  90. {
  91. ThrowIfDisposed();
  92. // Calculate number of bytes in string, this is a pessimistic estimate of token count. It can't
  93. // possibly be more than this.
  94. var count = encoding.GetByteCount(text) + (add_bos ? 1 : 0);
  95. // "Rent" an array to write results into (avoiding an allocation of a large array)
  96. var temporaryArray = ArrayPool<int>.Shared.Rent(count);
  97. try
  98. {
  99. // Do the actual conversion
  100. var n = NativeApi.llama_tokenize(this, text, encoding, temporaryArray, count, add_bos);
  101. if (n < 0)
  102. {
  103. throw new RuntimeError("Error happened during tokenization. It's possibly caused by wrong encoding. Please try to " +
  104. "specify the encoding.");
  105. }
  106. // Copy the results from the rented into an array which is exactly the right size
  107. var result = new int[n];
  108. Array.ConstrainedCopy(temporaryArray, 0, result, 0, n);
  109. return result;
  110. }
  111. finally
  112. {
  113. ArrayPool<int>.Shared.Return(temporaryArray);
  114. }
  115. }
  116. /// <summary>
  117. /// Token logits obtained from the last call to llama_eval()
  118. /// The logits for the last token are stored in the last row
  119. /// Can be mutated in order to change the probabilities of the next token.<br />
  120. /// Rows: n_tokens<br />
  121. /// Cols: n_vocab
  122. /// </summary>
  123. /// <returns></returns>
  124. public Span<float> GetLogits()
  125. {
  126. var model = ThrowIfDisposed();
  127. unsafe
  128. {
  129. var logits = NativeApi.llama_get_logits(this);
  130. return new Span<float>(logits, model.VocabCount);
  131. }
  132. }
  133. /// <summary>
  134. /// Convert a token into a string
  135. /// </summary>
  136. /// <param name="token"></param>
  137. /// <param name="encoding"></param>
  138. /// <returns></returns>
  139. public string TokenToString(int token, Encoding encoding)
  140. {
  141. return ThrowIfDisposed().TokenToString(token, encoding);
  142. }
  143. /// <summary>
  144. /// Convert a token into a span of bytes that could be decoded into a string
  145. /// </summary>
  146. /// <param name="token"></param>
  147. /// <returns></returns>
  148. public ReadOnlySpan<byte> TokenToSpan(int token)
  149. {
  150. return ThrowIfDisposed().TokenToSpan(token);
  151. }
  152. /// <summary>
  153. /// Run the llama inference to obtain the logits and probabilities for the next token.
  154. /// </summary>
  155. /// <param name="tokens">The provided batch of new tokens to process</param>
  156. /// <param name="n_past">the number of tokens to use from previous eval calls</param>
  157. /// <param name="n_threads"></param>
  158. /// <returns>Returns true on success</returns>
  159. public bool Eval(ReadOnlySpan<int> tokens, int n_past, int n_threads)
  160. {
  161. unsafe
  162. {
  163. fixed (int* pinned = tokens)
  164. {
  165. return NativeApi.llama_eval_with_pointer(this, pinned, tokens.Length, n_past, n_threads) == 0;
  166. }
  167. }
  168. }
  169. }
  170. }