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

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