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

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