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.

DefaultSamplingPipeline.cs 6.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. using System;
  2. using System.Collections.Generic;
  3. using LLama.Extensions;
  4. using LLama.Native;
  5. namespace LLama.Sampling;
  6. /// <summary>
  7. /// An implementation of ISamplePipeline which mimics the default llama.cpp sampling
  8. /// </summary>
  9. public sealed class DefaultSamplingPipeline
  10. : BaseSamplingPipeline
  11. {
  12. /// <summary>
  13. /// Bias values to add to certain logits
  14. /// </summary>
  15. public Dictionary<int, float> LogitBias { get; } = new();
  16. /// <summary>
  17. /// Repetition penalty, as described in https://arxiv.org/abs/1909.05858
  18. /// </summary>
  19. public float RepeatPenalty { get; set; }
  20. /// <summary>
  21. /// Frequency penalty as described by OpenAI: https://platform.openai.com/docs/api-reference/chat/create<br />
  22. /// Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text
  23. /// so far, decreasing the model's likelihood to repeat the same line verbatim.
  24. /// </summary>
  25. public float AlphaFrequency
  26. {
  27. get => _alphaFreq;
  28. set
  29. {
  30. if (value < -2)
  31. throw new ArgumentOutOfRangeException(nameof(value), "AlphaFrequency must be greater than -2");
  32. if (value > 2)
  33. throw new ArgumentOutOfRangeException(nameof(value), "AlphaFrequency must be less than 2");
  34. _alphaFreq = value;
  35. }
  36. }
  37. private float _alphaFreq;
  38. /// <summary>
  39. /// Presence penalty as described by OpenAI: https://platform.openai.com/docs/api-reference/chat/create<br />
  40. /// Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the
  41. /// text so far, increasing the model's likelihood to talk about new topics.
  42. /// </summary>
  43. public float AlphaPresence
  44. {
  45. get => _alphaPresence;
  46. set
  47. {
  48. if (value < -2)
  49. throw new ArgumentOutOfRangeException(nameof(value), "AlphaFrequency must be greater than -2");
  50. if (value > 2)
  51. throw new ArgumentOutOfRangeException(nameof(value), "AlphaFrequency must be less than 2");
  52. _alphaPresence = value;
  53. }
  54. }
  55. private float _alphaPresence;
  56. /// <summary>
  57. /// Temperature to apply (higher temperature is more "creative")
  58. /// </summary>
  59. public float Temperature { get; set; } = 0.75f;
  60. /// <summary>
  61. /// Number of tokens to keep in TopK sampling
  62. /// </summary>
  63. public int TopK { get; set; }
  64. /// <summary>
  65. /// Z value for tail free sampling
  66. /// </summary>
  67. public float TailFreeZ { get; set; }
  68. /// <summary>
  69. /// P value for locally typical sampling
  70. /// </summary>
  71. public float TypicalP { get; set; }
  72. /// <summary>
  73. /// P value for TopP sampling
  74. /// </summary>
  75. public float TopP { get; set; } = 1f;
  76. /// <summary>
  77. /// P value for MinP sampling
  78. /// </summary>
  79. public float MinP { get; set; }
  80. /// <summary>
  81. /// Whether the newline value should be protected from being modified by logit bias and repeat penalty
  82. /// </summary>
  83. public bool PenalizeNewline { get; set; } = false;
  84. /// <inheritdoc />
  85. protected override void ProcessLogits(SafeLLamaContextHandle ctx, Span<float> logits, ReadOnlySpan<LLamaToken> lastTokens)
  86. {
  87. // Apply logit bias
  88. foreach (var (key, value) in LogitBias)
  89. logits[key] += value;
  90. }
  91. /// <inheritdoc />
  92. protected override LLamaToken ProcessTokenDataArray(SafeLLamaContextHandle ctx, LLamaTokenDataArray candidates, ReadOnlySpan<LLamaToken> lastTokens)
  93. {
  94. // Only apply repetition penalty if we really must. Otherwise avoid all this work
  95. if (lastTokens.Length > 0 && (RepeatPenalty != 0 || AlphaFrequency != 0 || AlphaPresence != 0))
  96. {
  97. // Save the logit value for the newline token
  98. var (nlIndex, nlLogit) = PenalizeNewline ? GetNewlineLogit(ctx, candidates) : (-1, 0);
  99. // Apply penalties to candidates
  100. candidates.RepetitionPenalty(ctx, lastTokens, RepeatPenalty, AlphaFrequency, AlphaPresence);
  101. // Restore newline token
  102. if (!PenalizeNewline)
  103. SetNewlineLogit(ctx, candidates, nlIndex, nlLogit);
  104. }
  105. // Apply the normal llama.cpp pipeline
  106. candidates.ApplyGrammar(ctx, Grammar);
  107. candidates.TopK(ctx, TopK);
  108. candidates.TailFree(ctx, TailFreeZ);
  109. candidates.LocallyTypical(ctx, TypicalP);
  110. candidates.TopP(ctx, TopP);
  111. candidates.MinP(ctx, MinP);
  112. candidates.Temperature(ctx, Temperature);
  113. return candidates.SampleToken(ctx);
  114. }
  115. private static (int, float) GetNewlineLogit(SafeLLamaContextHandle ctx, LLamaTokenDataArray candidates)
  116. {
  117. var nlToken = NativeApi.llama_token_nl(ctx.ModelHandle);
  118. // Try using the ID as an index
  119. if (candidates.data.Span[(int)nlToken].id == nlToken)
  120. return ((int)nlToken, candidates.data.Span[(int)nlToken].logit);
  121. // Exhaustive search
  122. var span = candidates.data.Span;
  123. for (var i = 0; i < span.Length; i++)
  124. {
  125. if (span[i].id == nlToken)
  126. return (i, span[i].logit);
  127. }
  128. return (-1, 0);
  129. }
  130. private static void SetNewlineLogit(SafeLLamaContextHandle ctx, LLamaTokenDataArray candidates, int indexHint, float logit)
  131. {
  132. var nlToken = NativeApi.llama_token_nl(ctx.ModelHandle);
  133. // Try checking the index where we found it last time. It might not be there if `RepetitionPenalty` changed order
  134. if (indexHint >= 0 && candidates.data.Span[indexHint].id == nlToken)
  135. {
  136. candidates.data.Span[indexHint].logit = logit;
  137. return;
  138. }
  139. // Didn't find it, do an exhaustive search for it
  140. var span = candidates.data.Span;
  141. for (var i = 0; i < candidates.data.Length; i++)
  142. {
  143. if (span[i].id == nlToken)
  144. {
  145. span[i].logit = logit;
  146. return;
  147. }
  148. }
  149. }
  150. /// <inheritdoc />
  151. public override void Accept(SafeLLamaContextHandle ctx, LLamaToken token)
  152. {
  153. Grammar?.AcceptToken(ctx, token);
  154. }
  155. /// <inheritdoc />
  156. public override ISamplingPipeline Clone()
  157. {
  158. var clone = new DefaultSamplingPipeline();
  159. foreach (var (k, v) in LogitBias)
  160. clone.LogitBias.Add(k, v);
  161. clone.Grammar = Grammar?.Clone();
  162. clone.RepeatPenalty = RepeatPenalty;
  163. clone.AlphaFrequency = AlphaFrequency;
  164. clone.AlphaPresence = AlphaPresence;
  165. clone.Temperature = Temperature;
  166. clone.TopK = TopK;
  167. clone.TailFreeZ = TailFreeZ;
  168. clone.TypicalP = TypicalP;
  169. clone.TopP = TopP;
  170. clone.MinP = MinP;
  171. clone.PenalizeNewline = PenalizeNewline;
  172. return clone;
  173. }
  174. }