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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. /// <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<LLamaToken> _embeds = new(); // embd
  49. /// <summary>
  50. /// A container for the tokens of input.
  51. /// </summary>
  52. protected List<LLamaToken> _embed_inps = new();
  53. /// <summary>
  54. ///
  55. /// </summary>
  56. protected List<LLamaToken> _session_tokens = new();
  57. /// <summary>
  58. /// The last tokens generated by the model.
  59. /// </summary>
  60. protected FixedSizeQueue<LLamaToken> _last_n_tokens;
  61. /// <summary>
  62. /// The context used by the executor.
  63. /// </summary>
  64. public LLamaContext Context { get; }
  65. // LLava Section
  66. //
  67. /// <inheritdoc />
  68. public bool IsMultiModal
  69. {
  70. get
  71. {
  72. return ClipModel != null;
  73. }
  74. }
  75. /// <inheritdoc />
  76. public LLavaWeights? ClipModel { get; }
  77. /// <inheritdoc />
  78. public List<string> ImagePaths { get; set; }
  79. /// <inheritdoc />
  80. public List<byte[]> ImageBytes { get; set; }
  81. /// <summary>
  82. /// Current "mu" value for mirostat sampling
  83. /// </summary>
  84. protected float? MirostatMu { get; set; }
  85. private readonly StreamingTokenDecoder _decoder;
  86. /// <summary>
  87. ///
  88. /// </summary>
  89. /// <param name="context"></param>
  90. /// <param name="logger"></param>
  91. protected StatefulExecutorBase(LLamaContext context, ILogger? logger = null)
  92. {
  93. ImagePaths = new List<string>();
  94. ImageBytes = new List<byte[]>();
  95. _logger = logger;
  96. Context = context;
  97. _pastTokensCount = 0;
  98. _consumedTokensCount = 0;
  99. _n_session_consumed = 0;
  100. _last_n_tokens = new FixedSizeQueue<LLamaToken>((int)Context.ContextSize);
  101. _decoder = new StreamingTokenDecoder(context);
  102. }
  103. public StatefulExecutorBase(LLamaContext context, LLavaWeights lLavaWeights, ILogger? logger = null) :
  104. this( context, logger )
  105. {
  106. ClipModel = lLavaWeights;
  107. }
  108. /// <summary>
  109. /// This API is currently not verified.
  110. /// </summary>
  111. /// <param name="filename"></param>
  112. /// <returns></returns>
  113. /// <exception cref="ArgumentNullException"></exception>
  114. /// <exception cref="RuntimeError"></exception>
  115. public StatefulExecutorBase WithSessionFile(string filename)
  116. {
  117. _pathSession = filename;
  118. if (string.IsNullOrEmpty(filename))
  119. {
  120. throw new ArgumentNullException(nameof(filename), "File name cannot be empty.");
  121. }
  122. if (File.Exists(filename))
  123. {
  124. _logger?.LogInformation($"[LLamaExecutor] Attempting to load saved session from {filename}");
  125. var session_tokens = new LLamaToken[Context.ContextSize];
  126. if (!NativeApi.llama_load_session_file(Context.NativeHandle, _pathSession, session_tokens, (ulong)Context.ContextSize, out var n_token_count_out))
  127. {
  128. _logger?.LogError($"[LLamaExecutor] Failed to load session file {filename}");
  129. throw new RuntimeError($"Failed to load session file {_pathSession}");
  130. }
  131. _session_tokens = session_tokens.Take((int)n_token_count_out).ToList();
  132. _logger?.LogInformation($"[LLamaExecutor] Loaded a session with prompt size of {session_tokens.Length} tokens");
  133. }
  134. else
  135. {
  136. _logger?.LogWarning("[LLamaExecutor] Session file does not exist, will create");
  137. }
  138. _n_matching_session_tokens = 0;
  139. if (_session_tokens.Count > 0)
  140. {
  141. foreach (var id in _session_tokens)
  142. {
  143. if (_n_matching_session_tokens >= _embed_inps.Count || id != _embed_inps[_n_matching_session_tokens])
  144. {
  145. break;
  146. }
  147. _n_matching_session_tokens++;
  148. }
  149. if (_n_matching_session_tokens >= _embed_inps.Count)
  150. {
  151. _logger?.LogInformation("[LLamaExecutor] Session file has exact match for prompt!");
  152. }
  153. else if (_n_matching_session_tokens < _embed_inps.Count / 2)
  154. {
  155. _logger?.LogWarning($"[LLamaExecutor] Session file has low similarity to prompt ({_n_matching_session_tokens} / {_embed_inps.Count} tokens) will mostly be reevaluated");
  156. }
  157. else
  158. {
  159. _logger?.LogInformation($"[LLamaExecutor] Session file matches {_n_matching_session_tokens} / {_embed_inps.Count} tokens of prompt");
  160. }
  161. }
  162. return this;
  163. }
  164. /// <summary>
  165. /// This API has not been verified currently.
  166. /// </summary>
  167. /// <param name="filename"></param>
  168. public void SaveSessionFile(string filename)
  169. {
  170. var session_token_array = _session_tokens.ToArray();
  171. NativeApi.llama_save_session_file(Context.NativeHandle, filename, session_token_array, (ulong)session_token_array.Length);
  172. }
  173. /// <summary>
  174. /// After running out of the context, take some tokens from the original prompt and recompute the logits in batches.
  175. /// </summary>
  176. /// <param name="tokensToKeep"></param>
  177. protected virtual void HandleRunOutOfContext(int tokensToKeep)
  178. {
  179. // if we run out of context:
  180. // - take the tokensToKeep first tokens from the original prompt (via n_past)
  181. // - take half of the last (n_ctx - tokensToKeep) tokens and recompute the logits in batches
  182. int n_left = _pastTokensCount - tokensToKeep;
  183. _pastTokensCount = Math.Max(1, tokensToKeep);
  184. // insert n_left/2 tokens at the start of embed from last_n_tokens
  185. _embeds.InsertRange(0, _last_n_tokens.Take(_last_n_tokens.Count - _embeds.Count).Skip((int)Context.ContextSize - n_left / 2 - _embeds.Count));
  186. // stop saving session if we run out of context
  187. _pathSession = string.Empty;
  188. }
  189. /// <summary>
  190. /// Try to reuse the matching prefix from the session file.
  191. /// </summary>
  192. protected virtual void TryReuseMathingPrefix()
  193. {
  194. if (_n_session_consumed < _session_tokens.Count)
  195. {
  196. int i = 0;
  197. for (; i < _embeds.Count; i++)
  198. {
  199. if (_embeds[i] != _session_tokens[_n_session_consumed])
  200. {
  201. _session_tokens = _session_tokens.Take(_n_session_consumed).ToList();
  202. break;
  203. }
  204. _pastTokensCount++;
  205. _n_session_consumed++;
  206. if (_n_session_consumed >= _session_tokens.Count)
  207. {
  208. i++;
  209. break;
  210. }
  211. }
  212. if (i > 0)
  213. {
  214. _embeds.RemoveRange(0, i);
  215. }
  216. }
  217. }
  218. /// <summary>
  219. /// Decide whether to continue the loop.
  220. /// </summary>
  221. /// <param name="args"></param>
  222. /// <returns></returns>
  223. protected abstract Task<bool> GetLoopCondition(InferStateArgs args);
  224. /// <summary>
  225. /// Preprocess the inputs before the inference.
  226. /// </summary>
  227. /// <param name="text"></param>
  228. /// <param name="args"></param>
  229. protected abstract Task PreprocessInputs(string text, InferStateArgs args);
  230. /// <summary>
  231. /// Do some post processing after the inference.
  232. /// </summary>
  233. /// <param name="inferenceParams"></param>
  234. /// <param name="args"></param>
  235. /// <returns></returns>
  236. protected abstract Task<(bool, IReadOnlyList<string>)> PostProcess(IInferenceParams inferenceParams, InferStateArgs args);
  237. /// <summary>
  238. /// The core inference logic.
  239. /// </summary>
  240. /// <param name="inferenceParams"></param>
  241. /// <param name="args"></param>
  242. protected abstract Task InferInternal(IInferenceParams inferenceParams, InferStateArgs args);
  243. /// <summary>
  244. /// Save the current state to a file.
  245. /// </summary>
  246. /// <param name="filename"></param>
  247. public abstract Task SaveState(string filename);
  248. /// <summary>
  249. /// Get the current state data.
  250. /// </summary>
  251. /// <returns></returns>
  252. public abstract ExecutorBaseState GetStateData();
  253. /// <summary>
  254. /// Load the state from data.
  255. /// </summary>
  256. /// <param name="data"></param>
  257. public abstract Task LoadState(ExecutorBaseState data);
  258. /// <summary>
  259. /// Load the state from a file.
  260. /// </summary>
  261. /// <param name="filename"></param>
  262. public abstract Task LoadState(string filename);
  263. /// <summary>
  264. /// Execute the inference.
  265. /// </summary>
  266. /// <param name="text"></param>
  267. /// <param name="inferenceParams"></param>
  268. /// <param name="cancellationToken"></param>
  269. /// <returns></returns>
  270. public virtual async IAsyncEnumerable<string> InferAsync(string text, IInferenceParams? inferenceParams = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
  271. {
  272. cancellationToken.ThrowIfCancellationRequested();
  273. inferenceParams ??= new InferenceParams();
  274. var args = new InferStateArgs
  275. {
  276. Antiprompts = inferenceParams.AntiPrompts.ToList(),
  277. RemainedTokens = inferenceParams.MaxTokens,
  278. ReturnValue = false,
  279. WaitForInput = false,
  280. NeedToSaveSession = !string.IsNullOrEmpty(_pathSession) && _n_matching_session_tokens < _embed_inps.Count
  281. };
  282. await PreprocessInputs(text, args);
  283. while (await GetLoopCondition(args))
  284. {
  285. if (cancellationToken.IsCancellationRequested)
  286. {
  287. break;
  288. }
  289. await InferInternal(inferenceParams, args);
  290. if (args.ReturnValue)
  291. {
  292. _decoder.AddRange(_embeds);
  293. yield return _decoder.Read();
  294. }
  295. var (breakGeneration, extraOutputs) = await PostProcess(inferenceParams, args);
  296. if (extraOutputs is { Count: > 0 })
  297. {
  298. foreach (var item in extraOutputs)
  299. {
  300. yield return item;
  301. }
  302. }
  303. if (breakGeneration)
  304. {
  305. break;
  306. }
  307. }
  308. }
  309. /// <summary>
  310. /// Asynchronously runs a prompt through the model to compute KV cache without generating any new tokens.
  311. /// It could reduce the latency of the first time response if the first input from the user is not immediate.
  312. /// </summary>
  313. /// <param name="prompt">Prompt to process</param>
  314. /// <returns></returns>
  315. public virtual async Task PrefillPromptAsync(string prompt)
  316. {
  317. var inferenceParams = new InferenceParams
  318. {
  319. MaxTokens = 0
  320. };
  321. var args = new InferStateArgs
  322. {
  323. Antiprompts = new List<string>(),
  324. RemainedTokens = 0,
  325. ReturnValue = false,
  326. WaitForInput = true,
  327. NeedToSaveSession = false
  328. };
  329. await PreprocessInputs(prompt, args);
  330. // First run adds the prompt to the _embeds
  331. await InferInternal(inferenceParams, args);
  332. // Second run puts it through decode
  333. await InferInternal(inferenceParams, args);
  334. }
  335. /// <summary>
  336. /// State arguments that are used in single inference
  337. /// </summary>
  338. protected class InferStateArgs
  339. {
  340. /// <summary>
  341. ///
  342. /// </summary>
  343. public IList<string>? Antiprompts { get; set; }
  344. /// <summary>
  345. /// Tokens count remained to be used. (n_remain)
  346. /// </summary>
  347. public int RemainedTokens { get; set; }
  348. /// <summary>
  349. ///
  350. /// </summary>
  351. public bool ReturnValue { get; set; }
  352. /// <summary>
  353. ///
  354. /// </summary>
  355. public bool WaitForInput { get; set; }
  356. /// <summary>
  357. ///
  358. /// </summary>
  359. public bool NeedToSaveSession { get; set; }
  360. }
  361. [JsonConverter(typeof(PolymorphicJSONConverter<ExecutorBaseState>))]
  362. public class ExecutorBaseState
  363. {
  364. [JsonPropertyName("n_past")]
  365. public int PastTokensCount { get; set; }
  366. [JsonPropertyName("n_consumed")]
  367. public int ConsumedTokensCount { get; set; }
  368. [JsonPropertyName("n_session_consumed")]
  369. public int ConsumedSessionCount { get; set; }
  370. [JsonPropertyName("n_matching_session_tokens")]
  371. public int MatchingSessionTokensCount { get; set; }
  372. [JsonPropertyName("path_session")]
  373. public string? SessionFilePath { get; set; }
  374. [JsonPropertyName("embd")]
  375. public LLamaToken[] Embeds { get; set; }
  376. [JsonPropertyName("embd_inps")]
  377. public LLamaToken[] EmbedInps { get; set; }
  378. [JsonPropertyName("session_tokens")]
  379. public LLamaToken[] SessionTokens { get; set; }
  380. [JsonPropertyName("last_n_tokens")]
  381. public LLamaToken[] LastTokens { get; set; }
  382. [JsonPropertyName("last_tokens_maximum_count")]
  383. public int LastTokensCapacity { get; set; }
  384. [JsonPropertyName("mirostat_mu")]
  385. public float? MirostatMu { get; set; }
  386. }
  387. }
  388. }