sampling_params.py 23 KB

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