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

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