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

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