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.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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.Extensions;
  10. using LLama.Native;
  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. /// <summary>
  24. /// The context used by the executor when running the inference.
  25. /// </summary>
  26. public LLamaContext Context { get; private set; }
  27. /// <summary>
  28. /// Create a new stateless executor which will use the given model
  29. /// </summary>
  30. /// <param name="weights"></param>
  31. /// <param name="params"></param>
  32. public StatelessExecutor(LLamaWeights weights, IContextParams @params)
  33. {
  34. _weights = weights;
  35. _params = @params;
  36. Context = _weights.CreateContext(_params);
  37. Context.Dispose();
  38. }
  39. /// <inheritdoc />
  40. public async IAsyncEnumerable<string> InferAsync(string text, IInferenceParams? inferenceParams = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
  41. {
  42. using var context = _weights.CreateContext(_params);
  43. Context = context;
  44. if (!Context.NativeHandle.IsClosed)
  45. Context.Dispose();
  46. Context = _weights.CreateContext(Context.Params);
  47. if (inferenceParams != null)
  48. {
  49. if (inferenceParams.TokensKeep > Context.ContextSize)
  50. throw new ArgumentOutOfRangeException(nameof(inferenceParams), $"TokensKeep ({inferenceParams.TokensKeep}) cannot be larger than ContextSize ({Context.ContextSize})");
  51. }
  52. cancellationToken.ThrowIfCancellationRequested();
  53. var antiprompts = inferenceParams?.AntiPrompts.ToArray() ?? Array.Empty<string>();
  54. inferenceParams ??= new InferenceParams();
  55. var lastTokens = new List<llama_token>(inferenceParams.RepeatLastTokensCount);
  56. for (var i = 0; i < inferenceParams.RepeatLastTokensCount; i++)
  57. lastTokens.Add(0);
  58. var tokens = Context.Tokenize(text).ToList();
  59. await Task.Run(() => { Context.Eval(tokens, 1); }, cancellationToken)
  60. .ConfigureAwait(false);
  61. lastTokens.AddRange(tokens);
  62. var n_past = 1 + tokens.Count;
  63. var mu = (float?)null;
  64. var max_tokens = inferenceParams.MaxTokens < 0 ? int.MaxValue : inferenceParams.MaxTokens;
  65. for(var i = 0; i < max_tokens; i++)
  66. {
  67. if (cancellationToken.IsCancellationRequested)
  68. break;
  69. var repeat_last_n = inferenceParams.RepeatLastTokensCount < 0 ? Context.ContextSize : inferenceParams.RepeatLastTokensCount;
  70. var tokenDataArray = Context.ApplyPenalty(lastTokens, inferenceParams.LogitBias, repeat_last_n,
  71. inferenceParams.RepeatPenalty, inferenceParams.FrequencyPenalty, inferenceParams.PresencePenalty, inferenceParams.PenalizeNL);
  72. var id = Context.Sample(tokenDataArray, ref mu, inferenceParams.Temperature, inferenceParams.Mirostat, inferenceParams.MirostatTau,
  73. inferenceParams.MirostatEta, inferenceParams.TopK, inferenceParams.TopP, inferenceParams.TfsZ, inferenceParams.TypicalP, inferenceParams.Grammar);
  74. lastTokens.Add(id);
  75. yield return Context.TokenToString(id);
  76. tokens.Clear();
  77. tokens.Add(id);
  78. // Check if any of the antiprompts have been generated
  79. if (lastTokens.TokensEndsWithAnyString(antiprompts, Context))
  80. break;
  81. // when run out of context
  82. // based on this logic: https://github.com/ggerganov/llama.cpp/blob/master/examples/main/main.cpp#L497
  83. if (n_past + tokens.Count >= Context.ContextSize)
  84. {
  85. var n_left = n_past - inferenceParams.TokensKeep - 1;
  86. var n_discard = n_left / 2;
  87. NativeApi.llama_kv_cache_seq_rm(Context.NativeHandle, (LLamaSeqId)0, inferenceParams.TokensKeep + 1, inferenceParams.TokensKeep + n_discard + 1);
  88. NativeApi.llama_kv_cache_seq_shift(Context.NativeHandle, (LLamaSeqId)0, inferenceParams.TokensKeep + 1 + n_discard, n_past, -n_discard);
  89. n_past -= n_discard;
  90. }
  91. // ReSharper disable once AccessToModifiedClosure (Justification: n_past is modified inside and outside the capture, but not concurrently)
  92. n_past = await Task.Run(() => Context.Eval(tokens, n_past), cancellationToken)
  93. .ConfigureAwait(false);
  94. }
  95. }
  96. }
  97. }