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.

LLamaStatelessExecutor.cs 5.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. using LLama.Abstractions;
  2. using LLama.Common;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Runtime.CompilerServices;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using LLama.Native;
  10. using Microsoft.Extensions.Logging;
  11. namespace LLama
  12. {
  13. using llama_token = Int32;
  14. /// <summary>
  15. /// This executor infer the input as one-time job. Previous inputs won't impact on the
  16. /// response to current input.
  17. /// </summary>
  18. public class StatelessExecutor
  19. : ILLamaExecutor
  20. {
  21. private readonly LLamaWeights _weights;
  22. private readonly IContextParams _params;
  23. private readonly ILogger? _logger;
  24. /// <summary>
  25. /// The context used by the executor when running the inference.
  26. /// </summary>
  27. public LLamaContext Context { get; private set; }
  28. /// <summary>
  29. /// Create a new stateless executor which will use the given model
  30. /// </summary>
  31. /// <param name="weights"></param>
  32. /// <param name="params"></param>
  33. /// <param name="logger"></param>
  34. public StatelessExecutor(LLamaWeights weights, IContextParams @params, ILogger? logger = null)
  35. {
  36. _weights = weights;
  37. _params = @params;
  38. _logger = logger;
  39. Context = _weights.CreateContext(_params, logger);
  40. Context.Dispose();
  41. }
  42. /// <inheritdoc />
  43. public async IAsyncEnumerable<string> InferAsync(string prompt, IInferenceParams? inferenceParams = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
  44. {
  45. // Ensure the context from last time is disposed (it always hould be)
  46. if (!Context.NativeHandle.IsClosed)
  47. Context.Dispose();
  48. // Create an inference context which will be disposed when this method exits
  49. using var context = _weights.CreateContext(_params, _logger);
  50. Context = context;
  51. // Sanity check inference params
  52. inferenceParams ??= new InferenceParams();
  53. if (inferenceParams.TokensKeep > Context.ContextSize)
  54. throw new ArgumentOutOfRangeException(nameof(inferenceParams), $"TokensKeep ({inferenceParams.TokensKeep}) cannot be larger than ContextSize ({Context.ContextSize})");
  55. // Create decoders for the token stream
  56. var decoder = new StreamingTokenDecoder(Context);
  57. var antiprocessor = new AntipromptProcessor(inferenceParams.AntiPrompts);
  58. // Keep track of the last N tokens emitted
  59. var repeat_last_n = Math.Max(0, inferenceParams.RepeatLastTokensCount <0 ? _weights.ContextSize : inferenceParams.RepeatLastTokensCount);
  60. var lastTokens = new List<llama_token>(repeat_last_n);
  61. for (var i = 0; i < repeat_last_n; i++)
  62. lastTokens.Add(0);
  63. // Tokenize the prompt
  64. var tokens = Context.Tokenize(prompt).ToList();
  65. lastTokens.AddRange(tokens);
  66. var n_past = 1 + tokens.Count;
  67. // Evaluate the prompt
  68. await Task.Run(() => { Context.Eval(tokens, 1); }, cancellationToken)
  69. .ConfigureAwait(false);
  70. // Begin loop, evaluating one token at a time
  71. var mu = (float?)null;
  72. var max_tokens = inferenceParams.MaxTokens < 0 ? int.MaxValue : inferenceParams.MaxTokens;
  73. for(var i = 0; i < max_tokens && !cancellationToken.IsCancellationRequested; i++)
  74. {
  75. // Penalize the generated tokens by various penalties
  76. var tokenDataArray = Context.ApplyPenalty(lastTokens, inferenceParams.LogitBias, repeat_last_n,
  77. inferenceParams.RepeatPenalty, inferenceParams.FrequencyPenalty, inferenceParams.PresencePenalty, inferenceParams.PenalizeNL);
  78. // Sample a single token
  79. var id = Context.Sample(
  80. tokenDataArray, ref mu, inferenceParams.Temperature, inferenceParams.Mirostat, inferenceParams.MirostatTau,
  81. inferenceParams.MirostatEta, inferenceParams.TopK, inferenceParams.TopP, inferenceParams.TfsZ, inferenceParams.TypicalP, inferenceParams.Grammar,
  82. inferenceParams.MinP
  83. );
  84. // Decode this token into text
  85. decoder.Add(id);
  86. var decoded = decoder.Read();
  87. yield return decoded;
  88. // Check if any of the antiprompts have been generated
  89. if (antiprocessor.Add(decoded))
  90. break;
  91. lastTokens.Add(id);
  92. tokens.Clear();
  93. tokens.Add(id);
  94. // when run out of context
  95. // based on this logic: https://github.com/ggerganov/llama.cpp/blob/master/examples/main/main.cpp#L497
  96. if (n_past + tokens.Count >= Context.ContextSize)
  97. {
  98. var n_left = n_past - inferenceParams.TokensKeep - 1;
  99. var n_discard = n_left / 2;
  100. NativeApi.llama_kv_cache_seq_rm(Context.NativeHandle, (LLamaSeqId)0, inferenceParams.TokensKeep + 1, inferenceParams.TokensKeep + n_discard + 1);
  101. NativeApi.llama_kv_cache_seq_shift(Context.NativeHandle, (LLamaSeqId)0, inferenceParams.TokensKeep + 1 + n_discard, n_past, -n_discard);
  102. n_past -= n_discard;
  103. }
  104. // ReSharper disable once AccessToModifiedClosure (Justification: n_past is modified inside and outside the capture, but not concurrently)
  105. n_past = await Task.Run(() => Context.Eval(tokens, n_past), cancellationToken)
  106. .ConfigureAwait(false);
  107. }
  108. }
  109. }
  110. }