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

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