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

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

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