sampling_params.py 17 KB

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