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

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