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.

LLamaInstructExecutor.cs 9.8 kB

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

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