sampling_params.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. """Sampling parameters for text generation."""
  2. from enum import IntEnum
  3. from functools import cached_property
  4. from typing import Callable, List, Optional, Union
  5. import torch
  6. _SAMPLING_EPS = 1e-5
  7. class SamplingType(IntEnum):
  8. GREEDY = 0
  9. RANDOM = 1
  10. RANDOM_SEED = 2
  11. BEAM = 3
  12. LogitsProcessorFunc = Callable[[torch.Tensor, List[List[int]]], None]
  13. """LogitsProcessorFunc takes a logits tensor and corresponding lists of
  14. previously generated output tokens, and modifies the logits tensor."""
  15. class SamplingParams:
  16. """Sampling parameters for text generation.
  17. Overall, we follow the sampling parameters from the OpenAI text completion
  18. API (https://platform.openai.com/docs/api-reference/completions/create).
  19. In addition, we support multiple additional samplers which are not supported
  20. by OpenAI.
  21. Args:
  22. n: Number of output sequences to return for the given prompt.
  23. best_of: Number of output sequences that are generated from the prompt.
  24. From these `best_of` sequences, the top `n` sequences are returned.
  25. `best_of` must be greater than or equal to `n`. This is treated as
  26. the beam width when `use_beam_search` is True. By default, `best_of`
  27. is set to `n`.
  28. presence_penalty: Float that penalizes new tokens based on whether they
  29. appear in the generated text so far. Values > 0 encourage the model
  30. to use new tokens, while values < 0 encourage the model to repeat
  31. tokens.
  32. frequency_penalty: Float that penalizes new tokens based on their
  33. frequency in the generated text so far. Values > 0 encourage the
  34. model to use new tokens, while values < 0 encourage the model to
  35. repeat tokens.
  36. repetition_penalty: Float that penalizes new tokens based on their
  37. frequency in the generated text so far.
  38. freq_pen is applied additively while
  39. rep_pen is applied multiplicatively.
  40. Must be in [1, inf). Set to 1 to disable the effect.
  41. temperature: Float that controls the randomness of the sampling. Lower
  42. values make the model more deterministic, while higher values make
  43. the model more random. Zero means greedy sampling.
  44. top_p: Float that controls the cumulative probability of the top tokens
  45. to consider. Must be in (0, 1]. Set to 1 to consider all tokens.
  46. top_k: Integer that controls the number of top tokens to consider. Set
  47. to -1 to consider all tokens.
  48. top_a: Float that controls the cutoff for Top-A sampling.
  49. Exact cutoff is top_a*max_prob**2. Must be in [0,inf], 0 to disable.
  50. min_p: Float that controls the cutoff for min-p sampling.
  51. Exact cutoff is min_p*max_prob. Must be in [0,1], 0 to disable.
  52. tfs: Float that controls the cumulative approximate curvature of the
  53. distribution to retain for Tail Free Sampling.
  54. Must be in (0, 1]. Set to 1 to disable
  55. eta_cutoff: Float that controls the cutoff threshold for Eta sampling
  56. (a form of entropy adaptive truncation sampling)
  57. threshold is computed as min(eta, sqrt(eta)*entropy(probs)).
  58. Specified in units of 1e-4. Set to 0 to disable
  59. epsilon_cutoff: Float that controls the cutoff threshold for
  60. Epsilon sampling (simple probability threshold truncation).
  61. Specified in units of 1e-4. Set to 0 to disable.
  62. typical_p: Float that controls the cumulative probability of tokens
  63. closest in surprise to the expected surprise to consider.
  64. Must be in (0, 1]. Set to 1 to disable.
  65. typical_p_sigma: Used to scale the maximum threshold for positive
  66. deviations in typical_p. Range in [0, inf). Set to 0 to disable.
  67. mirostat_mode: Can either be 0 (disabled) or 2 (Mirostat v2).
  68. mirostat_tau: Target "surprisal" that mirostat works towards.
  69. Range [0, inf).
  70. mirostat_eta: Rate at which mirostat updates its internal surprisal
  71. value. Range [0, inf).
  72. dynatemp_min: Minimum temperature for dynatemp sampling.
  73. Range [0, inf).
  74. dynatemp_max: Maximum temperature for dynatemp sampling.
  75. Range [0, inf).
  76. dynatemp_exponent: Exponent for dynatemp sampling. Range [0, inf).
  77. smoothing_factor: Smoothing factor for Quadratic Sampling.
  78. smoothing_curve: Smoothing curve for Quadratic (Cubic) Sampling.
  79. seed: Random seed to use for the generation.
  80. use_beam_search: Whether to use beam search instead of sampling.
  81. length_penalty: Float that penalizes sequences based on their length.
  82. Used in beam search.
  83. early_stopping: Controls the stopping condition for beam search. It
  84. accepts the following values: `True`, where the generation stops as
  85. soon as there are `best_of` complete candidates; `False`, where an
  86. heuristic is applied and the generation stops when is it very
  87. unlikely to find better candidates; `"never"`, where the beam search
  88. procedure only stops when there cannot be better candidates
  89. (canonical beam search algorithm).
  90. stop: List of strings that stop the generation when they are generated.
  91. The returned output will not contain the stop strings.
  92. stop_token_ids: List of tokens that stop the generation when they are
  93. generated. The returned output will contain the stop tokens unless
  94. the stop tokens are special tokens.
  95. include_stop_str_in_output: Whether to include the stop strings in
  96. output text. Defaults to False.
  97. ignore_eos: Whether to ignore the EOS token and continue generating
  98. tokens after the EOS token is generated.
  99. max_tokens: Maximum number of tokens to generate per output sequence.
  100. logprobs: Number of log probabilities to return per output token.
  101. Note that the implementation follows the OpenAI API: The return
  102. result includes the log probabilities on the `logprobs` most likely
  103. tokens, as well the chosen tokens. The API will always return the
  104. log probability of the sampled token, so there may be up to
  105. `logprobs+1` elements in the response.
  106. prompt_logprobs: Number of log probabilities to return per prompt token.
  107. custom_token_bans: List of token IDs to ban from generating
  108. skip_special_tokens: Whether to skip special tokens in the output.
  109. defaults to true.
  110. spaces_between_special_tokens: Whether to add spaces between special
  111. tokens in the output. Defaults to True.
  112. logits_processors: List of LogitsProcessors to change the probability
  113. of token prediction at runtime.
  114. """
  115. def __init__(
  116. self,
  117. n: int = 1,
  118. best_of: Optional[int] = None,
  119. presence_penalty: float = 0.0,
  120. frequency_penalty: float = 0.0,
  121. repetition_penalty: float = 1.0,
  122. temperature: float = 1.0,
  123. top_p: float = 1.0,
  124. top_k: int = -1,
  125. top_a: float = 0.0,
  126. min_p: float = 0.0,
  127. tfs: float = 1.0,
  128. eta_cutoff: float = 0.0,
  129. epsilon_cutoff: float = 0.0,
  130. typical_p: float = 1.0,
  131. typical_p_sigma: float = 0.0,
  132. mirostat_mode: int = 0,
  133. mirostat_tau: float = 0,
  134. mirostat_eta: float = 0,
  135. dynatemp_min: float = 0,
  136. dynatemp_max: float = 0,
  137. dynatemp_exponent: float = 1,
  138. smoothing_factor: float = 0.0,
  139. smoothing_curve: float = 1.0,
  140. seed: Optional[int] = None,
  141. use_beam_search: bool = False,
  142. length_penalty: float = 1.0,
  143. early_stopping: Union[bool, str] = False,
  144. stop: Union[None, str, List[str]] = None,
  145. stop_token_ids: Optional[List[int]] = None,
  146. include_stop_str_in_output: bool = False,
  147. ignore_eos: bool = False,
  148. max_tokens: Optional[int] = 16,
  149. logprobs: Optional[int] = None,
  150. prompt_logprobs: Optional[int] = None,
  151. custom_token_bans: Optional[List[int]] = None,
  152. skip_special_tokens: bool = True,
  153. spaces_between_special_tokens: bool = True,
  154. logits_processors: Optional[List[LogitsProcessorFunc]] = None,
  155. ) -> None:
  156. self.n = n
  157. self.best_of = best_of if best_of is not None else n
  158. self.presence_penalty = presence_penalty
  159. self.frequency_penalty = frequency_penalty
  160. self.repetition_penalty = repetition_penalty
  161. self.temperature = temperature
  162. self.top_p = top_p
  163. self.top_k = top_k
  164. self.top_a = top_a
  165. self.min_p = min_p
  166. self.tfs = tfs
  167. self.eta_cutoff = eta_cutoff
  168. self.epsilon_cutoff = epsilon_cutoff
  169. self.typical_p = typical_p
  170. self.typical_p_sigma = typical_p_sigma
  171. self.mirostat_mode = mirostat_mode
  172. self.mirostat_tau = mirostat_tau
  173. self.mirostat_eta = mirostat_eta
  174. self.dynatemp_min = dynatemp_min
  175. self.dynatemp_max = dynatemp_max
  176. self.dynatemp_exponent = dynatemp_exponent
  177. self.smoothing_factor = smoothing_factor
  178. self.smoothing_curve = smoothing_curve
  179. self.seed = seed
  180. self.use_beam_search = use_beam_search
  181. self.length_penalty = length_penalty
  182. self.early_stopping = early_stopping
  183. if stop is None:
  184. self.stop = []
  185. elif isinstance(stop, str):
  186. self.stop = [stop]
  187. else:
  188. self.stop = list(stop)
  189. self.stop_token_ids = stop_token_ids or []
  190. self.ignore_eos = ignore_eos
  191. self.max_tokens = max_tokens
  192. self.logprobs = logprobs
  193. self.prompt_logprobs = prompt_logprobs
  194. self.custom_token_bans = custom_token_bans or []
  195. self.skip_special_tokens = skip_special_tokens
  196. self.spaces_between_special_tokens = spaces_between_special_tokens
  197. self.logits_processors = logits_processors or []
  198. self.include_stop_str_in_output = include_stop_str_in_output
  199. self.default_values = {
  200. "n": 1,
  201. "best_of": 1,
  202. "presence_penalty": 0.0,
  203. "frequency_penalty": 0.0,
  204. "repetition_penalty": 1.0,
  205. "temperature": 1.0,
  206. "top_p": 1.0,
  207. "top_k": -1,
  208. "top_a": 0.0,
  209. "min_p": 0.0,
  210. "tfs": 1.0,
  211. "eta_cutoff": 0.0,
  212. "epsilon_cutoff": 0.0,
  213. "typical_p": 1.0,
  214. "typical_p_sigma": 0.0,
  215. "mirostat_mode": 0,
  216. "mirostat_tau": 0,
  217. "mirostat_eta": 0,
  218. "dynatemp_min": 0,
  219. "dynatemp_max": 0,
  220. "dynatemp_exponent": 1,
  221. "smoothing_factor": 0.0,
  222. "smoothing_curve": 1.0,
  223. "seed": None,
  224. "use_beam_search": False,
  225. "length_penalty": 1.0,
  226. "early_stopping": False,
  227. "stop": [],
  228. "stop_token_ids": [],
  229. "ignore_eos": False,
  230. "max_tokens": 16,
  231. "logprobs": None,
  232. "prompt_logprobs": None,
  233. "custom_token_bans": [],
  234. "skip_special_tokens": True,
  235. "spaces_between_special_tokens": True,
  236. "include_stop_str_in_output": False
  237. }
  238. self._verify_args()
  239. if self.use_beam_search:
  240. self._verify_beam_search()
  241. else:
  242. self._verify_non_beam_search()
  243. if self.temperature < _SAMPLING_EPS:
  244. # Zero temperature means greedy sampling.
  245. self.top_p = 1.0
  246. self.top_k = -1
  247. self.min_p = 0.0
  248. self.top_a = 0.0
  249. self._verify_greedy_sampling()
  250. def _verify_args(self) -> None:
  251. if self.n < 1:
  252. raise ValueError(f"n must be at least 1, got {self.n}.")
  253. if self.best_of < self.n:
  254. raise ValueError(f"best_of must be greater than or equal to n, "
  255. f"got n={self.n} and best_of={self.best_of}.")
  256. if not -2.0 <= self.presence_penalty <= 2.0:
  257. raise ValueError("presence_penalty must be in [-2, 2], got "
  258. f"{self.presence_penalty}.")
  259. if not -2.0 <= self.frequency_penalty <= 2.0:
  260. raise ValueError("frequency_penalty must be in [-2, 2], got "
  261. f"{self.frequency_penalty}.")
  262. if self.repetition_penalty < 1.0:
  263. raise ValueError("repetition_penalty must be in [1, inf), got "
  264. f"{self.repetition_penalty}.")
  265. if self.temperature < 0.0:
  266. raise ValueError(
  267. f"temperature must be non-negative, got {self.temperature}.")
  268. if not 0.0 < self.top_p <= 1.0:
  269. raise ValueError(f"top_p must be in (0, 1], got {self.top_p}.")
  270. if self.top_k < -1 or self.top_k == 0:
  271. raise ValueError(f"top_k must be -1 (disable), or at least 1, "
  272. f"got {self.top_k}.")
  273. if self.top_a < 0:
  274. raise ValueError(f"top_a must be non negative, got {self.top_a}.")
  275. if not 0.0 <= self.min_p <= 1.0:
  276. raise ValueError(f"min_p must be in [0, 1], got {self.min_p}.")
  277. if not 0.0 < self.tfs <= 1.0:
  278. raise ValueError(f"tfs must be in (0, 1], got {self.tfs}.")
  279. if self.epsilon_cutoff < 0.0 or self.epsilon_cutoff > 1000.0:
  280. raise ValueError("epsilon_cutoff must be in [0, 1000], got "
  281. f"{self.epsilon_cutoff}.")
  282. # pylint: disable=unneeded-not
  283. if not self.eta_cutoff >= 0:
  284. raise ValueError(
  285. f"eta_cutoff must be non negative, got {self.eta_cutoff}.")
  286. if not 0.0 <= self.typical_p <= 1.0:
  287. raise ValueError(
  288. f"typical_p must be in (0, 1], got {self.typical_p}.")
  289. if not self.typical_p_sigma >= 0:
  290. raise ValueError(f"typical_p_sigma must be non negative, got "
  291. f"{self.typical_p_sigma}.")
  292. if not self.dynatemp_min >= 0:
  293. raise ValueError(
  294. f"dynatemp_min must be non negative, got {self.dynatemp_min}.")
  295. if not self.dynatemp_max >= 0:
  296. raise ValueError(
  297. f"dynatemp_max must be non negative, got {self.dynatemp_max}.")
  298. if not self.dynatemp_exponent >= 0:
  299. raise ValueError(f"dynatemp_exponent must be non negative, got "
  300. f"{self.dynatemp_exponent}.")
  301. if not self.smoothing_factor >= 0:
  302. raise ValueError(f"smoothing_factor must be non negative, got "
  303. f"{self.smoothing_factor}.")
  304. if not self.smoothing_curve >= 1.0:
  305. raise ValueError(f"smoothing_curve must larger than 1, got "
  306. f"{self.smoothing_curve}.")
  307. if self.mirostat_mode:
  308. if not self.mirostat_mode == 2:
  309. raise ValueError(
  310. "Only Mirostat v2 (2) and disabled (0) supported, "
  311. f"got {self.mirostat_mode}")
  312. if not self.mirostat_eta >= 0:
  313. raise ValueError(
  314. f"mirostat_eta must be positive, got {self.mirostat_eta}")
  315. if not self.mirostat_tau >= 0:
  316. raise ValueError(
  317. f"mirostat_tau must be positive, got {self.mirostat_tau}")
  318. if self.max_tokens is not None and self.max_tokens < 1:
  319. raise ValueError(
  320. f"max_tokens must be at least 1, got {self.max_tokens}.")
  321. if self.logprobs is not None and self.logprobs < 0:
  322. raise ValueError(
  323. f"logprobs must be non-negative, got {self.logprobs}.")
  324. if self.prompt_logprobs is not None and self.prompt_logprobs < 0:
  325. raise ValueError("prompt_logprobs must be non-negative, got "
  326. f"{self.prompt_logprobs}.")
  327. def _verify_beam_search(self) -> None:
  328. if self.best_of == 1:
  329. raise ValueError("best_of must be greater than 1 when using beam "
  330. f"search. Got {self.best_of}.")
  331. if self.temperature > _SAMPLING_EPS:
  332. raise ValueError("temperature must be 0 when using beam search.")
  333. if self.top_p < 1.0 - _SAMPLING_EPS:
  334. raise ValueError("top_p must be 1 when using beam search.")
  335. if self.top_k != -1:
  336. raise ValueError("top_k must be -1 when using beam search.")
  337. if self.early_stopping not in [True, False, "never"]:
  338. raise ValueError(
  339. f"early_stopping must be True, False, or 'never', "
  340. f"got {self.early_stopping}.")
  341. def _verify_non_beam_search(self) -> None:
  342. if self.early_stopping is not False:
  343. raise ValueError("early_stopping is not effective and must be "
  344. "False when not using beam search.")
  345. if (self.length_penalty < 1.0 - _SAMPLING_EPS
  346. or self.length_penalty > 1.0 + _SAMPLING_EPS):
  347. raise ValueError(
  348. "length_penalty is not effective and must be the "
  349. "default value of 1.0 when not using beam search.")
  350. def _verify_greedy_sampling(self) -> None:
  351. if self.best_of > 1:
  352. raise ValueError("best_of must be 1 when using greedy sampling."
  353. f"Got {self.best_of}.")
  354. if self.top_p < 1.0 - _SAMPLING_EPS:
  355. raise ValueError("top_p must be 1 when using greedy sampling.")
  356. if self.top_k != -1:
  357. raise ValueError("top_k must be -1 when using greedy sampling.")
  358. @cached_property
  359. def sampling_type(self) -> SamplingType:
  360. if self.use_beam_search:
  361. return SamplingType.BEAM
  362. if self.temperature < _SAMPLING_EPS:
  363. return SamplingType.GREEDY
  364. if self.seed is not None:
  365. return SamplingType.RANDOM_SEED
  366. return SamplingType.RANDOM
  367. def __repr__(self) -> str:
  368. repr_str = "SamplingParams("
  369. for param, default_value in self.default_values.items():
  370. current_value = getattr(self, param)
  371. if current_value != default_value:
  372. repr_str += f"{param}={current_value}, "
  373. repr_str = repr_str.rstrip(', ') + ")"
  374. return repr_str