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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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 LLama.Exceptions;
  9. using LLama.Native;
  10. using LLama.Sampling;
  11. using Microsoft.Extensions.Logging;
  12. namespace LLama
  13. {
  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. private readonly LLamaBatch _batch;
  25. // LLava Section
  26. public bool IsMultiModal => false;
  27. public bool MultiModalProject { get; }
  28. public LLavaWeights? ClipModel { get; }
  29. public List<string> ImagePaths { get; set; }
  30. /// <summary>
  31. /// The context used by the executor when running the inference.
  32. /// </summary>
  33. public LLamaContext Context { get; private set; }
  34. /// <summary>
  35. /// Create a new stateless executor which will use the given model
  36. /// </summary>
  37. /// <param name="weights"></param>
  38. /// <param name="params"></param>
  39. /// <param name="logger"></param>
  40. public StatelessExecutor(LLamaWeights weights, IContextParams @params, ILogger? logger = null)
  41. {
  42. ImagePaths = new List<string>();
  43. _weights = weights;
  44. _params = @params;
  45. _logger = logger;
  46. _batch = new LLamaBatch();
  47. Context = _weights.CreateContext(_params, logger);
  48. Context.Dispose();
  49. }
  50. /// <inheritdoc />
  51. public async IAsyncEnumerable<string> InferAsync(string prompt, IInferenceParams? inferenceParams = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
  52. {
  53. // Ensure the context from last time is disposed (it always hould be)
  54. if (!Context.NativeHandle.IsClosed)
  55. Context.Dispose();
  56. // Create an inference context which will be disposed when this method exits
  57. using var context = _weights.CreateContext(_params, _logger);
  58. Context = context;
  59. // Reset the sampling pipeline (if there is one)
  60. inferenceParams?.SamplingPipeline?.Reset();
  61. // Sanity check inference params
  62. inferenceParams ??= new InferenceParams();
  63. if (inferenceParams.TokensKeep > Context.ContextSize)
  64. throw new ArgumentOutOfRangeException(nameof(inferenceParams), $"TokensKeep ({inferenceParams.TokensKeep}) cannot be larger than ContextSize ({Context.ContextSize})");
  65. // Create decoders for the token stream
  66. var decoder = new StreamingTokenDecoder(Context);
  67. var antiprocessor = new AntipromptProcessor(inferenceParams.AntiPrompts);
  68. // Keep track of the last N tokens emitted
  69. var repeat_last_n = Math.Max(0, inferenceParams.RepeatLastTokensCount <0 ? _weights.ContextSize : inferenceParams.RepeatLastTokensCount);
  70. var lastTokens = new List<LLamaToken>(repeat_last_n);
  71. for (var i = 0; i < repeat_last_n; i++)
  72. lastTokens.Add(0);
  73. // Tokenize the prompt
  74. var tokens = Context.Tokenize(prompt).ToList();
  75. lastTokens.AddRange(tokens);
  76. // Evaluate the prompt, in chunks smaller than the max batch size
  77. var n_past = 0;
  78. var (r, _) = Context.NativeHandle.Decode(tokens, LLamaSeqId.Zero, _batch, ref n_past);
  79. if (r != DecodeResult.Ok)
  80. throw new LLamaDecodeError(r);
  81. // Begin loop, evaluating one token at a time
  82. var mu = (float?)null;
  83. var max_tokens = inferenceParams.MaxTokens < 0 ? int.MaxValue : inferenceParams.MaxTokens;
  84. for(var i = 0; i < max_tokens && !cancellationToken.IsCancellationRequested; i++)
  85. {
  86. LLamaToken id;
  87. if (inferenceParams.SamplingPipeline is not null)
  88. {
  89. id = inferenceParams.SamplingPipeline.Sample(Context.NativeHandle, Context.NativeHandle.GetLogitsIth(_batch.TokenCount - 1), lastTokens);
  90. }
  91. else
  92. {
  93. // Penalize the generated tokens by various penalties
  94. var tokenDataArray = Context.ApplyPenalty(_batch.TokenCount - 1, lastTokens, inferenceParams.LogitBias, repeat_last_n,
  95. inferenceParams.RepeatPenalty, inferenceParams.FrequencyPenalty, inferenceParams.PresencePenalty, inferenceParams.PenalizeNL);
  96. // Sample a single token
  97. id = Context.Sample(
  98. tokenDataArray, ref mu, inferenceParams.Temperature, inferenceParams.Mirostat, inferenceParams.MirostatTau,
  99. inferenceParams.MirostatEta, inferenceParams.TopK, inferenceParams.TopP, inferenceParams.TfsZ, inferenceParams.TypicalP, inferenceParams.Grammar,
  100. inferenceParams.MinP
  101. );
  102. }
  103. // Check if this is the EOS token
  104. if (id == _weights.EndOfSentenceToken)
  105. break;
  106. // Decode this token into text
  107. decoder.Add(id);
  108. var decoded = decoder.Read();
  109. yield return decoded;
  110. // Check if any of the antiprompts have been generated
  111. if (antiprocessor.Add(decoded))
  112. break;
  113. lastTokens.Add(id);
  114. tokens.Clear();
  115. tokens.Add(id);
  116. // when run out of context
  117. // based on this logic: https://github.com/ggerganov/llama.cpp/blob/master/examples/main/main.cpp#L497
  118. if (n_past + tokens.Count >= Context.ContextSize)
  119. {
  120. var n_left = n_past - inferenceParams.TokensKeep - 1;
  121. var n_discard = n_left / 2;
  122. NativeApi.llama_kv_cache_seq_rm(Context.NativeHandle, (LLamaSeqId)0, inferenceParams.TokensKeep + 1, inferenceParams.TokensKeep + n_discard + 1);
  123. NativeApi.llama_kv_cache_seq_add(Context.NativeHandle, (LLamaSeqId)0, inferenceParams.TokensKeep + 1 + n_discard, n_past, -n_discard);
  124. n_past -= n_discard;
  125. }
  126. // Evaluate with this new token
  127. _batch.Clear();
  128. _batch.Add(id, n_past++, LLamaSeqId.Zero, true);
  129. var returnCode = await context.DecodeAsync(_batch, cancellationToken);
  130. if (returnCode != 0)
  131. throw new LLamaDecodeError(returnCode);
  132. }
  133. }
  134. }
  135. }