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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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.Text;
  11. namespace LLama
  12. {
  13. using llama_token = Int32;
  14. /// <summary>
  15. /// The LLama executor for interactive mode.
  16. /// </summary>
  17. public class InteractiveExecutor : StatefulExecutorBase
  18. {
  19. private bool _is_prompt_run = true;
  20. private readonly llama_token _llama_token_newline;
  21. /// <summary>
  22. ///
  23. /// </summary>
  24. /// <param name="context"></param>
  25. public InteractiveExecutor(LLamaContext context) : base(context)
  26. {
  27. _llama_token_newline = NativeApi.llama_token_nl(Context.NativeHandle);
  28. }
  29. /// <inheritdoc />
  30. public override ExecutorBaseState GetStateData()
  31. {
  32. InteractiveExecutorState state = new()
  33. {
  34. ConsumedSessionCount = _n_session_consumed,
  35. EmbedInps = _embed_inps,
  36. IsPromptRun = _is_prompt_run,
  37. ConsumedTokensCount = _consumedTokensCount,
  38. Embeds = _embeds,
  39. LastTokens = _last_n_tokens.ToArray(),
  40. MatchingSessionTokensCount = _n_matching_session_tokens,
  41. PastTokensCount = _pastTokensCount,
  42. SessionFilePath = _pathSession,
  43. SessionTokens = _session_tokens,
  44. LastTokensCapacity = _last_n_tokens.Capacity,
  45. MirostatMu = MirostatMu
  46. };
  47. return state;
  48. }
  49. /// <inheritdoc />
  50. public override void LoadState(ExecutorBaseState data)
  51. {
  52. if (data is InteractiveExecutorState state)
  53. {
  54. _n_session_consumed = state.ConsumedSessionCount;
  55. _embed_inps = state.EmbedInps;
  56. _is_prompt_run = state.IsPromptRun;
  57. _consumedTokensCount = state.ConsumedTokensCount;
  58. _embeds = state.Embeds;
  59. _last_n_tokens = new FixedSizeQueue<llama_token>(state.LastTokensCapacity, state.LastTokens);
  60. _n_matching_session_tokens = state.MatchingSessionTokensCount;
  61. _pastTokensCount = state.PastTokensCount;
  62. _pathSession = state.SessionFilePath;
  63. _session_tokens = state.SessionTokens;
  64. }
  65. else
  66. throw new ArgumentException("Invalid state data type.");
  67. }
  68. /// <inheritdoc />
  69. public override void SaveState(string filename)
  70. {
  71. InteractiveExecutorState state = (InteractiveExecutorState)GetStateData();
  72. using(FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
  73. {
  74. JsonSerializer.Serialize(fs, state);
  75. }
  76. }
  77. /// <inheritdoc />
  78. public override void LoadState(string filename)
  79. {
  80. using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
  81. {
  82. var state = JsonSerializer.Deserialize<InteractiveExecutorState>(fs);
  83. LoadState(state);
  84. }
  85. }
  86. /// <summary>
  87. /// Define whether to continue the loop to generate responses.
  88. /// </summary>
  89. /// <returns></returns>
  90. protected override bool GetLoopCondition(InferStateArgs args)
  91. {
  92. return args.RemainedTokens != 0 && !args.WaitForInput || _is_prompt_run;
  93. }
  94. /// <inheritdoc />
  95. protected override void PreprocessInputs(string text, InferStateArgs args)
  96. {
  97. if (_is_prompt_run)
  98. {
  99. // When running the first input (prompt) in inteactive mode, we should specially process it.
  100. _embed_inps = Context.Tokenize(text, true).ToList();
  101. }
  102. else
  103. {
  104. if (!text.EndsWith("\n"))
  105. {
  106. text += "\n";
  107. }
  108. var line_inp = Context.Tokenize(text, false);
  109. _embed_inps.AddRange(line_inp);
  110. args.RemainedTokens -= line_inp.Length;
  111. }
  112. }
  113. /// <summary>
  114. /// Return whether to break the generation.
  115. /// </summary>
  116. /// <param name="inferenceParams"></param>
  117. /// <param name="args"></param>
  118. /// <param name="extraOutputs"></param>
  119. /// <returns></returns>
  120. protected override bool PostProcess(IInferenceParams inferenceParams, InferStateArgs args, out IEnumerable<string>? extraOutputs)
  121. {
  122. extraOutputs = null;
  123. if (_embed_inps.Count <= _consumedTokensCount)
  124. {
  125. if (args.Antiprompts is not null && args.Antiprompts.Count > 0)
  126. {
  127. var last_output_builder = new StringBuilder();
  128. foreach (var token in _last_n_tokens)
  129. Context.NativeHandle.TokenToString(token, Context.Encoding, last_output_builder);
  130. var last_output = last_output_builder.ToString();
  131. foreach (var antiprompt in args.Antiprompts)
  132. {
  133. if (last_output.EndsWith(antiprompt))
  134. {
  135. args.WaitForInput = true;
  136. break;
  137. }
  138. }
  139. }
  140. if (_pastTokensCount > 0 && args.WaitForInput)
  141. {
  142. return true;
  143. }
  144. }
  145. if (_embeds.Count > 0 && _embeds.Last() == NativeApi.llama_token_eos(Context.NativeHandle))
  146. {
  147. extraOutputs = new[] { " [end of text]\n" };
  148. return true;
  149. }
  150. if (args.RemainedTokens <= 0 && inferenceParams.MaxTokens != -1)
  151. {
  152. args.RemainedTokens = inferenceParams.MaxTokens;
  153. args.WaitForInput = true;
  154. }
  155. return false;
  156. }
  157. /// <inheritdoc />
  158. protected override void InferInternal(IInferenceParams inferenceParams, InferStateArgs args)
  159. {
  160. if (_embeds.Count > 0)
  161. {
  162. _is_prompt_run = false;
  163. if (_pastTokensCount + _embeds.Count > Context.ContextSize)
  164. {
  165. HandleRunOutOfContext(inferenceParams.TokensKeep);
  166. }
  167. TryReuseMathingPrefix();
  168. _pastTokensCount = Context.Eval(_embeds, _pastTokensCount);
  169. if (_embeds.Count > 0 && !string.IsNullOrEmpty(_pathSession))
  170. {
  171. _session_tokens.AddRange(_embeds);
  172. _n_session_consumed = _session_tokens.Count;
  173. }
  174. }
  175. _embeds.Clear();
  176. if (_embed_inps.Count <= _consumedTokensCount && !args.WaitForInput)
  177. {
  178. var repeat_last_n = inferenceParams.RepeatLastTokensCount < 0 ? Context.ContextSize : inferenceParams.RepeatLastTokensCount;
  179. // optionally save the session on first sample (for faster prompt loading next time)
  180. if (!string.IsNullOrEmpty(_pathSession) && args.NeedToSaveSession)
  181. {
  182. args.NeedToSaveSession = false;
  183. SaveSessionFile(_pathSession);
  184. }
  185. var tokenDataArray = Context.ApplyPenalty(_last_n_tokens, inferenceParams.LogitBias, repeat_last_n,
  186. inferenceParams.RepeatPenalty, inferenceParams.FrequencyPenalty, inferenceParams.PresencePenalty, inferenceParams.PenalizeNL);
  187. var mu = MirostatMu;
  188. var id = Context.Sample(
  189. tokenDataArray, ref mu, inferenceParams.Temperature, inferenceParams.Mirostat, inferenceParams.MirostatTau,
  190. inferenceParams.MirostatEta, inferenceParams.TopK, inferenceParams.TopP, inferenceParams.TfsZ, inferenceParams.TypicalP,
  191. inferenceParams.Grammar
  192. );
  193. MirostatMu = mu;
  194. _last_n_tokens.Enqueue(id);
  195. if (id == NativeApi.llama_token_eos(Context.NativeHandle))
  196. {
  197. id = _llama_token_newline;
  198. if (args.Antiprompts is not null && args.Antiprompts.Count > 0)
  199. {
  200. var first_antiprompt = Context.Tokenize(args.Antiprompts[0], false);
  201. _embed_inps.AddRange(first_antiprompt);
  202. }
  203. }
  204. _embeds.Add(id);
  205. args.RemainedTokens--;
  206. args.ReturnValue = true;
  207. }
  208. else
  209. {
  210. while (_embed_inps.Count > _consumedTokensCount)
  211. {
  212. _embeds.Add(_embed_inps[_consumedTokensCount]);
  213. _last_n_tokens.Enqueue(_embed_inps[_consumedTokensCount]);
  214. _consumedTokensCount++;
  215. if (_embeds.Count >= Context.Params.BatchSize)
  216. {
  217. break;
  218. }
  219. }
  220. }
  221. }
  222. /// <summary>
  223. /// The descriptor of the state of the interactive executor.
  224. /// </summary>
  225. public class InteractiveExecutorState
  226. : ExecutorBaseState
  227. {
  228. /// <summary>
  229. /// Whether the executor is running for the first time (running the prompt).
  230. /// </summary>
  231. [JsonPropertyName("is_prompt_run")]
  232. public bool IsPromptRun { get; set; }
  233. }
  234. }
  235. }