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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. using LLama.Abstractions;
  2. using LLama.Common;
  3. using LLama.Exceptions;
  4. using LLama.Native;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Runtime.CompilerServices;
  10. using System.Text.Json.Serialization;
  11. using System.Threading;
  12. namespace LLama
  13. {
  14. using llama_token = Int32;
  15. /// <summary>
  16. /// The base class for stateful LLama executors.
  17. /// </summary>
  18. public abstract class StatefulExecutorBase : ILLamaExecutor
  19. {
  20. /// <summary>
  21. /// The logger used by this executor.
  22. /// </summary>
  23. protected ILLamaLogger? _logger;
  24. /// <summary>
  25. /// The tokens that were already processed by the model.
  26. /// </summary>
  27. protected int _pastTokensCount; // n_past
  28. /// <summary>
  29. /// The tokens that were consumed by the model during the current inference.
  30. /// </summary>
  31. protected int _consumedTokensCount; // n_consume
  32. /// <summary>
  33. ///
  34. /// </summary>
  35. protected int _n_session_consumed;
  36. /// <summary>
  37. ///
  38. /// </summary>
  39. protected int _n_matching_session_tokens;
  40. /// <summary>
  41. /// The path of the session file.
  42. /// </summary>
  43. protected string? _pathSession;
  44. /// <summary>
  45. /// A container of the tokens to be processed and after processed.
  46. /// </summary>
  47. protected List<llama_token> _embeds = new(); // embd
  48. /// <summary>
  49. /// A container for the tokens of input.
  50. /// </summary>
  51. protected List<llama_token> _embed_inps = new();
  52. /// <summary>
  53. ///
  54. /// </summary>
  55. protected List<llama_token> _session_tokens = new();
  56. /// <summary>
  57. /// The last tokens generated by the model.
  58. /// </summary>
  59. protected FixedSizeQueue<llama_token> _last_n_tokens;
  60. /// <summary>
  61. /// The context used by the executor.
  62. /// </summary>
  63. public LLamaContext Context { get; }
  64. /// <summary>
  65. /// Current "mu" value for mirostat sampling
  66. /// </summary>
  67. protected float? MirostatMu { get; set; }
  68. /// <summary>
  69. ///
  70. /// </summary>
  71. /// <param name="context"></param>
  72. /// <param name="logger"></param>
  73. protected StatefulExecutorBase(LLamaContext context, ILLamaLogger? logger = null)
  74. {
  75. Context = context;
  76. _logger = logger;
  77. _pastTokensCount = 0;
  78. _consumedTokensCount = 0;
  79. _n_session_consumed = 0;
  80. _last_n_tokens = new FixedSizeQueue<llama_token>(Context.ContextSize).FillWith(0);
  81. }
  82. /// <summary>
  83. /// This API is currently not verified.
  84. /// </summary>
  85. /// <param name="filename"></param>
  86. /// <returns></returns>
  87. /// <exception cref="ArgumentNullException"></exception>
  88. /// <exception cref="RuntimeError"></exception>
  89. public unsafe StatefulExecutorBase WithSessionFile(string filename)
  90. {
  91. _pathSession = filename;
  92. if (string.IsNullOrEmpty(filename))
  93. {
  94. throw new ArgumentNullException(nameof(filename), "File name cannot be empty.");
  95. }
  96. if (File.Exists(filename))
  97. {
  98. _logger?.Log("LLamaExecutor", $"Attempting to load saved session from {filename}", ILLamaLogger.LogLevel.Info);
  99. llama_token[] session_tokens = new llama_token[Context.ContextSize];
  100. ulong n_token_count_out = 0;
  101. if (!NativeApi.llama_load_session_file(Context.NativeHandle, _pathSession, session_tokens, (ulong)Context.ContextSize, &n_token_count_out))
  102. {
  103. _logger?.Log("LLamaExecutor", $"Failed to load session file {filename}", ILLamaLogger.LogLevel.Error);
  104. throw new RuntimeError($"Failed to load session file {_pathSession}");
  105. }
  106. _session_tokens = session_tokens.Take((int)n_token_count_out).ToList();
  107. _logger?.Log("LLamaExecutor", $"Loaded a session with prompt size of {session_tokens.Length} tokens", ILLamaLogger.LogLevel.Info);
  108. }
  109. else
  110. {
  111. _logger?.Log("LLamaExecutor", $"Session file does not exist, will create", ILLamaLogger.LogLevel.Warning);
  112. }
  113. _n_matching_session_tokens = 0;
  114. if (_session_tokens.Count > 0)
  115. {
  116. foreach (var id in _session_tokens)
  117. {
  118. if (_n_matching_session_tokens >= _embed_inps.Count || id != _embed_inps[_n_matching_session_tokens])
  119. {
  120. break;
  121. }
  122. _n_matching_session_tokens++;
  123. }
  124. if (_n_matching_session_tokens >= _embed_inps.Count)
  125. {
  126. _logger?.Log("LLamaExecutor", $"Session file has exact match for prompt!", ILLamaLogger.LogLevel.Info);
  127. }
  128. else if (_n_matching_session_tokens < _embed_inps.Count / 2)
  129. {
  130. _logger?.Log("LLamaExecutor", $"session file has low similarity to prompt ({_n_matching_session_tokens}" +
  131. $" / {_embed_inps.Count} tokens); will mostly be reevaluated", ILLamaLogger.LogLevel.Warning);
  132. }
  133. else
  134. {
  135. _logger?.Log("LLamaExecutor", $"Session file matches {_n_matching_session_tokens} / " +
  136. $"{_embed_inps.Count} tokens of prompt", ILLamaLogger.LogLevel.Info);
  137. }
  138. }
  139. return this;
  140. }
  141. /// <summary>
  142. /// This API has not been verified currently.
  143. /// </summary>
  144. /// <param name="filename"></param>
  145. public void SaveSessionFile(string filename)
  146. {
  147. var session_token_array = _session_tokens.ToArray();
  148. NativeApi.llama_save_session_file(Context.NativeHandle, filename, session_token_array, (ulong)session_token_array.Length);
  149. }
  150. /// <summary>
  151. /// After running out of the context, take some tokens from the original prompt and recompute the logits in batches.
  152. /// </summary>
  153. /// <param name="tokensToKeep"></param>
  154. protected virtual void HandleRunOutOfContext(int tokensToKeep)
  155. {
  156. // if we run out of context:
  157. // - take the tokensToKeep first tokens from the original prompt (via n_past)
  158. // - take half of the last (n_ctx - tokensToKeep) tokens and recompute the logits in batches
  159. int n_left = _pastTokensCount - tokensToKeep;
  160. _pastTokensCount = Math.Max(1, tokensToKeep);
  161. // insert n_left/2 tokens at the start of embed from last_n_tokens
  162. _embeds.InsertRange(0, _last_n_tokens.Take(_last_n_tokens.Count - _embeds.Count).Skip(Context.ContextSize - n_left / 2 - _embeds.Count));
  163. // stop saving session if we run out of context
  164. _pathSession = string.Empty;
  165. }
  166. /// <summary>
  167. /// Try to reuse the matching prefix from the session file.
  168. /// </summary>
  169. protected virtual void TryReuseMathingPrefix()
  170. {
  171. if (_n_session_consumed < _session_tokens.Count)
  172. {
  173. int i = 0;
  174. for (; i < _embeds.Count; i++)
  175. {
  176. if (_embeds[i] != _session_tokens[_n_session_consumed])
  177. {
  178. _session_tokens = _session_tokens.Take(_n_session_consumed).ToList();
  179. break;
  180. }
  181. _pastTokensCount++;
  182. _n_session_consumed++;
  183. if (_n_session_consumed >= _session_tokens.Count)
  184. {
  185. i++;
  186. break;
  187. }
  188. }
  189. if (i > 0)
  190. {
  191. _embeds.RemoveRange(0, i);
  192. }
  193. }
  194. }
  195. /// <summary>
  196. /// Decide whether to continue the loop.
  197. /// </summary>
  198. /// <param name="args"></param>
  199. /// <returns></returns>
  200. protected abstract bool GetLoopCondition(InferStateArgs args);
  201. /// <summary>
  202. /// Preprocess the inputs before the inference.
  203. /// </summary>
  204. /// <param name="text"></param>
  205. /// <param name="args"></param>
  206. protected abstract void PreprocessInputs(string text, InferStateArgs args);
  207. /// <summary>
  208. /// Do some post processing after the inference.
  209. /// </summary>
  210. /// <param name="inferenceParams"></param>
  211. /// <param name="args"></param>
  212. /// <param name="extraOutputs"></param>
  213. /// <returns></returns>
  214. protected abstract bool PostProcess(IInferenceParams inferenceParams, InferStateArgs args, out IEnumerable<string>? extraOutputs);
  215. /// <summary>
  216. /// The core inference logic.
  217. /// </summary>
  218. /// <param name="inferenceParams"></param>
  219. /// <param name="args"></param>
  220. protected abstract void InferInternal(IInferenceParams inferenceParams, InferStateArgs args);
  221. /// <summary>
  222. /// Save the current state to a file.
  223. /// </summary>
  224. /// <param name="filename"></param>
  225. public abstract void SaveState(string filename);
  226. /// <summary>
  227. /// Get the current state data.
  228. /// </summary>
  229. /// <returns></returns>
  230. public abstract ExecutorBaseState GetStateData();
  231. /// <summary>
  232. /// Load the state from data.
  233. /// </summary>
  234. /// <param name="data"></param>
  235. public abstract void LoadState(ExecutorBaseState data);
  236. /// <summary>
  237. /// Load the state from a file.
  238. /// </summary>
  239. /// <param name="filename"></param>
  240. public abstract void LoadState(string filename);
  241. /// <summary>
  242. /// Execute the inference.
  243. /// </summary>
  244. /// <param name="text"></param>
  245. /// <param name="inferenceParams"></param>
  246. /// <param name="cancellationToken"></param>
  247. /// <returns></returns>
  248. public virtual IEnumerable<string> Infer(string text, IInferenceParams? inferenceParams = null, CancellationToken cancellationToken = default)
  249. {
  250. cancellationToken.ThrowIfCancellationRequested();
  251. inferenceParams ??= new InferenceParams();
  252. InferStateArgs args = new InferStateArgs()
  253. {
  254. Antiprompts = inferenceParams.AntiPrompts.ToList(),
  255. RemainedTokens = inferenceParams.MaxTokens,
  256. ReturnValue = false,
  257. WaitForInput = false,
  258. NeedToSaveSession = !string.IsNullOrEmpty(_pathSession) && _n_matching_session_tokens < _embed_inps.Count
  259. };
  260. PreprocessInputs(text, args);
  261. while (GetLoopCondition(args))
  262. {
  263. if (cancellationToken.IsCancellationRequested)
  264. {
  265. break;
  266. }
  267. InferInternal(inferenceParams, args);
  268. if (args.ReturnValue)
  269. {
  270. foreach (var item in Context.GenerateResult(_embeds))
  271. {
  272. yield return item;
  273. }
  274. }
  275. var breakGeneration = PostProcess(inferenceParams, args, out var extraOutputs);
  276. if (extraOutputs is not null)
  277. {
  278. foreach (var item in extraOutputs)
  279. {
  280. yield return item;
  281. }
  282. }
  283. if (breakGeneration)
  284. {
  285. break;
  286. }
  287. }
  288. }
  289. /// <summary>
  290. /// Execute the inference asynchronously.
  291. /// </summary>
  292. /// <param name="text"></param>
  293. /// <param name="inferenceParams"></param>
  294. /// <param name="cancellationToken"></param>
  295. /// <returns></returns>
  296. public virtual async IAsyncEnumerable<string> InferAsync(string text, IInferenceParams? inferenceParams = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
  297. {
  298. foreach (var result in Infer(text, inferenceParams, cancellationToken))
  299. {
  300. yield return result;
  301. }
  302. }
  303. /// <summary>
  304. /// State arguments that are used in single inference
  305. /// </summary>
  306. protected class InferStateArgs
  307. {
  308. /// <summary>
  309. ///
  310. /// </summary>
  311. public IList<string>? Antiprompts { get; set; }
  312. /// <summary>
  313. /// Tokens count remained to be used. (n_remain)
  314. /// </summary>
  315. public int RemainedTokens { get; set; }
  316. /// <summary>
  317. ///
  318. /// </summary>
  319. public bool ReturnValue { get; set; }
  320. /// <summary>
  321. ///
  322. /// </summary>
  323. public bool WaitForInput { get; set; }
  324. /// <summary>
  325. ///
  326. /// </summary>
  327. public bool NeedToSaveSession { get; set; }
  328. }
  329. public class ExecutorBaseState
  330. {
  331. [JsonPropertyName("n_past")]
  332. public int PastTokensCount { get; set; }
  333. [JsonPropertyName("n_consumed")]
  334. public int ConsumedTokensCount { get; set; }
  335. [JsonPropertyName("n_session_consumed")]
  336. public int ConsumedSessionCount { get; set; }
  337. [JsonPropertyName("n_matching_session_tokens")]
  338. public int MatchingSessionTokensCount { get; set; }
  339. [JsonPropertyName("path_session")]
  340. public string SessionFilePath { get; set; }
  341. [JsonPropertyName("embd")]
  342. public List<llama_token> Embeds { get; set; }
  343. [JsonPropertyName("embd_inps")]
  344. public List<llama_token> EmbedInps { get; set; }
  345. [JsonPropertyName("session_tokens")]
  346. public List<llama_token> SessionTokens { get; set; }
  347. [JsonPropertyName("last_n_tokens")]
  348. public llama_token[] LastTokens { get; set; }
  349. [JsonPropertyName("last_tokens_maximum_count")]
  350. public int LastTokensCapacity { get; set; }
  351. [JsonPropertyName("mirostat_mu")]
  352. public float? MirostatMu { get; set; }
  353. }
  354. }
  355. }