sampling_params.py 18 KB

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