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.

LLamaExecutorBase.cs 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. using LLama.Common;
  2. using LLama.Exceptions;
  3. using LLama.Native;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Runtime.CompilerServices;
  9. using System.Text.Json.Serialization;
  10. using System.Threading;
  11. namespace LLama
  12. {
  13. using llama_token = Int32;
  14. public abstract class StatefulExecutorBase : ILLamaExecutor
  15. {
  16. protected readonly LLamaModel _model;
  17. protected ILLamaLogger? _logger;
  18. protected int _pastTokensCount; // n_past
  19. protected int _consumedTokensCount; // n_consume
  20. protected int _n_session_consumed;
  21. protected int _n_matching_session_tokens;
  22. protected string? _pathSession;
  23. protected List<llama_token> _embeds = new(); // embd
  24. protected List<llama_token> _embed_inps = new();
  25. protected List<llama_token> _session_tokens = new();
  26. protected FixedSizeQuene<llama_token> _last_n_tokens;
  27. public LLamaModel Model => _model;
  28. protected StatefulExecutorBase(LLamaModel model, ILLamaLogger? logger = null)
  29. {
  30. _model = model;
  31. _logger = logger;
  32. _pastTokensCount = 0;
  33. _consumedTokensCount = 0;
  34. _n_session_consumed = 0;
  35. _embeds = new();
  36. _embed_inps = new();
  37. _last_n_tokens = new FixedSizeQuene<llama_token>(_model.ContextSize).FillWith(0);
  38. }
  39. public unsafe StatefulExecutorBase WithSessionFile(string filename)
  40. {
  41. _pathSession = filename;
  42. if (string.IsNullOrEmpty(filename))
  43. {
  44. throw new ArgumentNullException("File name cannot be empty.");
  45. }
  46. if (File.Exists(filename))
  47. {
  48. _logger?.Log("LLamaExecutor", $"Attempting to load saved session from {filename}", ILLamaLogger.LogLevel.Info);
  49. llama_token[] session_tokens = new llama_token[_model.ContextSize];
  50. ulong n_token_count_out = 0;
  51. if (!NativeApi.llama_load_session_file(_model.NativeHandle, _pathSession, session_tokens, (ulong)_model.ContextSize, &n_token_count_out))
  52. {
  53. _logger?.Log("LLamaExecutor", $"Failed to load session file {filename}", ILLamaLogger.LogLevel.Error);
  54. throw new RuntimeError($"Failed to load session file {_pathSession}");
  55. }
  56. _session_tokens = session_tokens.Take((int)n_token_count_out).ToList();
  57. _logger?.Log("LLamaExecutor", $"Loaded a session with prompt size of {session_tokens.Length} tokens", ILLamaLogger.LogLevel.Info);
  58. }
  59. else
  60. {
  61. _logger?.Log("LLamaExecutor", $"Session file does not exist, will create", ILLamaLogger.LogLevel.Warning);
  62. }
  63. _n_matching_session_tokens = 0;
  64. if (_session_tokens.Count > 0)
  65. {
  66. foreach (var id in _session_tokens)
  67. {
  68. if (_n_matching_session_tokens >= _embed_inps.Count || id != _embed_inps[_n_matching_session_tokens])
  69. {
  70. break;
  71. }
  72. _n_matching_session_tokens++;
  73. }
  74. if (_n_matching_session_tokens >= _embed_inps.Count)
  75. {
  76. _logger?.Log("LLamaExecutor", $"Session file has exact match for prompt!", ILLamaLogger.LogLevel.Info);
  77. }
  78. else if (_n_matching_session_tokens < _embed_inps.Count / 2)
  79. {
  80. _logger?.Log("LLamaExecutor", $"session file has low similarity to prompt ({_n_matching_session_tokens}" +
  81. $" / {_embed_inps.Count} tokens); will mostly be reevaluated", ILLamaLogger.LogLevel.Warning);
  82. }
  83. else
  84. {
  85. _logger?.Log("LLamaExecutor", $"Session file matches {_n_matching_session_tokens} / " +
  86. $"{_embed_inps.Count} tokens of prompt", ILLamaLogger.LogLevel.Info);
  87. }
  88. }
  89. return this;
  90. }
  91. public void SaveSessionFile(string filename)
  92. {
  93. var session_token_array = _session_tokens.ToArray();
  94. NativeApi.llama_save_session_file(_model.NativeHandle, filename, session_token_array, (ulong)session_token_array.Length);
  95. }
  96. protected virtual void HandleRunOutOfContext(int tokensToKeep)
  97. {
  98. // if we run out of context:
  99. // - take the tokensToKeep first tokens from the original prompt (via n_past)
  100. // - take half of the last (n_ctx - tokensToKeep) tokens and recompute the logits in batches
  101. int n_left = _pastTokensCount - tokensToKeep;
  102. _pastTokensCount = Math.Max(1, tokensToKeep);
  103. // insert n_left/2 tokens at the start of embed from last_n_tokens
  104. _embeds.InsertRange(0, _last_n_tokens.Take(_last_n_tokens.Count - _embeds.Count).Skip(_model.ContextSize - n_left / 2 - _embeds.Count));
  105. // stop saving session if we run out of context
  106. _pathSession = string.Empty;
  107. }
  108. protected virtual void TryReuseMathingPrefix()
  109. {
  110. if (_n_session_consumed < _session_tokens.Count)
  111. {
  112. int i = 0;
  113. for (; i < _embeds.Count; i++)
  114. {
  115. if (_embeds[i] != _session_tokens[_n_session_consumed])
  116. {
  117. _session_tokens = _session_tokens.Take(_n_session_consumed).ToList();
  118. break;
  119. }
  120. _pastTokensCount++;
  121. _n_session_consumed++;
  122. if (_n_session_consumed >= _session_tokens.Count)
  123. {
  124. i++;
  125. break;
  126. }
  127. }
  128. if (i > 0)
  129. {
  130. _embeds.RemoveRange(0, i);
  131. }
  132. }
  133. }
  134. protected abstract bool GetLoopCondition(InferStateArgs args);
  135. protected abstract void PreprocessInputs(string text, InferStateArgs args);
  136. protected abstract bool PostProcess(InferenceParams inferenceParams, InferStateArgs args, out IEnumerable<string>? extraOutputs);
  137. protected abstract void InferInternal(InferenceParams inferenceParams, InferStateArgs args);
  138. public abstract void SaveState(string filename);
  139. public abstract void LoadState(string filename);
  140. public virtual IEnumerable<string> Infer(string text, InferenceParams? inferenceParams = null, CancellationToken cancellationToken = default)
  141. {
  142. cancellationToken.ThrowIfCancellationRequested();
  143. if (inferenceParams is null)
  144. {
  145. inferenceParams = new InferenceParams();
  146. }
  147. InferStateArgs args = new InferStateArgs()
  148. {
  149. Antiprompts = inferenceParams.AntiPrompts.ToList(),
  150. RemainedTokens = inferenceParams.MaxTokens,
  151. ReturnValue = false,
  152. WaitForInput = false,
  153. NeedToSaveSession = !string.IsNullOrEmpty(_pathSession) && _n_matching_session_tokens < _embed_inps.Count
  154. };
  155. PreprocessInputs(text, args);
  156. while (GetLoopCondition(args))
  157. {
  158. if (cancellationToken.IsCancellationRequested)
  159. {
  160. break;
  161. }
  162. InferInternal(inferenceParams, args);
  163. if (args.ReturnValue)
  164. {
  165. foreach (var item in _model.GenerateResult(_embeds))
  166. {
  167. yield return item;
  168. }
  169. }
  170. var breakGeneration = PostProcess(inferenceParams, args, out var extraOutputs);
  171. if (extraOutputs is not null)
  172. {
  173. foreach (var item in extraOutputs)
  174. {
  175. yield return item;
  176. }
  177. }
  178. if (breakGeneration)
  179. {
  180. break;
  181. }
  182. }
  183. }
  184. public virtual async IAsyncEnumerable<string> InferAsync(string text, InferenceParams? inferenceParams = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
  185. {
  186. foreach (var result in Infer(text, inferenceParams, cancellationToken))
  187. {
  188. yield return result;
  189. }
  190. }
  191. /// <summary>
  192. /// State arguments that are used in single inference
  193. /// </summary>
  194. protected class InferStateArgs
  195. {
  196. public IList<string>? Antiprompts { get; set; }
  197. /// <summary>
  198. /// Tokens count remained to be used. (n_remain)
  199. /// </summary>
  200. public int RemainedTokens { get; set; }
  201. public bool ReturnValue { get; set; }
  202. public bool WaitForInput { get; set; }
  203. public bool NeedToSaveSession { get; set; }
  204. }
  205. public class ExecutorBaseState
  206. {
  207. [JsonPropertyName("n_past")]
  208. public int PastTokensCount { get; set; }
  209. [JsonPropertyName("n_consumed")]
  210. public int ConsumedTokensCount { get; set; }
  211. [JsonPropertyName("n_session_consumed")]
  212. public int ConsumedSessionCount { get; set; }
  213. [JsonPropertyName("n_matching_session_tokens")]
  214. public int MatchingSessionTokensCount { get; set; }
  215. [JsonPropertyName("path_session")]
  216. public string SessionFilePath { get; set; }
  217. [JsonPropertyName("embd")]
  218. public List<llama_token> Embeds { get; set; }
  219. [JsonPropertyName("embd_inps")]
  220. public List<llama_token> EmbedInps { get; set; }
  221. [JsonPropertyName("session_tokens")]
  222. public List<llama_token> SessionTokens { get; set; }
  223. [JsonPropertyName("last_n_tokens")]
  224. public llama_token[] LastTokens { get; set; }
  225. [JsonPropertyName("last_tokens_maximum_count")]
  226. public int LastTokensCapacity { get; set; }
  227. }
  228. }
  229. }

C#/.NET上易用的LLM高性能推理框架,支持LLaMA和LLaVA系列模型。