1
0

sampling_params.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. """Sampling parameters for text generation."""
  2. from enum import IntEnum
  3. from functools import cached_property
  4. from typing import List, Optional, Union
  5. from aphrodite.common.logits_processor import LogitsProcessor
  6. _SAMPLING_EPS = 1e-5
  7. class SamplingType(IntEnum):
  8. GREEDY = 0
  9. RANDOM = 1
  10. BEAM = 2
  11. class SamplingParams:
  12. """Sampling parameters for text generation.
  13. Overall, we follow the sampling parameters from the OpenAI text completion
  14. API (https://platform.openai.com/docs/api-reference/completions/create).
  15. In addition, we support multiple additional samplers which are not supported
  16. by OpenAI.
  17. Args:
  18. n: Number of output sequences to return for the given prompt.
  19. best_of: Number of output sequences that are generated from the prompt.
  20. From these `best_of` sequences, the top `n` sequences are returned.
  21. `best_of` must be greater than or equal to `n`. This is treated as
  22. the beam width when `use_beam_search` is True. By default, `best_of`
  23. is set to `n`.
  24. presence_penalty: Float that penalizes new tokens based on whether they
  25. appear in the generated text so far. Values > 0 encourage the model
  26. to use new tokens, while values < 0 encourage the model to repeat
  27. tokens.
  28. frequency_penalty: Float that penalizes new tokens based on their
  29. frequency in the generated text so far. Values > 0 encourage the
  30. model to use new tokens, while values < 0 encourage the model to
  31. repeat tokens.
  32. repetition_penalty: Float that penalizes new tokens based on their
  33. frequency in the generated text so far.
  34. freq_pen is applied additively while
  35. rep_pen is applied multiplicatively.
  36. Must be in [1, inf). Set to 1 to disable the effect.
  37. temperature: Float that controls the randomness of the sampling. Lower
  38. values make the model more deterministic, while higher values make
  39. the model more random. Zero means greedy sampling.
  40. top_p: Float that controls the cumulative probability of the top tokens
  41. to consider. Must be in (0, 1]. Set to 1 to consider all tokens.
  42. top_k: Integer that controls the number of top tokens to consider. Set
  43. to -1 to consider all tokens.
  44. top_a: Float that controls the cutoff for Top-A sampling.
  45. Exact cutoff is top_a*max_prob**2. Must be in [0,inf], 0 to disable.
  46. tfs: Float that controls the cummulative approximate curvature of the
  47. distribution to retain for Tail Free Sampling.
  48. Must be in (0, 1]. Set to 1 to disable
  49. eta_cutoff: Float that controls the cutoff treshold for Eta sampling
  50. (a form of entropy adaptive truncation sampling)
  51. treshold is computed as min(eta, sqrt(eta)*entropy(probs)).
  52. Specified in units of 1e-4. Set to 0 to disable
  53. epsilon_cutoff: Float that controls the cutoff treshold for Epsilon sampling
  54. (simple probability treshold truncation).
  55. Specified in units of 1e-4. Set to 0 to disable.
  56. typical_p: Float that controls the cumulative probability of tokens
  57. closest in surprise to the expected surprise to consider.
  58. Must be in (0, 1]. Set to 1 to disable.
  59. use_beam_search: Whether to use beam search instead of sampling.
  60. length_penalty: Float that penalizes sequences based on their length.
  61. Used in beam search.
  62. early_stopping: Controls the stopping condition for beam search. It
  63. accepts the following values: `True`, where the generation stops as
  64. soon as there are `best_of` complete candidates; `False`, where an
  65. heuristic is applied and the generation stops when is it very
  66. unlikely to find better candidates; `"never"`, where the beam search
  67. procedure only stops when there cannot be better candidates
  68. (canonical beam search algorithm).
  69. stop: List of strings that stop the generation when they are generated.
  70. The returned output will not contain the stop strings.
  71. stop_token_ids: List of tokens that stop the generation when they are
  72. generated. The returned output will contain the stop tokens unless
  73. the stop tokens are sepcial tokens.
  74. ignore_eos: Whether to ignore the EOS token and continue generating
  75. tokens after the EOS token is generated.
  76. max_tokens: Maximum number of tokens to generate per output sequence.
  77. logprobs: Number of log probabilities to return per output token.
  78. Note that the implementation follows the OpenAI API: The return
  79. result includes the log probabilities on the `logprobs` most likely
  80. tokens, as well the chosen tokens. The API will always return the
  81. log probability of the sampled token, so there may be up to
  82. `logprobs+1` elements in the response.
  83. prompt_logprobs: Number of log probabilities to return per prompt token.
  84. custom_token_bans: List of token IDs to ban from generating
  85. skip_special_tokens: Whether to skip special tokens in the output.
  86. defaults to true.
  87. logits_processors: List of LogitsProcessors to change the probability
  88. of token prediction at runtime.
  89. """
  90. def __init__(
  91. self,
  92. n: int = 1,
  93. best_of: Optional[int] = None,
  94. presence_penalty: float = 0.0,
  95. frequency_penalty: float = 0.0,
  96. repetition_penalty: float = 1.0,
  97. temperature: float = 1.0,
  98. top_p: float = 1.0,
  99. top_k: int = -1,
  100. top_a: float = 0.0,
  101. tfs: float = 1.0,
  102. eta_cutoff: float = 0.0,
  103. epsilon_cutoff: float = 0.0,
  104. typical_p: float = 1.0,
  105. use_beam_search: bool = False,
  106. length_penalty: float = 1.0,
  107. early_stopping: Union[bool, str] = False,
  108. stop: Union[None, str, List[str]] = None,
  109. stop_token_ids: List[int] = None,
  110. ignore_eos: bool = False,
  111. max_tokens: int = 16,
  112. logprobs: Optional[int] = None,
  113. prompt_logprobs: Optional[int] = None,
  114. custom_token_bans: Optional[List[int]] = None,
  115. skip_special_tokens: bool = True,
  116. logits_processors: List[LogitsProcessor] = None,
  117. ) -> None:
  118. self.n = n
  119. self.best_of = best_of if best_of is not None else n
  120. self.presence_penalty = presence_penalty
  121. self.frequency_penalty = frequency_penalty
  122. self.repetition_penalty = repetition_penalty
  123. self.temperature = temperature
  124. self.top_p = top_p
  125. self.top_k = top_k
  126. self.top_a = top_a
  127. self.tfs = tfs
  128. self.eta_cutoff = eta_cutoff
  129. self.epsilon_cutoff = epsilon_cutoff
  130. self.typical_p = typical_p
  131. self.use_beam_search = use_beam_search
  132. self.length_penalty = length_penalty
  133. self.early_stopping = early_stopping
  134. if stop is None:
  135. self.stop = []
  136. elif isinstance(stop, str):
  137. self.stop = [stop]
  138. else:
  139. self.stop = list(stop)
  140. if stop_token_ids is None:
  141. self.stop_token_ids = []
  142. else:
  143. self.stop_token_ids = list(stop_token_ids)
  144. self.ignore_eos = ignore_eos
  145. self.max_tokens = max_tokens
  146. self.logprobs = logprobs
  147. self.prompt_logprobs = prompt_logprobs
  148. self.custom_token_bans = custom_token_bans or []
  149. self.skip_special_tokens = skip_special_tokens
  150. self.logits_processors = logits_processors or []
  151. self._verify_args()
  152. if self.use_beam_search:
  153. self._verify_beam_search()
  154. else:
  155. self._verify_non_beam_search()
  156. if self.temperature < _SAMPLING_EPS:
  157. # Zero temperature means greedy sampling.
  158. self._verify_greedy_sampling()
  159. def _verify_args(self) -> None:
  160. if self.n < 1:
  161. raise ValueError(f"n must be at least 1, got {self.n}.")
  162. if self.best_of < self.n:
  163. raise ValueError(f"best_of must be greater than or equal to n, "
  164. f"got n={self.n} and best_of={self.best_of}.")
  165. if not -2.0 <= self.presence_penalty <= 2.0:
  166. raise ValueError("presence_penalty must be in [-2, 2], got "
  167. f"{self.presence_penalty}.")
  168. if not -2.0 <= self.frequency_penalty <= 2.0:
  169. raise ValueError("frequency_penalty must be in [-2, 2], got "
  170. f"{self.frequency_penalty}.")
  171. if not 1.0 <= self.repetition_penalty:
  172. raise ValueError("repetition_penalty must be in [1, inf), got "
  173. f"{self.repetition_penalty}.")
  174. if self.temperature < 0.0:
  175. raise ValueError(
  176. f"temperature must be non-negative, got {self.temperature}.")
  177. if not 0.0 < self.top_p <= 1.0:
  178. raise ValueError(f"top_p must be in (0, 1], got {self.top_p}.")
  179. if self.top_k < -1 or self.top_k == 0:
  180. raise ValueError(f"top_k must be -1 (disable), or at least 1, "
  181. f"got {self.top_k}.")
  182. if not 0.0 <= self.top_a <= 1.0:
  183. raise ValueError(f"top_a must be in [0, 1], got {self.top_a}.")
  184. if not 0.0 < self.tfs <= 1.0:
  185. raise ValueError(f"tfs must be in (0, 1], got {self.tfs}.")
  186. if not 0.0 <= self.epsilon_cutoff <= 1000.0:
  187. raise ValueError(
  188. f"epsilon_cutoff must be in [0, 1000], got {self.epsilon_cutoff}."
  189. )
  190. if not self.eta_cutoff >= 0:
  191. raise ValueError(
  192. f"eta_cutoff must be non negative, got {self.eta_cutoff}.")
  193. if not 0.0 <= self.typical_p <= 1.0:
  194. raise ValueError(
  195. f"typical_p must be in (0, 1], got {self.typical_p}.")
  196. if self.max_tokens < 1:
  197. raise ValueError(
  198. f"max_tokens must be at least 1, got {self.max_tokens}.")
  199. if self.logprobs is not None and self.logprobs < 0:
  200. raise ValueError(
  201. f"logprobs must be non-negative, got {self.logprobs}.")
  202. if self.prompt_logprobs is not None and self.prompt_logprobs < 0:
  203. raise ValueError(
  204. f"prompt_logprobs must be non-negative, got {self.prompt_logprobs}."
  205. )
  206. def _verify_beam_search(self) -> None:
  207. if self.best_of == 1:
  208. raise ValueError("best_of must be greater than 1 when using beam "
  209. f"search. Got {self.best_of}.")
  210. if self.temperature > _SAMPLING_EPS:
  211. raise ValueError("temperature must be 0 when using beam search.")
  212. if self.top_p < 1.0 - _SAMPLING_EPS:
  213. raise ValueError("top_p must be 1 when using beam search.")
  214. if self.top_k != -1:
  215. raise ValueError("top_k must be -1 when using beam search.")
  216. if self.early_stopping not in [True, False, "never"]:
  217. raise ValueError(
  218. f"early_stopping must be True, False, or 'never', "
  219. f"got {self.early_stopping}.")
  220. def _verify_non_beam_search(self) -> None:
  221. if self.early_stopping is not False:
  222. raise ValueError("early_stopping is not effective and must be "
  223. "False when not using beam search.")
  224. if (self.length_penalty < 1.0 - _SAMPLING_EPS
  225. or self.length_penalty > 1.0 + _SAMPLING_EPS):
  226. raise ValueError(
  227. "length_penalty is not effective and must be the "
  228. "default value of 1.0 when not using beam search.")
  229. def _verify_greedy_sampling(self) -> None:
  230. if self.best_of > 1:
  231. raise ValueError("best_of must be 1 when using greedy sampling."
  232. f"Got {self.best_of}.")
  233. if self.top_p < 1.0 - _SAMPLING_EPS:
  234. raise ValueError("top_p must be 1 when using greedy sampling.")
  235. if self.top_k != -1:
  236. raise ValueError("top_k must be -1 when using greedy sampling.")
  237. @cached_property
  238. def sampling_type(self) -> SamplingType:
  239. if self.use_beam_search:
  240. return SamplingType.BEAM
  241. if self.temperature < _SAMPLING_EPS:
  242. return SamplingType.GREEDY
  243. return SamplingType.RANDOM
  244. def __repr__(self) -> str:
  245. return (f"SamplingParams(n={self.n}, "
  246. f"best_of={self.best_of}, "
  247. f"presence_penalty={self.presence_penalty}, "
  248. f"frequency_penalty={self.frequency_penalty}, "
  249. f"repetition_penalty={self.repetition_penalty}, "
  250. f"temperature={self.temperature}, "
  251. f"top_p={self.top_p}, "
  252. f"top_k={self.top_k}, "
  253. f"top_a={self.top_a}, "
  254. f"tfs={self.tfs}, "
  255. f"eta_cutoff={self.eta_cutoff}, "
  256. f"epsilon_cutoff={self.epsilon_cutoff}, "
  257. f"typical_p={self.typical_p}, "
  258. f"use_beam_search={self.use_beam_search}, "
  259. f"length_penalty={self.length_penalty}, "
  260. f"early_stopping={self.early_stopping}, "
  261. f"stop={self.stop}, "
  262. f"ignore_eos={self.ignore_eos}, "
  263. f"max_tokens={self.max_tokens}, "
  264. f"custom_token_bans={self.custom_token_bans}, "
  265. f"logprobs={self.logprobs}, "
  266. f"prompt_logprobs={self.prompt_logprobs}, "
  267. f"skip_special_tokens={self.skip_special_tokens})")