sampling_params.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. from pydantic import conint
  8. _SAMPLING_EPS = 1e-5
  9. class SamplingType(IntEnum):
  10. GREEDY = 0
  11. RANDOM = 1
  12. RANDOM_SEED = 2
  13. BEAM = 3
  14. LogitsProcessorFunc = Callable[[torch.Tensor, List[List[int]]], None]
  15. """LogitsProcessorFunc takes a logits tensor and corresponding lists of
  16. previously generated output tokens, and modifies the logits tensor."""
  17. class SamplingParams:
  18. """Sampling parameters for text generation.
  19. Overall, we follow the sampling parameters from the OpenAI text completion
  20. API (https://platform.openai.com/docs/api-reference/completions/create).
  21. In addition, we support multiple additional samplers which are not supported
  22. by OpenAI.
  23. Args:
  24. n: Number of output sequences to return for the given prompt.
  25. best_of: Number of output sequences that are generated from the prompt.
  26. From these `best_of` sequences, the top `n` sequences are returned.
  27. `best_of` must be greater than or equal to `n`. This is treated as
  28. the beam width when `use_beam_search` is True. By default, `best_of`
  29. is set to `n`.
  30. presence_penalty: Float that penalizes new tokens based on whether they
  31. appear in the generated text so far. Values > 0 encourage the model
  32. to use new tokens, while values < 0 encourage the model to repeat
  33. tokens.
  34. frequency_penalty: Float that penalizes new tokens based on their
  35. frequency in the generated text so far. Values > 0 encourage the
  36. model to use new tokens, while values < 0 encourage the model to
  37. repeat tokens.
  38. repetition_penalty: Float that penalizes new tokens based on their
  39. frequency in the generated text so far.
  40. freq_pen is applied additively while
  41. rep_pen is applied multiplicatively.
  42. Must be in [1, inf). Set to 1 to disable the effect.
  43. temperature: Float that controls the randomness of the sampling. Lower
  44. values make the model more deterministic, while higher values make
  45. the model more random. Zero means greedy sampling.
  46. top_p: Float that controls the cumulative probability of the top tokens
  47. to consider. Must be in (0, 1]. Set to 1 to consider all tokens.
  48. top_k: Integer that controls the number of top tokens to consider. Set
  49. to -1 to consider all tokens.
  50. top_a: Float that controls the cutoff for Top-A sampling.
  51. Exact cutoff is top_a*max_prob**2. Must be in [0,inf], 0 to disable.
  52. min_p: Float that controls the cutoff for min-p sampling.
  53. Exact cutoff is min_p*max_prob. Must be in [0,1], 0 to disable.
  54. tfs: Float that controls the cumulative approximate curvature of the
  55. distribution to retain for Tail Free Sampling.
  56. Must be in (0, 1]. Set to 1 to disable
  57. eta_cutoff: Float that controls the cutoff threshold for Eta sampling
  58. (a form of entropy adaptive truncation sampling)
  59. threshold is computed as min(eta, sqrt(eta)*entropy(probs)).
  60. Specified in units of 1e-4. Set to 0 to disable
  61. epsilon_cutoff: Float that controls the cutoff threshold for
  62. Epsilon sampling (simple probability threshold truncation).
  63. Specified in units of 1e-4. Set to 0 to disable.
  64. typical_p: Float that controls the cumulative probability of tokens
  65. closest in surprise to the expected surprise to consider.
  66. Must be in (0, 1]. Set to 1 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. min_tokens: Minimum number of tokens to generate per output sequence
  101. before EOS or stop tokens are generated.
  102. logprobs: Number of log probabilities to return per output token.
  103. Note that the implementation follows the OpenAI API: The return
  104. result includes the log probabilities on the `logprobs` most likely
  105. tokens, as well the chosen tokens. The API will always return the
  106. log probability of the sampled token, so there may be up to
  107. `logprobs+1` elements in the response.
  108. prompt_logprobs: Number of log probabilities to return per prompt token.
  109. detokenize: Whether to detokenize the output. Defaults to True.
  110. custom_token_bans: List of token IDs to ban from generating
  111. skip_special_tokens: Whether to skip special tokens in the output.
  112. defaults to true.
  113. spaces_between_special_tokens: Whether to add spaces between special
  114. tokens in the output. Defaults to True.
  115. logits_processors: List of LogitsProcessors to change the probability
  116. of token prediction at runtime.
  117. truncate_prompt_tokens: If set to an integer k, will use only the last
  118. k tokens from the prompt (i.e. left-truncation). Defaults to None
  119. (i.e. no truncation).
  120. """
  121. def __init__(
  122. self,
  123. n: int = 1,
  124. best_of: Optional[int] = None,
  125. presence_penalty: float = 0.0,
  126. frequency_penalty: float = 0.0,
  127. repetition_penalty: float = 1.0,
  128. temperature: float = 1.0,
  129. top_p: float = 1.0,
  130. top_k: int = -1,
  131. top_a: float = 0.0,
  132. min_p: float = 0.0,
  133. tfs: float = 1.0,
  134. eta_cutoff: float = 0.0,
  135. epsilon_cutoff: float = 0.0,
  136. typical_p: float = 1.0,
  137. mirostat_mode: int = 0,
  138. mirostat_tau: float = 0,
  139. mirostat_eta: float = 0,
  140. dynatemp_min: float = 0,
  141. dynatemp_max: float = 0,
  142. dynatemp_exponent: float = 1,
  143. smoothing_factor: float = 0.0,
  144. smoothing_curve: float = 1.0,
  145. seed: Optional[int] = None,
  146. use_beam_search: bool = False,
  147. length_penalty: float = 1.0,
  148. early_stopping: Union[bool, str] = False,
  149. stop: Union[None, str, List[str]] = None,
  150. stop_token_ids: Optional[List[int]] = None,
  151. include_stop_str_in_output: bool = False,
  152. ignore_eos: bool = False,
  153. max_tokens: Optional[int] = 16,
  154. min_tokens: int = 0,
  155. logprobs: Optional[int] = None,
  156. prompt_logprobs: Optional[int] = None,
  157. detokenize: bool = True,
  158. custom_token_bans: Optional[List[int]] = None,
  159. skip_special_tokens: bool = True,
  160. spaces_between_special_tokens: bool = True,
  161. logits_processors: Optional[List[LogitsProcessorFunc]] = None,
  162. truncate_prompt_tokens: Optional[conint(ge=1)] = None,
  163. ) -> None:
  164. self.n = n
  165. self.best_of = best_of if best_of is not None else n
  166. self.presence_penalty = presence_penalty
  167. self.frequency_penalty = frequency_penalty
  168. self.repetition_penalty = repetition_penalty
  169. self.temperature = temperature
  170. self.top_p = top_p
  171. self.top_k = top_k
  172. self.top_a = top_a
  173. self.min_p = min_p
  174. self.tfs = tfs
  175. self.eta_cutoff = eta_cutoff
  176. self.epsilon_cutoff = epsilon_cutoff
  177. self.typical_p = typical_p
  178. self.mirostat_mode = mirostat_mode
  179. self.mirostat_tau = mirostat_tau
  180. self.mirostat_eta = mirostat_eta
  181. self.dynatemp_min = dynatemp_min
  182. self.dynatemp_max = dynatemp_max
  183. self.dynatemp_exponent = dynatemp_exponent
  184. self.smoothing_factor = smoothing_factor
  185. self.smoothing_curve = smoothing_curve
  186. self.seed = seed
  187. self.use_beam_search = use_beam_search
  188. self.length_penalty = length_penalty
  189. self.early_stopping = early_stopping
  190. if stop is None:
  191. self.stop = []
  192. elif isinstance(stop, str):
  193. self.stop = [stop]
  194. else:
  195. self.stop = list(stop)
  196. self.stop_token_ids = stop_token_ids or []
  197. self.ignore_eos = ignore_eos
  198. self.max_tokens = max_tokens
  199. self.min_tokens = min_tokens
  200. self.logprobs = logprobs
  201. self.prompt_logprobs = prompt_logprobs
  202. # NOTE: This parameter is only exposed at the engine level for now.
  203. # It is not exposed in the OpenAI API server, as the OpenAI API does
  204. # not support returning only a list of token IDs.
  205. self.detokenize = detokenize
  206. self.custom_token_bans = custom_token_bans or []
  207. self.skip_special_tokens = skip_special_tokens
  208. self.spaces_between_special_tokens = spaces_between_special_tokens
  209. self.logits_processors = logits_processors or []
  210. self.include_stop_str_in_output = include_stop_str_in_output
  211. self.truncate_prompt_tokens = truncate_prompt_tokens
  212. self.default_values = {
  213. "n": 1,
  214. "best_of": 1,
  215. "presence_penalty": 0.0,
  216. "frequency_penalty": 0.0,
  217. "repetition_penalty": 1.0,
  218. "temperature": 1.0,
  219. "top_p": 1.0,
  220. "top_k": -1,
  221. "top_a": 0.0,
  222. "min_p": 0.0,
  223. "tfs": 1.0,
  224. "eta_cutoff": 0.0,
  225. "epsilon_cutoff": 0.0,
  226. "typical_p": 1.0,
  227. "mirostat_mode": 0,
  228. "mirostat_tau": 0,
  229. "mirostat_eta": 0,
  230. "dynatemp_min": 0,
  231. "dynatemp_max": 0,
  232. "dynatemp_exponent": 1,
  233. "smoothing_factor": 0.0,
  234. "smoothing_curve": 1.0,
  235. "seed": None,
  236. "use_beam_search": False,
  237. "length_penalty": 1.0,
  238. "early_stopping": False,
  239. "stop": [],
  240. "stop_token_ids": [],
  241. "ignore_eos": False,
  242. "max_tokens": 16,
  243. "min_tokens": 0,
  244. "logprobs": None,
  245. "prompt_logprobs": None,
  246. "detokenize": True,
  247. "custom_token_bans": [],
  248. "skip_special_tokens": True,
  249. "spaces_between_special_tokens": True,
  250. "include_stop_str_in_output": False,
  251. "truncate_prompt_tokens": None,
  252. }
  253. # Number of characters to hold back for stop string evaluation
  254. # until sequence is finished.
  255. if self.stop and not include_stop_str_in_output:
  256. self.output_text_buffer_length = max(len(s) for s in self.stop) - 1
  257. else:
  258. self.output_text_buffer_length = 0
  259. self._verify_args()
  260. if self.use_beam_search:
  261. self._verify_beam_search()
  262. else:
  263. self._verify_non_beam_search()
  264. if self.temperature < _SAMPLING_EPS:
  265. # Zero temperature means greedy sampling.
  266. self.top_p = 1.0
  267. self.top_k = -1
  268. self.min_p = 0.0
  269. self.top_a = 0.0
  270. self._verify_greedy_sampling()
  271. # injected by the engine
  272. self.eos_token_id = None
  273. def _verify_args(self) -> None:
  274. if self.n < 1:
  275. raise ValueError(f"n must be at least 1, got {self.n}.")
  276. if self.best_of < self.n:
  277. raise ValueError(f"best_of must be greater than or equal to n, "
  278. f"got n={self.n} and best_of={self.best_of}.")
  279. if not -2.0 <= self.presence_penalty <= 2.0:
  280. raise ValueError("presence_penalty must be in [-2, 2], got "
  281. f"{self.presence_penalty}.")
  282. if not -2.0 <= self.frequency_penalty <= 2.0:
  283. raise ValueError("frequency_penalty must be in [-2, 2], got "
  284. f"{self.frequency_penalty}.")
  285. if self.repetition_penalty < 1.0:
  286. raise ValueError("repetition_penalty must be in [1, inf), got "
  287. f"{self.repetition_penalty}.")
  288. if self.temperature < 0.0:
  289. raise ValueError(
  290. f"temperature must be non-negative, got {self.temperature}.")
  291. if not 0.0 < self.top_p <= 1.0:
  292. raise ValueError(f"top_p must be in (0, 1], got {self.top_p}.")
  293. if self.top_k < -1 or self.top_k == 0:
  294. raise ValueError(f"top_k must be -1 (disable), or at least 1, "
  295. f"got {self.top_k}.")
  296. if self.top_a < 0:
  297. raise ValueError(f"top_a must be non negative, got {self.top_a}.")
  298. if not 0.0 <= self.min_p <= 1.0:
  299. raise ValueError(f"min_p must be in [0, 1], got {self.min_p}.")
  300. if not 0.0 < self.tfs <= 1.0:
  301. raise ValueError(f"tfs must be in (0, 1], got {self.tfs}.")
  302. if self.epsilon_cutoff < 0.0 or self.epsilon_cutoff > 1000.0:
  303. raise ValueError("epsilon_cutoff must be in [0, 1000], got "
  304. f"{self.epsilon_cutoff}.")
  305. # pylint: disable=unneeded-not
  306. if not self.eta_cutoff >= 0:
  307. raise ValueError(
  308. f"eta_cutoff must be non negative, got {self.eta_cutoff}.")
  309. if not 0.0 <= self.typical_p <= 1.0:
  310. raise ValueError(
  311. f"typical_p must be in (0, 1], got {self.typical_p}.")
  312. if not self.dynatemp_min >= 0:
  313. raise ValueError(
  314. f"dynatemp_min must be non negative, got {self.dynatemp_min}.")
  315. if not self.dynatemp_max >= 0:
  316. raise ValueError(
  317. f"dynatemp_max must be non negative, got {self.dynatemp_max}.")
  318. if not self.dynatemp_exponent >= 0:
  319. raise ValueError(f"dynatemp_exponent must be non negative, got "
  320. f"{self.dynatemp_exponent}.")
  321. if not self.smoothing_factor >= 0:
  322. raise ValueError(f"smoothing_factor must be non negative, got "
  323. f"{self.smoothing_factor}.")
  324. if not self.smoothing_curve >= 1.0:
  325. raise ValueError(f"smoothing_curve must larger than 1, got "
  326. f"{self.smoothing_curve}.")
  327. if self.mirostat_mode:
  328. if not self.mirostat_mode == 2:
  329. raise ValueError(
  330. "Only Mirostat v2 (2) and disabled (0) supported, "
  331. f"got {self.mirostat_mode}")
  332. if not self.mirostat_eta >= 0:
  333. raise ValueError(
  334. f"mirostat_eta must be positive, got {self.mirostat_eta}")
  335. if not self.mirostat_tau >= 0:
  336. raise ValueError(
  337. f"mirostat_tau must be positive, got {self.mirostat_tau}")
  338. if self.max_tokens is not None and self.max_tokens < 1:
  339. raise ValueError(
  340. f"max_tokens must be at least 1, got {self.max_tokens}.")
  341. if self.min_tokens < 0:
  342. raise ValueError(f"min_tokens must be greater than or equal to 0, "
  343. f"got {self.min_tokens}.")
  344. if self.max_tokens is not None and self.min_tokens > self.max_tokens:
  345. raise ValueError(
  346. f"min_tokens must be less than or equal to "
  347. f"max_tokens={self.max_tokens}, got {self.min_tokens}.")
  348. if self.logprobs is not None and self.logprobs < 0:
  349. raise ValueError(
  350. f"logprobs must be non-negative, got {self.logprobs}.")
  351. if self.prompt_logprobs is not None and self.prompt_logprobs < 0:
  352. raise ValueError("prompt_logprobs must be non-negative, got "
  353. f"{self.prompt_logprobs}.")
  354. if (self.truncate_prompt_tokens is not None
  355. and self.truncate_prompt_tokens < 1):
  356. raise ValueError(f"truncate_prompt_tokens must be >= 1, "
  357. f"got {self.truncate_prompt_tokens}")
  358. if any(not stop_str for stop_str in self.stop):
  359. raise ValueError("stop cannot contain an empty string.")
  360. if self.stop and not self.detokenize:
  361. raise ValueError(
  362. "stop strings are only supported when detokenize is True. "
  363. "Set detokenize=True to use stop.")
  364. def _verify_beam_search(self) -> None:
  365. if self.best_of == 1:
  366. raise ValueError("best_of must be greater than 1 when using beam "
  367. f"search. Got {self.best_of}.")
  368. if self.temperature > _SAMPLING_EPS:
  369. raise ValueError("temperature must be 0 when using beam search.")
  370. if self.top_p < 1.0 - _SAMPLING_EPS:
  371. raise ValueError("top_p must be 1 when using beam search.")
  372. if self.top_k != -1:
  373. raise ValueError("top_k must be -1 when using beam search.")
  374. if self.early_stopping not in [True, False, "never"]:
  375. raise ValueError(
  376. f"early_stopping must be True, False, or 'never', "
  377. f"got {self.early_stopping}.")
  378. def _verify_non_beam_search(self) -> None:
  379. if self.early_stopping is not False:
  380. raise ValueError("early_stopping is not effective and must be "
  381. "False when not using beam search.")
  382. if (self.length_penalty < 1.0 - _SAMPLING_EPS
  383. or self.length_penalty > 1.0 + _SAMPLING_EPS):
  384. raise ValueError(
  385. "length_penalty is not effective and must be the "
  386. "default value of 1.0 when not using beam search.")
  387. def _verify_greedy_sampling(self) -> None:
  388. if self.best_of > 1:
  389. raise ValueError("best_of must be 1 when using greedy sampling."
  390. f"Got {self.best_of}.")
  391. if self.top_p < 1.0 - _SAMPLING_EPS:
  392. raise ValueError("top_p must be 1 when using greedy sampling.")
  393. if self.top_k != -1:
  394. raise ValueError("top_k must be -1 when using greedy sampling.")
  395. @cached_property
  396. def sampling_type(self) -> SamplingType:
  397. if self.use_beam_search:
  398. return SamplingType.BEAM
  399. if self.temperature < _SAMPLING_EPS:
  400. return SamplingType.GREEDY
  401. if self.seed is not None:
  402. return SamplingType.RANDOM_SEED
  403. return SamplingType.RANDOM
  404. def clone(self) -> "SamplingParams":
  405. """Deep copy excluding LogitsProcessor objects.
  406. LogitsProcessor objects are excluded because they may contain an
  407. arbitrary, nontrivial amount of data.
  408. """
  409. logit_processor_refs = None if self.logits_processors is None else {
  410. id(lp): lp
  411. for lp in self.logits_processors
  412. }
  413. return copy.deepcopy(self, memo=logit_processor_refs)
  414. def __repr__(self) -> str:
  415. repr_str = "SamplingParams("
  416. for param, default_value in self.default_values.items():
  417. current_value = getattr(self, param)
  418. if current_value != default_value:
  419. repr_str += f"{param}={current_value}, "
  420. repr_str = repr_str.rstrip(', ') + ")"
  421. return repr_str