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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. ///
  70. /// </summary>
  71. /// <param name="model"></param>
  72. /// <param name="logger"></param>
  73. protected StatefulExecutorBase(LLamaModel model, ILLamaLogger? logger = null)
  74. {
  75. _model = model;
  76. _logger = logger;
  77. _pastTokensCount = 0;
  78. _consumedTokensCount = 0;
  79. _n_session_consumed = 0;
  80. _embeds = new();
  81. _embed_inps = new();
  82. _last_n_tokens = new FixedSizeQueue<llama_token>(_model.ContextSize).FillWith(0);
  83. }
  84. /// <summary>
  85. /// This API is currently not verified.
  86. /// </summary>
  87. /// <param name="filename"></param>
  88. /// <returns></returns>
  89. /// <exception cref="ArgumentNullException"></exception>
  90. /// <exception cref="RuntimeError"></exception>
  91. public unsafe StatefulExecutorBase WithSessionFile(string filename)
  92. {
  93. _pathSession = filename;
  94. if (string.IsNullOrEmpty(filename))
  95. {
  96. throw new ArgumentNullException("File name cannot be empty.");
  97. }
  98. if (File.Exists(filename))
  99. {
  100. _logger?.Log("LLamaExecutor", $"Attempting to load saved session from {filename}", ILLamaLogger.LogLevel.Info);
  101. llama_token[] session_tokens = new llama_token[_model.ContextSize];
  102. ulong n_token_count_out = 0;
  103. if (!NativeApi.llama_load_session_file(_model.NativeHandle, _pathSession, session_tokens, (ulong)_model.ContextSize, &n_token_count_out))
  104. {
  105. _logger?.Log("LLamaExecutor", $"Failed to load session file {filename}", ILLamaLogger.LogLevel.Error);
  106. throw new RuntimeError($"Failed to load session file {_pathSession}");
  107. }
  108. _session_tokens = session_tokens.Take((int)n_token_count_out).ToList();
  109. _logger?.Log("LLamaExecutor", $"Loaded a session with prompt size of {session_tokens.Length} tokens", ILLamaLogger.LogLevel.Info);
  110. }
  111. else
  112. {
  113. _logger?.Log("LLamaExecutor", $"Session file does not exist, will create", ILLamaLogger.LogLevel.Warning);
  114. }
  115. _n_matching_session_tokens = 0;
  116. if (_session_tokens.Count > 0)
  117. {
  118. foreach (var id in _session_tokens)
  119. {
  120. if (_n_matching_session_tokens >= _embed_inps.Count || id != _embed_inps[_n_matching_session_tokens])
  121. {
  122. break;
  123. }
  124. _n_matching_session_tokens++;
  125. }
  126. if (_n_matching_session_tokens >= _embed_inps.Count)
  127. {
  128. _logger?.Log("LLamaExecutor", $"Session file has exact match for prompt!", ILLamaLogger.LogLevel.Info);
  129. }
  130. else if (_n_matching_session_tokens < _embed_inps.Count / 2)
  131. {
  132. _logger?.Log("LLamaExecutor", $"session file has low similarity to prompt ({_n_matching_session_tokens}" +
  133. $" / {_embed_inps.Count} tokens); will mostly be reevaluated", ILLamaLogger.LogLevel.Warning);
  134. }
  135. else
  136. {
  137. _logger?.Log("LLamaExecutor", $"Session file matches {_n_matching_session_tokens} / " +
  138. $"{_embed_inps.Count} tokens of prompt", ILLamaLogger.LogLevel.Info);
  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(_model.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(_model.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 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 void 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. /// <param name="extraOutputs"></param>
  215. /// <returns></returns>
  216. protected abstract bool PostProcess(InferenceParams inferenceParams, InferStateArgs args, out IEnumerable<string>? extraOutputs);
  217. /// <summary>
  218. /// The core inference logic.
  219. /// </summary>
  220. /// <param name="inferenceParams"></param>
  221. /// <param name="args"></param>
  222. protected abstract void InferInternal(InferenceParams inferenceParams, InferStateArgs args);
  223. /// <summary>
  224. /// Save the current state to a file.
  225. /// </summary>
  226. /// <param name="filename"></param>
  227. public abstract void 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 void LoadState(ExecutorBaseState data);
  238. /// <summary>
  239. /// Load the state from a file.
  240. /// </summary>
  241. /// <param name="filename"></param>
  242. public abstract void 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 IEnumerable<string> Infer(string text, InferenceParams? inferenceParams = null, CancellationToken cancellationToken = default)
  251. {
  252. cancellationToken.ThrowIfCancellationRequested();
  253. if (inferenceParams is null)
  254. {
  255. inferenceParams = new InferenceParams();
  256. }
  257. InferStateArgs args = new InferStateArgs()
  258. {
  259. Antiprompts = inferenceParams.AntiPrompts.ToList(),
  260. RemainedTokens = inferenceParams.MaxTokens,
  261. ReturnValue = false,
  262. WaitForInput = false,
  263. NeedToSaveSession = !string.IsNullOrEmpty(_pathSession) && _n_matching_session_tokens < _embed_inps.Count
  264. };
  265. PreprocessInputs(text, args);
  266. while (GetLoopCondition(args))
  267. {
  268. if (cancellationToken.IsCancellationRequested)
  269. {
  270. break;
  271. }
  272. InferInternal(inferenceParams, args);
  273. if (args.ReturnValue)
  274. {
  275. foreach (var item in _model.GenerateResult(_embeds))
  276. {
  277. yield return item;
  278. }
  279. }
  280. var breakGeneration = PostProcess(inferenceParams, args, out var extraOutputs);
  281. if (extraOutputs is not null)
  282. {
  283. foreach (var item in extraOutputs)
  284. {
  285. yield return item;
  286. }
  287. }
  288. if (breakGeneration)
  289. {
  290. break;
  291. }
  292. }
  293. }
  294. /// <summary>
  295. /// Execute the inference asynchronously.
  296. /// </summary>
  297. /// <param name="text"></param>
  298. /// <param name="inferenceParams"></param>
  299. /// <param name="cancellationToken"></param>
  300. /// <returns></returns>
  301. public virtual async IAsyncEnumerable<string> InferAsync(string text, InferenceParams? inferenceParams = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
  302. {
  303. foreach (var result in Infer(text, inferenceParams, cancellationToken))
  304. {
  305. yield return result;
  306. }
  307. }
  308. /// <summary>
  309. /// State arguments that are used in single inference
  310. /// </summary>
  311. protected class InferStateArgs
  312. {
  313. /// <summary>
  314. ///
  315. /// </summary>
  316. public IList<string>? Antiprompts { get; set; }
  317. /// <summary>
  318. /// Tokens count remained to be used. (n_remain)
  319. /// </summary>
  320. public int RemainedTokens { get; set; }
  321. /// <summary>
  322. ///
  323. /// </summary>
  324. public bool ReturnValue { get; set; }
  325. /// <summary>
  326. ///
  327. /// </summary>
  328. public bool WaitForInput { get; set; }
  329. /// <summary>
  330. ///
  331. /// </summary>
  332. public bool NeedToSaveSession { get; set; }
  333. }
  334. public class ExecutorBaseState
  335. {
  336. [JsonPropertyName("n_past")]
  337. public int PastTokensCount { get; set; }
  338. [JsonPropertyName("n_consumed")]
  339. public int ConsumedTokensCount { get; set; }
  340. [JsonPropertyName("n_session_consumed")]
  341. public int ConsumedSessionCount { get; set; }
  342. [JsonPropertyName("n_matching_session_tokens")]
  343. public int MatchingSessionTokensCount { get; set; }
  344. [JsonPropertyName("path_session")]
  345. public string SessionFilePath { get; set; }
  346. [JsonPropertyName("embd")]
  347. public List<llama_token> Embeds { get; set; }
  348. [JsonPropertyName("embd_inps")]
  349. public List<llama_token> EmbedInps { get; set; }
  350. [JsonPropertyName("session_tokens")]
  351. public List<llama_token> SessionTokens { get; set; }
  352. [JsonPropertyName("last_n_tokens")]
  353. public llama_token[] LastTokens { get; set; }
  354. [JsonPropertyName("last_tokens_maximum_count")]
  355. public int LastTokensCapacity { get; set; }
  356. }
  357. }
  358. }

C#/.NET上易用的LLM高性能推理框架,支持LLaMA和LLaVA系列模型。