sampling_params.py 21 KB

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