sampling_params.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. min_p: Float that controls the cutoff for min-p sampling.
  47. Exact cutoff is min_p*max_prob. Must be in [0,1], 0 to disable.
  48. tfs: Float that controls the cummulative approximate curvature of the
  49. distribution to retain for Tail Free Sampling.
  50. Must be in (0, 1]. Set to 1 to disable
  51. eta_cutoff: Float that controls the cutoff treshold for Eta sampling
  52. (a form of entropy adaptive truncation sampling)
  53. treshold is computed as min(eta, sqrt(eta)*entropy(probs)).
  54. Specified in units of 1e-4. Set to 0 to disable
  55. epsilon_cutoff: Float that controls the cutoff treshold for
  56. Epsilon sampling (simple probability treshold truncation).
  57. Specified in units of 1e-4. Set to 0 to disable.
  58. typical_p: Float that controls the cumulative probability of tokens
  59. closest in surprise to the expected surprise to consider.
  60. Must be in (0, 1]. Set to 1 to disable.
  61. mirostat_mode: Can either be 0 (disabled) or 2 (Mirostat v2).
  62. mirostat_tau: Target "surprisal" that mirostat works towards.
  63. Range [0, inf).
  64. mirostat_eta: Rate at which mirostat updates its internal surprisal
  65. value. Range [0, inf).
  66. use_beam_search: Whether to use beam search instead of sampling.
  67. length_penalty: Float that penalizes sequences based on their length.
  68. Used in beam search.
  69. early_stopping: Controls the stopping condition for beam search. It
  70. accepts the following values: `True`, where the generation stops as
  71. soon as there are `best_of` complete candidates; `False`, where an
  72. heuristic is applied and the generation stops when is it very
  73. unlikely to find better candidates; `"never"`, where the beam search
  74. procedure only stops when there cannot be better candidates
  75. (canonical beam search algorithm).
  76. stop: List of strings that stop the generation when they are generated.
  77. The returned output will not contain the stop strings.
  78. stop_token_ids: List of tokens that stop the generation when they are
  79. generated. The returned output will contain the stop tokens unless
  80. the stop tokens are sepcial tokens.
  81. include_stop_str_in_output: Whether to include the stop strings in
  82. output text. Defaults to False.
  83. ignore_eos: Whether to ignore the EOS token and continue generating
  84. tokens after the EOS token is generated.
  85. max_tokens: Maximum number of tokens to generate per output sequence.
  86. logprobs: Number of log probabilities to return per output token.
  87. Note that the implementation follows the OpenAI API: The return
  88. result includes the log probabilities on the `logprobs` most likely
  89. tokens, as well the chosen tokens. The API will always return the
  90. log probability of the sampled token, so there may be up to
  91. `logprobs+1` elements in the response.
  92. prompt_logprobs: Number of log probabilities to return per prompt token.
  93. custom_token_bans: List of token IDs to ban from generating
  94. skip_special_tokens: Whether to skip special tokens in the output.
  95. defaults to true.
  96. spaces_between_special_tokens: Whether to add spaces between special
  97. tokens in the output. Defaults to True.
  98. logits_processors: List of LogitsProcessors to change the probability
  99. of token prediction at runtime.
  100. """
  101. def __init__(
  102. self,
  103. n: int = 1,
  104. best_of: Optional[int] = None,
  105. presence_penalty: float = 0.0,
  106. frequency_penalty: float = 0.0,
  107. repetition_penalty: float = 1.0,
  108. temperature: float = 1.0,
  109. top_p: float = 1.0,
  110. top_k: int = -1,
  111. top_a: float = 0.0,
  112. min_p: float = 0.0,
  113. tfs: float = 1.0,
  114. eta_cutoff: float = 0.0,
  115. epsilon_cutoff: float = 0.0,
  116. typical_p: float = 1.0,
  117. mirostat_mode: int = 0,
  118. mirostat_tau: float = 0,
  119. mirostat_eta: float = 0,
  120. use_beam_search: bool = False,
  121. length_penalty: float = 1.0,
  122. early_stopping: Union[bool, str] = False,
  123. stop: Union[None, str, List[str]] = None,
  124. stop_token_ids: List[int] = None,
  125. include_stop_str_in_output: bool = False,
  126. ignore_eos: bool = False,
  127. max_tokens: int = 16,
  128. logprobs: Optional[int] = None,
  129. prompt_logprobs: Optional[int] = None,
  130. custom_token_bans: Optional[List[int]] = None,
  131. skip_special_tokens: bool = True,
  132. spaces_between_special_tokens: bool = True,
  133. logits_processors: List[LogitsProcessor] = None,
  134. ) -> None:
  135. self.n = n
  136. self.best_of = best_of if best_of is not None else n
  137. self.presence_penalty = presence_penalty
  138. self.frequency_penalty = frequency_penalty
  139. self.repetition_penalty = repetition_penalty
  140. self.temperature = temperature
  141. self.top_p = top_p
  142. self.top_k = top_k
  143. self.top_a = top_a
  144. self.min_p = min_p
  145. self.tfs = tfs
  146. self.eta_cutoff = eta_cutoff
  147. self.epsilon_cutoff = epsilon_cutoff
  148. self.typical_p = typical_p
  149. self.mirostat_mode = mirostat_mode
  150. self.mirostat_tau = mirostat_tau
  151. self.mirostat_eta = mirostat_eta
  152. self.use_beam_search = use_beam_search
  153. self.length_penalty = length_penalty
  154. self.early_stopping = early_stopping
  155. if stop is None:
  156. self.stop = []
  157. elif isinstance(stop, str):
  158. self.stop = [stop]
  159. else:
  160. self.stop = list(stop)
  161. if stop_token_ids is None:
  162. self.stop_token_ids = []
  163. else:
  164. self.stop_token_ids = list(stop_token_ids)
  165. self.ignore_eos = ignore_eos
  166. self.max_tokens = max_tokens
  167. self.logprobs = logprobs
  168. self.prompt_logprobs = prompt_logprobs
  169. self.custom_token_bans = custom_token_bans or []
  170. self.skip_special_tokens = skip_special_tokens
  171. self.spaces_between_special_tokens = spaces_between_special_tokens
  172. self.logits_processors = logits_processors or []
  173. self.include_stop_str_in_output = include_stop_str_in_output
  174. self.verify()
  175. if self.use_beam_search:
  176. self._verify_beam_search()
  177. else:
  178. self._verify_non_beam_search()
  179. if self.temperature < _SAMPLING_EPS:
  180. # Zero temperature means greedy sampling.
  181. self.top_p = 1.0
  182. self.top_k = -1
  183. self.min_p = 0.0
  184. self.top_a = 0.0
  185. self._verify_greedy_sampling()
  186. def verify(self) -> None:
  187. self._verify_args()
  188. if self.use_beam_search:
  189. self._verify_beam_search()
  190. else:
  191. self._verify_non_beam_search()
  192. if self.temperature < _SAMPLING_EPS:
  193. # Zero temperature means greedy sampling.
  194. self._verify_greedy_sampling()
  195. def _verify_args(self) -> None:
  196. if self.n < 1:
  197. raise ValueError(f"n must be at least 1, got {self.n}.")
  198. if self.best_of < self.n:
  199. raise ValueError(f"best_of must be greater than or equal to n, "
  200. f"got n={self.n} and best_of={self.best_of}.")
  201. if not -2.0 <= self.presence_penalty <= 2.0:
  202. raise ValueError("presence_penalty must be in [-2, 2], got "
  203. f"{self.presence_penalty}.")
  204. if not -2.0 <= self.frequency_penalty <= 2.0:
  205. raise ValueError("frequency_penalty must be in [-2, 2], got "
  206. f"{self.frequency_penalty}.")
  207. if self.repetition_penalty < 1.0:
  208. raise ValueError("repetition_penalty must be in [1, inf), got "
  209. f"{self.repetition_penalty}.")
  210. if self.temperature < 0.0:
  211. raise ValueError(
  212. f"temperature must be non-negative, got {self.temperature}.")
  213. if not 0.0 < self.top_p <= 1.0:
  214. raise ValueError(f"top_p must be in (0, 1], got {self.top_p}.")
  215. if self.top_k < -1 or self.top_k == 0:
  216. raise ValueError(f"top_k must be -1 (disable), or at least 1, "
  217. f"got {self.top_k}.")
  218. if self.top_a < 0:
  219. raise ValueError(f"top_a must be non negative, got {self.top_a}.")
  220. if not 0.0 <= self.min_p <= 1.0:
  221. raise ValueError(f"min_p must be in [0, 1], got {self.min_p}.")
  222. if not 0.0 < self.tfs <= 1.0:
  223. raise ValueError(f"tfs must be in (0, 1], got {self.tfs}.")
  224. if self.epsilon_cutoff < 0.0 or self.epsilon_cutoff > 1000.0:
  225. raise ValueError("epsilon_cutoff must be in [0, 1000], got "
  226. f"{self.epsilon_cutoff}.")
  227. # pylint: disable=unneeded-not
  228. if not self.eta_cutoff >= 0:
  229. raise ValueError(
  230. f"eta_cutoff must be non negative, got {self.eta_cutoff}.")
  231. if not 0.0 <= self.typical_p <= 1.0:
  232. raise ValueError(
  233. f"typical_p must be in (0, 1], got {self.typical_p}.")
  234. if self.mirostat_mode:
  235. if not self.mirostat_mode == 2:
  236. raise ValueError(
  237. "Only Mirostat v2 (2) and disabled (0) supported, "
  238. f"got {self.mirostat_mode}")
  239. if not self.mirostat_eta >= 0:
  240. raise ValueError(
  241. f"mirostat_eta must be positive, got {self.mirostat_eta}")
  242. if not self.mirostat_tau >= 0:
  243. raise ValueError(
  244. f"mirostat_tau must be positive, got {self.mirostat_tau}")
  245. if self.max_tokens < 1:
  246. raise ValueError(
  247. f"max_tokens must be at least 1, got {self.max_tokens}.")
  248. if self.logprobs is not None and self.logprobs < 0:
  249. raise ValueError(
  250. f"logprobs must be non-negative, got {self.logprobs}.")
  251. if self.prompt_logprobs is not None and self.prompt_logprobs < 0:
  252. raise ValueError("prompt_logprobs must be non-negative, got "
  253. f"{self.prompt_logprobs}.")
  254. def _verify_beam_search(self) -> None:
  255. if self.best_of == 1:
  256. raise ValueError("best_of must be greater than 1 when using beam "
  257. f"search. Got {self.best_of}.")
  258. if self.temperature > _SAMPLING_EPS:
  259. raise ValueError("temperature must be 0 when using beam search.")
  260. if self.top_p < 1.0 - _SAMPLING_EPS:
  261. raise ValueError("top_p must be 1 when using beam search.")
  262. if self.top_k != -1:
  263. raise ValueError("top_k must be -1 when using beam search.")
  264. if self.early_stopping not in [True, False, "never"]:
  265. raise ValueError(
  266. f"early_stopping must be True, False, or 'never', "
  267. f"got {self.early_stopping}.")
  268. def _verify_non_beam_search(self) -> None:
  269. if self.early_stopping is not False:
  270. raise ValueError("early_stopping is not effective and must be "
  271. "False when not using beam search.")
  272. if (self.length_penalty < 1.0 - _SAMPLING_EPS
  273. or self.length_penalty > 1.0 + _SAMPLING_EPS):
  274. raise ValueError(
  275. "length_penalty is not effective and must be the "
  276. "default value of 1.0 when not using beam search.")
  277. def _verify_greedy_sampling(self) -> None:
  278. if self.best_of > 1:
  279. raise ValueError("best_of must be 1 when using greedy sampling."
  280. f"Got {self.best_of}.")
  281. if self.top_p < 1.0 - _SAMPLING_EPS:
  282. raise ValueError("top_p must be 1 when using greedy sampling.")
  283. if self.top_k != -1:
  284. raise ValueError("top_k must be -1 when using greedy sampling.")
  285. @cached_property
  286. def sampling_type(self) -> SamplingType:
  287. if self.use_beam_search:
  288. return SamplingType.BEAM
  289. if self.temperature < _SAMPLING_EPS:
  290. return SamplingType.GREEDY
  291. return SamplingType.RANDOM
  292. def __repr__(self) -> str:
  293. return (f"SamplingParams(n={self.n}, "
  294. f"best_of={self.best_of}, "
  295. f"presence_penalty={self.presence_penalty}, "
  296. f"frequency_penalty={self.frequency_penalty}, "
  297. f"repetition_penalty={self.repetition_penalty}, "
  298. f"temperature={self.temperature}, "
  299. f"top_p={self.top_p}, "
  300. f"top_k={self.top_k}, "
  301. f"top_a={self.top_a}, "
  302. f"min_p={self.min_p}, "
  303. f"tfs={self.tfs}, "
  304. f"eta_cutoff={self.eta_cutoff}, "
  305. f"epsilon_cutoff={self.epsilon_cutoff}, "
  306. f"typical_p={self.typical_p}, "
  307. f"mirostat_mode={self.mirostat_mode}, "
  308. f"mirostat_tau={self.mirostat_tau}, "
  309. f"mirostat_eta={self.mirostat_eta}, "
  310. f"use_beam_search={self.use_beam_search}, "
  311. f"length_penalty={self.length_penalty}, "
  312. f"early_stopping={self.early_stopping}, "
  313. f"stop={self.stop}, "
  314. f"stop_token_ids={self.stop_token_ids}, "
  315. "include_stop_str_in_output="
  316. f"{self.include_stop_str_in_output}, "
  317. f"ignore_eos={self.ignore_eos}, "
  318. f"max_tokens={self.max_tokens}, "
  319. f"custom_token_bans={self.custom_token_bans}, "
  320. f"logprobs={self.logprobs}, "
  321. f"prompt_logprobs={self.prompt_logprobs}, "
  322. f"skip_special_tokens={self.skip_special_tokens}, "
  323. "spaces_between_special_tokens="
  324. f"{self.spaces_between_special_tokens})")