sampling_params.py 21 KB

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