1
0

sampling_params.py 21 KB

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