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.

LlamaSharpTextGenerator.cs 5.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using LLama;
  2. using LLama.Common;
  3. using LLama.Native;
  4. using Microsoft.KernelMemory.AI;
  5. namespace LLamaSharp.KernelMemory
  6. {
  7. /// <summary>
  8. /// Provides text generation for LLamaSharp.
  9. /// </summary>
  10. public class LlamaSharpTextGenerator : ITextGenerator, IDisposable
  11. {
  12. private readonly LLamaWeights _weights;
  13. private readonly StatelessExecutor _executor;
  14. private readonly LLamaContext _context;
  15. private readonly InferenceParams? _defaultInferenceParams;
  16. private bool _ownsContext = false;
  17. private bool _ownsWeights = false;
  18. public int MaxTokenTotal { get; }
  19. /// <summary>
  20. /// Initializes a new instance of the <see cref="LlamaSharpTextGenerator"/> class.
  21. /// </summary>
  22. /// <param name="config">The configuration for LLamaSharp.</param>
  23. public LlamaSharpTextGenerator(LLamaSharpConfig config)
  24. {
  25. var parameters = new ModelParams(config.ModelPath)
  26. {
  27. ContextSize = config?.ContextSize ?? 2048,
  28. Seed = config?.Seed ?? 0,
  29. GpuLayerCount = config?.GpuLayerCount ?? 20,
  30. MainGpu = config?.MainGpu ?? 0,
  31. SplitMode = config?.SplitMode ?? GPUSplitMode.None
  32. };
  33. _weights = LLamaWeights.LoadFromFile(parameters);
  34. _context = _weights.CreateContext(parameters);
  35. _executor = new StatelessExecutor(_weights, parameters);
  36. _defaultInferenceParams = config?.DefaultInferenceParams;
  37. _ownsWeights = _ownsContext = true;
  38. MaxTokenTotal = (int)parameters.ContextSize;
  39. }
  40. /// <summary>
  41. /// Initializes a new instance of the <see cref="LlamaSharpTextGenerator"/> class from reused weights, context and executor.
  42. /// If executor is not specified, then a StatelessExecutor will be created with `context.Params`. So far only `StatelessExecutor` is expected.
  43. /// </summary>
  44. /// <param name="weights">A LLamaWeights object.</param>
  45. /// <param name="context">A LLamaContext object.</param>
  46. /// <param name="executor">An executor. Currently only StatelessExecutor is expected.</param>
  47. public LlamaSharpTextGenerator(LLamaWeights weights, LLamaContext context, StatelessExecutor? executor = null, InferenceParams? inferenceParams = null)
  48. {
  49. _weights = weights;
  50. _context = context;
  51. _executor = executor ?? new StatelessExecutor(_weights, _context.Params);
  52. _defaultInferenceParams = inferenceParams;
  53. MaxTokenTotal = (int)_context.Params.ContextSize;
  54. }
  55. /// <inheritdoc/>
  56. public void Dispose()
  57. {
  58. if (_ownsWeights)
  59. {
  60. _weights?.Dispose();
  61. }
  62. if (_ownsContext)
  63. {
  64. _context.Dispose();
  65. }
  66. }
  67. /// <inheritdoc/>
  68. public IAsyncEnumerable<string> GenerateTextAsync(string prompt, TextGenerationOptions options, CancellationToken cancellationToken = default)
  69. {
  70. return _executor.InferAsync(prompt, OptionsToParams(options, this._defaultInferenceParams), cancellationToken: cancellationToken);
  71. }
  72. private static InferenceParams OptionsToParams(TextGenerationOptions options, InferenceParams? defaultParams)
  73. {
  74. if (defaultParams != null)
  75. {
  76. return defaultParams with
  77. {
  78. AntiPrompts = defaultParams.AntiPrompts.Concat(options.StopSequences).ToList().AsReadOnly(),
  79. Temperature = options.Temperature == defaultParams.Temperature ? defaultParams.Temperature : (float)options.Temperature,
  80. MaxTokens = options.MaxTokens ?? defaultParams.MaxTokens,
  81. FrequencyPenalty = options.FrequencyPenalty == defaultParams.FrequencyPenalty ? defaultParams.FrequencyPenalty : (float)options.FrequencyPenalty,
  82. PresencePenalty = options.PresencePenalty == defaultParams.PresencePenalty ? defaultParams.PresencePenalty : (float)options.PresencePenalty,
  83. TopP = options.TopP == defaultParams.TopP ? defaultParams.TopP : (float)options.TopP
  84. };
  85. }
  86. else
  87. {
  88. return new InferenceParams()
  89. {
  90. AntiPrompts = options.StopSequences.ToList().AsReadOnly(),
  91. Temperature = (float)options.Temperature,
  92. MaxTokens = options.MaxTokens ?? 1024,
  93. FrequencyPenalty = (float)options.FrequencyPenalty,
  94. PresencePenalty = (float)options.PresencePenalty,
  95. TopP = (float)options.TopP,
  96. };
  97. }
  98. }
  99. /// <inheritdoc/>
  100. public int CountTokens(string text) => _context.Tokenize(text, special: true).Length;
  101. }
  102. }