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.2 kB

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