sampling_params.py 23 KB

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