sampling_params.py 18 KB

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