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.

LLamaInteractExecutor.cs 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. using LLama.Common;
  2. using LLama.Native;
  3. using LLama.Abstractions;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text.Json;
  9. using System.Text.Json.Serialization;
  10. using System.Threading.Tasks;
  11. using LLama.Exceptions;
  12. using LLama.Extensions;
  13. using Microsoft.Extensions.Logging;
  14. namespace LLama
  15. {
  16. /// <summary>
  17. /// The LLama executor for interactive mode.
  18. /// </summary>
  19. public class InteractiveExecutor : StatefulExecutorBase
  20. {
  21. private bool _is_prompt_run = true;
  22. private readonly LLamaToken _llama_token_newline;
  23. // LLava
  24. private int _EmbedImagePosition = -1;
  25. private List<SafeLlavaImageEmbedHandle> _imageEmbedHandles = new List<SafeLlavaImageEmbedHandle>();
  26. private bool _imageInPrompt = false;
  27. /// <summary>
  28. ///
  29. /// </summary>
  30. /// <param name="context"></param>
  31. /// <param name="logger"></param>
  32. public InteractiveExecutor(LLamaContext context, ILogger? logger = null)
  33. : base(context, logger)
  34. {
  35. _llama_token_newline = NativeApi.llama_token_nl(Context.NativeHandle.ModelHandle);
  36. }
  37. public InteractiveExecutor(LLamaContext context, LLavaWeights clipModel, ILogger? logger = null)
  38. : base(context, clipModel, logger)
  39. {
  40. _llama_token_newline = NativeApi.llama_token_nl(Context.NativeHandle.ModelHandle);
  41. }
  42. /// <inheritdoc />
  43. public override ExecutorBaseState GetStateData()
  44. {
  45. InteractiveExecutorState state = new()
  46. {
  47. ConsumedSessionCount = _n_session_consumed,
  48. EmbedInps = _embed_inps.ToArray(),
  49. IsPromptRun = _is_prompt_run,
  50. ConsumedTokensCount = _consumedTokensCount,
  51. Embeds = _embeds.ToArray(),
  52. LastTokens = _last_n_tokens.ToArray(),
  53. MatchingSessionTokensCount = _n_matching_session_tokens,
  54. PastTokensCount = _pastTokensCount,
  55. SessionFilePath = _pathSession,
  56. SessionTokens = _session_tokens.ToArray(),
  57. LastTokensCapacity = _last_n_tokens.Capacity,
  58. MirostatMu = MirostatMu
  59. };
  60. return state;
  61. }
  62. /// <inheritdoc />
  63. public override Task LoadState(ExecutorBaseState data)
  64. {
  65. if (data is InteractiveExecutorState state)
  66. {
  67. _n_session_consumed = state.ConsumedSessionCount;
  68. _embed_inps = state.EmbedInps.ToList();
  69. _is_prompt_run = state.IsPromptRun;
  70. _consumedTokensCount = state.ConsumedTokensCount;
  71. _embeds = state.Embeds.ToList();
  72. _last_n_tokens = new FixedSizeQueue<LLamaToken>(state.LastTokensCapacity, state.LastTokens);
  73. _n_matching_session_tokens = state.MatchingSessionTokensCount;
  74. _pastTokensCount = state.PastTokensCount;
  75. _pathSession = state.SessionFilePath;
  76. _session_tokens = state.SessionTokens.ToList();
  77. }
  78. else
  79. throw new ArgumentException("Invalid state data type.");
  80. return Task.CompletedTask;
  81. }
  82. /// <inheritdoc />
  83. public override async Task SaveState(string filename)
  84. {
  85. var state = (InteractiveExecutorState)GetStateData();
  86. using(var fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
  87. {
  88. await JsonSerializer.SerializeAsync(fs, state);
  89. }
  90. }
  91. /// <inheritdoc />
  92. public override async Task LoadState(string filename)
  93. {
  94. using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
  95. {
  96. var state = await JsonSerializer.DeserializeAsync<InteractiveExecutorState>(fs);
  97. await LoadState(state);
  98. }
  99. }
  100. /// <summary>
  101. /// Define whether to continue the loop to generate responses.
  102. /// </summary>
  103. /// <returns></returns>
  104. protected override Task<bool> GetLoopCondition(InferStateArgs args)
  105. {
  106. return Task.FromResult(args.RemainedTokens != 0 && !args.WaitForInput || _is_prompt_run);
  107. }
  108. /// <inheritdoc />
  109. protected override Task PreprocessInputs(string text, InferStateArgs args)
  110. {
  111. if (_is_prompt_run)
  112. {
  113. // When running the first input (prompt) in interactive mode, we should specially process it.
  114. if (!this.IsMultiModal)
  115. {
  116. _embed_inps = Context.Tokenize(text, true).ToList();
  117. }
  118. else
  119. {
  120. PreprocessLlava(text, args, true );
  121. }
  122. }
  123. else
  124. {
  125. if (!text.EndsWith("\n"))
  126. {
  127. text += "\n";
  128. }
  129. var line_inp = Context.Tokenize(text, false);
  130. _embed_inps.AddRange(line_inp);
  131. args.RemainedTokens -= line_inp.Length;
  132. }
  133. return Task.CompletedTask;
  134. }
  135. private Task PreprocessLlava(string text, InferStateArgs args, bool addBos = true )
  136. {
  137. int usedTokens = 0;
  138. // If the prompt contains the tag <image> extract this.
  139. _imageInPrompt = text.Contains("<image>");
  140. if (_imageInPrompt)
  141. {
  142. foreach (var image in ImagePaths)
  143. {
  144. _imageEmbedHandles.Add(SafeLlavaImageEmbedHandle.CreateFromFileName( ClipModel.NativeHandle, Context, image ) );
  145. }
  146. foreach (var image in ImageBytes)
  147. {
  148. _imageEmbedHandles.Add(SafeLlavaImageEmbedHandle.CreateFromMemory(ClipModel.NativeHandle, Context, image));
  149. }
  150. int imageIndex = text.IndexOf("<image>");
  151. // Tokenize segment 1 (before <image> tag)
  152. string preImagePrompt = text.Substring(0, imageIndex);
  153. var segment1 = Context.Tokenize(preImagePrompt, addBos );
  154. // Remember the position to add the image embeddings
  155. _EmbedImagePosition = segment1.Length;
  156. string postImagePrompt = text.Substring(imageIndex + 7);
  157. var segment2 = Context.Tokenize(postImagePrompt, false);
  158. _embed_inps.AddRange(segment1);
  159. _embed_inps.AddRange(segment2);
  160. usedTokens += (segment1.Length + segment2.Length);
  161. }
  162. else
  163. {
  164. _embed_inps = Context.Tokenize(text, true).ToList();
  165. }
  166. return Task.CompletedTask;
  167. }
  168. /// <summary>
  169. /// Return whether to break the generation.
  170. /// </summary>
  171. /// <param name="inferenceParams"></param>
  172. /// <param name="args"></param>
  173. /// <returns></returns>
  174. protected override async Task<(bool, IReadOnlyList<string>)> PostProcess(IInferenceParams inferenceParams, InferStateArgs args)
  175. {
  176. if (_embed_inps.Count <= _consumedTokensCount)
  177. {
  178. if (_last_n_tokens.TokensEndsWithAnyString(args.Antiprompts, Context.NativeHandle.ModelHandle, Context.Encoding))
  179. args.WaitForInput = true;
  180. if (_pastTokensCount > 0 && args.WaitForInput)
  181. return (true, Array.Empty<string>());
  182. }
  183. if (_embeds.Count > 0 && _embeds.Last() == NativeApi.llama_token_eos(Context.NativeHandle.ModelHandle))
  184. {
  185. return (true, new[] { " [end of text]\n" });
  186. }
  187. if (args.RemainedTokens <= 0 && inferenceParams.MaxTokens != -1)
  188. {
  189. args.RemainedTokens = inferenceParams.MaxTokens;
  190. args.WaitForInput = true;
  191. }
  192. return (false, Array.Empty<string>());
  193. }
  194. /// <inheritdoc />
  195. protected override Task InferInternal(IInferenceParams inferenceParams, InferStateArgs args)
  196. {
  197. var batch = new LLamaBatch();
  198. if (_embeds.Count > 0)
  199. {
  200. _is_prompt_run = false;
  201. if (_pastTokensCount + _embeds.Count > Context.ContextSize)
  202. {
  203. HandleRunOutOfContext(inferenceParams.TokensKeep);
  204. }
  205. TryReuseMathingPrefix();
  206. // Changes to support Multi-Modal LLMs.
  207. //
  208. (DecodeResult, int) header, end, result;
  209. if (IsMultiModal && _EmbedImagePosition > 0)
  210. {
  211. // Tokens previous to the images
  212. header = Context.NativeHandle.Decode(_embeds.GetRange(0, _EmbedImagePosition), LLamaSeqId.Zero, batch, ref _pastTokensCount);
  213. if (header.Item1 != DecodeResult.Ok) throw new LLamaDecodeError(header.Item1);
  214. // Images
  215. foreach( var image in _imageEmbedHandles )
  216. ClipModel.EvalImageEmbed(Context, image, ref _pastTokensCount);
  217. // Post-image Tokens
  218. end = Context.NativeHandle.Decode(_embeds.GetRange(_EmbedImagePosition, _embeds.Count - _EmbedImagePosition), LLamaSeqId.Zero, batch, ref _pastTokensCount);
  219. _EmbedImagePosition = -1;
  220. _imageEmbedHandles.Clear();
  221. }
  222. else
  223. {
  224. result = Context.NativeHandle.Decode(_embeds, LLamaSeqId.Zero, batch, ref _pastTokensCount);
  225. if (result.Item1 != DecodeResult.Ok) throw new LLamaDecodeError(result.Item1);
  226. }
  227. if (_embeds.Count > 0 && !string.IsNullOrEmpty(_pathSession))
  228. {
  229. _session_tokens.AddRange(_embeds);
  230. _n_session_consumed = _session_tokens.Count;
  231. }
  232. }
  233. _embeds.Clear();
  234. if (_embed_inps.Count <= _consumedTokensCount && !args.WaitForInput)
  235. {
  236. var repeat_last_n = inferenceParams.RepeatLastTokensCount < 0 ? (int)Context.ContextSize : inferenceParams.RepeatLastTokensCount;
  237. // optionally save the session on first sample (for faster prompt loading next time)
  238. if (!string.IsNullOrEmpty(_pathSession) && args.NeedToSaveSession)
  239. {
  240. args.NeedToSaveSession = false;
  241. SaveSessionFile(_pathSession);
  242. }
  243. LLamaToken id;
  244. if (inferenceParams.SamplingPipeline is not null)
  245. {
  246. id = inferenceParams.SamplingPipeline.Sample(Context.NativeHandle, Context.NativeHandle.GetLogitsIth(batch.TokenCount - 1), _last_n_tokens.ToArray());
  247. inferenceParams.SamplingPipeline.Accept(Context.NativeHandle, id);
  248. }
  249. else
  250. {
  251. var tokenDataArray = Context.ApplyPenalty(batch.TokenCount - 1, _last_n_tokens, inferenceParams.LogitBias, repeat_last_n,
  252. inferenceParams.RepeatPenalty, inferenceParams.FrequencyPenalty, inferenceParams.PresencePenalty, inferenceParams.PenalizeNL);
  253. var mu = MirostatMu;
  254. id = Context.Sample(
  255. tokenDataArray, ref mu, inferenceParams.Temperature, inferenceParams.Mirostat, inferenceParams.MirostatTau,
  256. inferenceParams.MirostatEta, inferenceParams.TopK, inferenceParams.TopP, inferenceParams.TfsZ, inferenceParams.TypicalP, inferenceParams.Grammar,
  257. inferenceParams.MinP
  258. );
  259. MirostatMu = mu;
  260. }
  261. _last_n_tokens.Enqueue(id);
  262. if (id == NativeApi.llama_token_eos(Context.NativeHandle.ModelHandle))
  263. {
  264. id = _llama_token_newline;
  265. if (args.Antiprompts is not null && args.Antiprompts.Count > 0)
  266. {
  267. var first_antiprompt = Context.Tokenize(args.Antiprompts[0], false);
  268. _embed_inps.AddRange(first_antiprompt);
  269. }
  270. }
  271. _embeds.Add(id);
  272. args.RemainedTokens--;
  273. args.ReturnValue = true;
  274. }
  275. else
  276. {
  277. while (_embed_inps.Count > _consumedTokensCount)
  278. {
  279. _embeds.Add(_embed_inps[_consumedTokensCount]);
  280. _last_n_tokens.Enqueue(_embed_inps[_consumedTokensCount]);
  281. _consumedTokensCount++;
  282. if (_embeds.Count >= Context.Params.BatchSize)
  283. {
  284. break;
  285. }
  286. }
  287. }
  288. return Task.CompletedTask;
  289. }
  290. /// <summary>
  291. /// The descriptor of the state of the interactive executor.
  292. /// </summary>
  293. public class InteractiveExecutorState
  294. : ExecutorBaseState
  295. {
  296. /// <summary>
  297. /// Whether the executor is running for the first time (running the prompt).
  298. /// </summary>
  299. [JsonPropertyName("is_prompt_run")]
  300. public bool IsPromptRun { get; set; }
  301. }
  302. }
  303. }