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