sampling_params.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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, Set, Union
  6. import msgspec
  7. import torch
  8. from loguru import logger
  9. from typing_extensions import Annotated
  10. import aphrodite.common.envs as envs
  11. from aphrodite.common.config import SchedulerConfig
  12. _SAMPLING_EPS = 1e-5
  13. _MAX_TEMP = 1e-2
  14. APHRODITE_NO_DEPRECATION_WARNING = envs.APHRODITE_NO_DEPRECATION_WARNING
  15. class SamplingType(IntEnum):
  16. GREEDY = 0
  17. RANDOM = 1
  18. RANDOM_SEED = 2
  19. BEAM = 3
  20. class SamplerID(IntEnum):
  21. # Mirror these in aphrodite/modeling/layers/sampler.py
  22. # Values out of order to keep backwards compatibility
  23. # with Koboldcpp values
  24. DRY = 7
  25. PENALTIES = 6
  26. NO_REPEAT_NGRAM = 8
  27. TEMPERATURE = 5
  28. TOP_NSIGMA = 9
  29. TOP_P_TOP_K = 0
  30. TOP_A = 1
  31. MIN_P = 2
  32. TFS = 3
  33. ETA_CUTOFF = 10
  34. EPSILON_CUTOFF = 11
  35. TYPICAL_P = 4
  36. QUADRATIC = 12
  37. XTC = 13
  38. @classmethod
  39. def from_str(cls, value: Union[str, int]) -> "SamplerID":
  40. """Convert string or int to SamplerID enum.
  41. Args:
  42. value: String name (case-insensitive) or integer value
  43. Returns:
  44. SamplerID enum value
  45. Raises:
  46. ValueError: If value cannot be converted to SamplerID
  47. """
  48. if isinstance(value, int):
  49. return cls(value)
  50. try:
  51. return cls[value.upper()]
  52. except KeyError as e:
  53. valid_names = [x.name for x in cls]
  54. raise ValueError(
  55. f"Invalid sampler name '{value}'. Must be one of: {valid_names}"
  56. ) from e
  57. LogitsProcessorFunc = Union[Callable[[List[int], torch.Tensor], torch.Tensor],
  58. Callable[[List[int], List[int], torch.Tensor],
  59. torch.Tensor]]
  60. """LogitsProcessor is a function that takes a list
  61. of previously generated tokens, the logits tensor
  62. for the next token and, optionally, prompt tokens as a
  63. first argument, and returns a modified tensor of logits
  64. to sample from."""
  65. class SamplingParams(
  66. msgspec.Struct,
  67. omit_defaults=True,
  68. dict=True):
  69. """Sampling parameters for text generation.
  70. Overall, we follow the sampling parameters from the OpenAI text completion
  71. API (https://platform.openai.com/docs/api-reference/completions/create).
  72. In addition, we support multiple additional samplers which are not supported
  73. by OpenAI.
  74. Args:
  75. n: Number of output sequences to return for the given prompt.
  76. best_of: Number of output sequences that are generated from the prompt.
  77. From these `best_of` sequences, the top `n` sequences are returned.
  78. `best_of` must be greater than or equal to `n`. This is treated as
  79. the beam width when `use_beam_search` is True. By default, `best_of`
  80. is set to `n`.
  81. presence_penalty: Float that penalizes new tokens based on whether they
  82. appear in the generated text so far. Values > 0 encourage the model
  83. to use new tokens, while values < 0 encourage the model to repeat
  84. tokens.
  85. frequency_penalty: Float that penalizes new tokens based on their
  86. frequency in the generated text so far. Values > 0 encourage the
  87. model to use new tokens, while values < 0 encourage the model to
  88. repeat tokens.
  89. repetition_penalty: Float that penalizes new tokens based on their
  90. frequency in the generated text so far.
  91. freq_pen is applied additively while
  92. rep_pen is applied multiplicatively.
  93. Must be in [1, inf). Set to 1 to disable the effect.
  94. no_repeat_ngram_size: Size of the n-grams to prevent repeating.
  95. 1 would mean no token can appear twice.
  96. 2 would mean no pair of consecutive tokens can appear twice.
  97. temperature: Float that controls the randomness of the sampling. Lower
  98. values make the model more deterministic, while higher values make
  99. the model more random. Zero means greedy sampling.
  100. top_p: Float that controls the cumulative probability of the top tokens
  101. to consider. Must be in (0, 1]. Set to 1 to consider all tokens.
  102. top_k: Integer that controls the number of top tokens to consider. Set
  103. to -1 to consider all tokens.
  104. top_a: Float that controls the cutoff for Top-A sampling.
  105. Exact cutoff is top_a*max_prob**2. Must be in [0,inf], 0 to disable.
  106. min_p: Float that controls the cutoff for min-p sampling.
  107. Exact cutoff is min_p*max_prob. Must be in [0,1], 0 to disable.
  108. tfs: Float that controls the cumulative approximate curvature of the
  109. distribution to retain for Tail Free Sampling.
  110. Must be in (0, 1]. Set to 1 to disable
  111. eta_cutoff: Float that controls the cutoff threshold for Eta sampling
  112. (a form of entropy adaptive truncation sampling)
  113. threshold is computed as min(eta, sqrt(eta)*entropy(probs)).
  114. Specified in units of 1e-4. Set to 0 to disable
  115. epsilon_cutoff: Float that controls the cutoff threshold for
  116. Epsilon sampling (simple probability threshold truncation).
  117. Specified in units of 1e-4. Set to 0 to disable.
  118. typical_p: Float that controls the cumulative probability of tokens
  119. closest in surprise to the expected surprise to consider.
  120. Must be in (0, 1]. Set to 1 to disable.
  121. mirostat_mode: Can either be 0 (disabled) or 2 (Mirostat v2).
  122. mirostat_tau: Target "surprisal" that mirostat works towards.
  123. Range [0, inf).
  124. mirostat_eta: Rate at which mirostat updates its internal surprisal
  125. value. Range [0, inf).
  126. dynatemp_min: Minimum temperature for dynatemp sampling.
  127. Range [0, inf).
  128. dynatemp_max: Maximum temperature for dynatemp sampling.
  129. Range [0, inf).
  130. dynatemp_exponent: Exponent for dynatemp sampling. Range [0, inf).
  131. smoothing_factor: Smoothing factor for Quadratic Sampling.
  132. smoothing_curve: Smoothing curve for Quadratic (Cubic) Sampling.
  133. seed: Random seed to use for the generation.
  134. use_beam_search: Whether to use beam search instead of sampling.
  135. length_penalty: Float that penalizes sequences based on their length.
  136. Used in beam search.
  137. early_stopping: Controls the stopping condition for beam search. It
  138. accepts the following values: `True`, where the generation stops as
  139. soon as there are `best_of` complete candidates; `False`, where an
  140. heuristic is applied and the generation stops when is it very
  141. unlikely to find better candidates; `"never"`, where the beam search
  142. procedure only stops when there cannot be better candidates
  143. (canonical beam search algorithm).
  144. stop: List of strings that stop the generation when they are generated.
  145. The returned output will not contain the stop strings.
  146. stop_token_ids: List of tokens that stop the generation when they are
  147. generated. The returned output will contain the stop tokens unless
  148. the stop tokens are special tokens.
  149. include_stop_str_in_output: Whether to include the stop strings in
  150. output text. Defaults to False.
  151. ignore_eos: Whether to ignore the EOS token and continue generating
  152. tokens after the EOS token is generated.
  153. max_tokens: Maximum number of tokens to generate per output sequence.
  154. min_tokens: Minimum number of tokens to generate per output sequence
  155. before EOS or stop tokens are generated.
  156. logprobs: Number of log probabilities to return per output token.
  157. When set to None, no probability is returned. If set to a non-None
  158. value, the result includes the log probabilities of the specified
  159. number of most likely tokens, as well as the chosen tokens.
  160. Note that the implementation follows the OpenAI API: The API will
  161. always return the log probability of the sampled token, so there
  162. may be up to `logprobs+1` elements in the response.
  163. prompt_logprobs: Number of log probabilities to return per prompt token.
  164. detokenize: Whether to detokenize the output. Defaults to True.
  165. custom_token_bans: List of token IDs to ban from generating
  166. skip_special_tokens: Whether to skip special tokens in the output.
  167. defaults to true.
  168. spaces_between_special_tokens: Whether to add spaces between special
  169. tokens in the output. Defaults to True.
  170. logits_processors: List of functions that modify logits based on
  171. previously generated tokens, and optionally prompt tokens as
  172. a first argument.
  173. truncate_prompt_tokens: If set to an integer k, will use only the last
  174. k tokens from the prompt (i.e. left-truncation). Defaults to None
  175. (i.e. no truncation).
  176. xtc_threshold: In XTC sampling, if 2 or more tokens have probability
  177. above this threshold, consider removing all but the last one.
  178. xtc_probability: Probability that the removal will actually happen.
  179. 0 disables the sampler, 1 makes it always happen.
  180. nsigma: Number of standard deviations from the maximum logit to use
  181. as a cutoff threshold. Tokens with logits below
  182. (max_logit - nsgima * std_dev) are filtered out. Higher values
  183. (e.g. 3.0) keep more tokens, lower values (e.g. 1.0) are more
  184. selective. Must be positive. 0 to disable.
  185. dry_multiplier: Float that controls the magnitude of the DRY sampling
  186. penalty. Higher values create stronger penalties against
  187. repetition. The penalty is multiplied by this value before being
  188. applied. Must be non-negative. 0 disables the sampler.
  189. dry_base: Base for the exponential growth of the DRY sampling penalty.
  190. Controls how quickly the penalty increases with longer repeated
  191. sequences. Must be greater than 1. Higher values (e.g. 2.0) create
  192. more aggressive penalties for longer repetitions. Defaults to 1.75.
  193. dry_allowed_length: Maximum number of tokens that can be repeated
  194. without incurring a DRY sampling penalty. Sequences longer than
  195. this will be penalized exponentially. Must be at least 1.
  196. Defaults to 2.
  197. dry_sequence_breaker_ids: List of token IDs that stop
  198. the matching of repeated content. These tokens will break up the
  199. input into sections where repetition is evaluated separately.
  200. Common examples are newlines, quotes, and other structural tokens.
  201. Defaults to None.
  202. dry_range: The range of tokens (input + output) to apply the DRY
  203. sampler.
  204. skew: Bias the token selection towards higher or lower probability
  205. tokens. Defaults to 0 (disabled).
  206. sampler_priority: A list of integers to control the order in which
  207. samplers are applied.
  208. """
  209. n: int = 1
  210. best_of: Optional[int] = None
  211. presence_penalty: float = 0.0
  212. frequency_penalty: float = 0.0
  213. repetition_penalty: float = 1.0
  214. no_repeat_ngram_size: int = 0
  215. temperature: float = 1.0
  216. dynatemp_min: float = 0.0
  217. dynatemp_max: float = 0.0
  218. dynatemp_exponent: float = 1.0
  219. temperature_last: bool = False
  220. top_p: float = 1.0
  221. top_k: int = -1
  222. top_a: float = 0.0
  223. min_p: float = 0.0
  224. tfs: float = 1.0
  225. eta_cutoff: float = 0.0
  226. epsilon_cutoff: float = 0.0
  227. typical_p: float = 1.0
  228. smoothing_factor: float = 0.0
  229. smoothing_curve: float = 1.0
  230. seed: Optional[int] = None
  231. use_beam_search: bool = False
  232. length_penalty: float = 1.0
  233. early_stopping: Union[bool, str] = False
  234. stop: Union[None, str, List[str]] = None
  235. stop_token_ids: Optional[List[int]] = None
  236. include_stop_str_in_output: bool = False
  237. ignore_eos: bool = False
  238. max_tokens: Optional[int] = 16
  239. min_tokens: int = 0
  240. logprobs: Optional[int] = None
  241. prompt_logprobs: Optional[int] = None
  242. detokenize: bool = True
  243. custom_token_bans: Optional[List[int]] = None
  244. skip_special_tokens: bool = True
  245. spaces_between_special_tokens: bool = True
  246. # Optional[List[LogitsProcessorFunc]] type.
  247. # We use Any here because the type above
  248. # is not supported by msgspec.
  249. logits_processors: Optional[Any] = None
  250. truncate_prompt_tokens: Optional[Annotated[int, msgspec.Meta(ge=1)]] = None
  251. xtc_threshold: float = 0.1
  252. xtc_probability: float = 0
  253. nsigma: float = 0.0
  254. dry_multiplier: float = 0.0
  255. dry_base: float = 1.75
  256. dry_allowed_length: int = 2
  257. dry_sequence_breaker_ids: List[int] = []
  258. dry_range: int = 0
  259. skew: float = 0.0
  260. sampler_priority: Optional[List[int]] = []
  261. # The below fields are not supposed to be used as an input.
  262. # They are set in post_init.
  263. output_text_buffer_length: int = 0
  264. _all_stop_token_ids: Set[int] = msgspec.field(default_factory=set)
  265. default_values = {
  266. "n": 1,
  267. "best_of": 1,
  268. "presence_penalty": 0.0,
  269. "frequency_penalty": 0.0,
  270. "repetition_penalty": 1.0,
  271. "no_repeat_ngram_size": 0,
  272. "temperature": 1.0,
  273. "dynatemp_min": 0.0,
  274. "dynatemp_max": 0.0,
  275. "dynatemp_exponent": 1.0,
  276. "temperature_last": False,
  277. "top_p": 1.0,
  278. "top_k": -1,
  279. "top_a": 0.0,
  280. "min_p": 0.0,
  281. "tfs": 1.0,
  282. "eta_cutoff": 0.0,
  283. "epsilon_cutoff": 0.0,
  284. "typical_p": 1.0,
  285. "smoothing_factor": 0.0,
  286. "smoothing_curve": 1.0,
  287. "seed": None,
  288. "use_beam_search": False,
  289. "length_penalty": 1.0,
  290. "early_stopping": False,
  291. "stop": [],
  292. "stop_token_ids": [],
  293. "ignore_eos": False,
  294. "max_tokens": 16,
  295. "min_tokens": 0,
  296. "logprobs": None,
  297. "prompt_logprobs": None,
  298. "detokenize": True,
  299. "custom_token_bans": None,
  300. "skip_special_tokens": True,
  301. "spaces_between_special_tokens": True,
  302. "include_stop_str_in_output": False,
  303. "truncate_prompt_tokens": None,
  304. "xtc_threshold": 0.1,
  305. "xtc_probability": 0,
  306. "nsigma": 0.0,
  307. "dry_multiplier": 0.0,
  308. "dry_base": 1.75,
  309. "dry_allowed_length": 2,
  310. "dry_sequence_breaker_ids": [],
  311. "dry_range": 0,
  312. "skew": 0.0,
  313. "sampler_priority": [],
  314. }
  315. def __post_init__(self) -> None:
  316. self.best_of = self.best_of or self.n
  317. if 0 < self.temperature < _MAX_TEMP:
  318. logger.warning(
  319. f"temperature {self.temperature} is less than {_MAX_TEMP}, "
  320. "which may cause numerical errors NaN or inf in tensors. We "
  321. f"have maxed it out to {_MAX_TEMP}.")
  322. self.temperature = max(self.temperature, _MAX_TEMP)
  323. if self.seed == -1:
  324. self.seed = None
  325. else:
  326. self.seed = self.seed
  327. if self.stop is None:
  328. self.stop = []
  329. elif isinstance(self.stop, str):
  330. self.stop = [self.stop]
  331. else:
  332. self.stop = list(self.stop)
  333. if self.stop_token_ids is None:
  334. self.stop_token_ids = []
  335. else:
  336. self.stop_token_ids = list(self.stop_token_ids)
  337. self.logprobs = 1 if self.logprobs is True else self.logprobs
  338. self.prompt_logprobs = (1 if self.prompt_logprobs is True else
  339. self.prompt_logprobs)
  340. # Number of characters to hold back for stop string evaluation
  341. # until sequence is finished.
  342. if self.stop and not self.include_stop_str_in_output:
  343. self.output_text_buffer_length = max(len(s) for s in self.stop) - 1
  344. self._verify_args()
  345. if self.use_beam_search:
  346. if not APHRODITE_NO_DEPRECATION_WARNING:
  347. logger.warning(
  348. "[IMPORTANT] We plan to discontinue the support for beam "
  349. "search in the next major release. Set "
  350. "APHRODITE_NO_DEPRECATION_WARNING=1 to "
  351. "suppress this warning.")
  352. self._verify_beam_search()
  353. else:
  354. self._verify_non_beam_search()
  355. if self.temperature < _SAMPLING_EPS:
  356. # Zero temperature means greedy sampling.
  357. self.top_p = 1.0
  358. self.top_k = -1
  359. self.min_p = 0.0
  360. self.top_a = 0.0
  361. self._verify_greedy_sampling()
  362. # eos_token_id is added to this by the engine
  363. self._all_stop_token_ids = set(self.stop_token_ids)
  364. def _verify_args(self) -> None:
  365. if self.n < 1:
  366. raise ValueError(f"n must be at least 1, got {self.n}.")
  367. assert isinstance(self.best_of, int)
  368. if self.best_of < self.n:
  369. raise ValueError(f"best_of must be greater than or equal to n, "
  370. f"got n={self.n} and best_of={self.best_of}.")
  371. if not -2.0 <= self.presence_penalty <= 2.0:
  372. raise ValueError("presence_penalty must be in [-2, 2], got "
  373. f"{self.presence_penalty}.")
  374. if not -2.0 <= self.frequency_penalty <= 2.0:
  375. raise ValueError("frequency_penalty must be in [-2, 2], got "
  376. f"{self.frequency_penalty}.")
  377. if self.repetition_penalty < 1.0:
  378. raise ValueError("repetition_penalty must be in [1, inf), got "
  379. f"{self.repetition_penalty}.")
  380. if self.temperature < 0.0:
  381. raise ValueError(
  382. f"temperature must be non-negative, got {self.temperature}.")
  383. if not 0.0 < self.top_p <= 1.0:
  384. raise ValueError(f"top_p must be in (0, 1], got {self.top_p}.")
  385. if self.top_k < -1 or self.top_k == 0:
  386. raise ValueError(f"top_k must be -1 (disable), or at least 1, "
  387. f"got {self.top_k}.")
  388. if self.top_a < 0:
  389. raise ValueError(f"top_a must be non negative, got {self.top_a}.")
  390. if not 0.0 <= self.min_p <= 1.0:
  391. raise ValueError(f"min_p must be in [0, 1], got {self.min_p}.")
  392. if not 0.0 < self.tfs <= 1.0:
  393. raise ValueError(f"tfs must be in (0, 1], got {self.tfs}.")
  394. if self.epsilon_cutoff < 0.0 or self.epsilon_cutoff > 1000.0:
  395. raise ValueError("epsilon_cutoff must be in [0, 1000], got "
  396. f"{self.epsilon_cutoff}.")
  397. # pylint: disable=unneeded-not
  398. if not self.eta_cutoff >= 0:
  399. raise ValueError(
  400. f"eta_cutoff must be non negative, got {self.eta_cutoff}.")
  401. if not 0.0 <= self.typical_p <= 1.0:
  402. raise ValueError(
  403. f"typical_p must be in (0, 1], got {self.typical_p}.")
  404. if self.max_tokens is not None and self.max_tokens < 1:
  405. raise ValueError(
  406. f"max_tokens must be at least 1, got {self.max_tokens}.")
  407. if self.min_tokens < 0:
  408. raise ValueError(f"min_tokens must be greater than or equal to 0, "
  409. f"got {self.min_tokens}.")
  410. if self.max_tokens is not None and self.min_tokens > self.max_tokens:
  411. raise ValueError(
  412. f"min_tokens must be less than or equal to "
  413. f"max_tokens={self.max_tokens}, got {self.min_tokens}.")
  414. if self.logprobs is not None and self.logprobs < 0:
  415. raise ValueError(
  416. f"logprobs must be non-negative, got {self.logprobs}.")
  417. if self.prompt_logprobs is not None and self.prompt_logprobs < 0:
  418. raise ValueError("prompt_logprobs must be non-negative, got "
  419. f"{self.prompt_logprobs}.")
  420. if (self.truncate_prompt_tokens is not None
  421. and self.truncate_prompt_tokens < 1):
  422. raise ValueError(f"truncate_prompt_tokens must be >= 1, "
  423. f"got {self.truncate_prompt_tokens}")
  424. assert isinstance(self.stop, list)
  425. if any(not stop_str for stop_str in self.stop):
  426. raise ValueError("stop cannot contain an empty string.")
  427. if self.stop and not self.detokenize:
  428. raise ValueError(
  429. "stop strings are only supported when detokenize is True. "
  430. "Set detokenize=True to use stop.")
  431. if self.xtc_threshold < 0.0:
  432. raise ValueError(
  433. "xtc_threshold must be non-negative, got "
  434. f"{self.xtc_threshold}.")
  435. if not 0.0 <= self.xtc_probability <= 1.0:
  436. raise ValueError(
  437. "xtc_probability must be in [0, 1], got "
  438. f"{self.xtc_probability}.")
  439. if self.nsigma < 0.0:
  440. raise ValueError(
  441. "nsigma must be non-negative, got "
  442. f"{self.nsigma}.")
  443. if self.dry_multiplier < 0.0:
  444. raise ValueError(
  445. "dry_multiplier must be non-negative, got "
  446. f"{self.dry_multiplier}.")
  447. if self.dry_base <= 1.0:
  448. raise ValueError(
  449. "dry_base must be greater than 1, got "
  450. f"{self.dry_base}.")
  451. if self.dry_allowed_length < 0:
  452. raise ValueError(
  453. "dry_allowed_length must be non-negative, got "
  454. f"{self.dry_allowed_length}.")
  455. if self.dry_range < 0:
  456. raise ValueError(
  457. "dry_range must be non-negative, got "
  458. f"{self.dry_range}.")
  459. if self.skew < 0.0:
  460. raise ValueError(
  461. "skew must be non-negative, got "
  462. f"{self.skew}.")
  463. if self.sampler_priority is not None:
  464. if not self.sampler_priority:
  465. self.sampler_priority = None
  466. return
  467. if not isinstance(self.sampler_priority, list):
  468. raise ValueError(
  469. "sampler_priority must be a list of integers or strings")
  470. try:
  471. self.sampler_priority = [
  472. SamplerID.from_str(x) for x in self.sampler_priority
  473. ]
  474. provided_samplers = set(self.sampler_priority)
  475. except ValueError as e:
  476. raise ValueError(
  477. f"Invalid sampler ID in priority list: {e}"
  478. ) from e
  479. required_samplers = set(SamplerID)
  480. if not required_samplers.issubset(provided_samplers):
  481. missing = required_samplers - provided_samplers
  482. missing_names = [s.name for s in missing]
  483. raise ValueError(
  484. "Missing required samplers in priority list: "
  485. f"{missing_names}"
  486. )
  487. def _verify_beam_search(self) -> None:
  488. if self.best_of == 1:
  489. raise ValueError("best_of must be greater than 1 when using beam "
  490. f"search. Got {self.best_of}.")
  491. if self.temperature > _SAMPLING_EPS:
  492. raise ValueError("temperature must be 0 when using beam search.")
  493. if self.top_p < 1.0 - _SAMPLING_EPS:
  494. raise ValueError("top_p must be 1 when using beam search.")
  495. if self.top_k != -1:
  496. raise ValueError("top_k must be -1 when using beam search.")
  497. if self.early_stopping not in [True, False, "never"]:
  498. raise ValueError(
  499. f"early_stopping must be True, False, or 'never', "
  500. f"got {self.early_stopping}.")
  501. def _verify_non_beam_search(self) -> None:
  502. if self.early_stopping is not False:
  503. raise ValueError("early_stopping is not effective and must be "
  504. "False when not using beam search.")
  505. if (self.length_penalty < 1.0 - _SAMPLING_EPS
  506. or self.length_penalty > 1.0 + _SAMPLING_EPS):
  507. raise ValueError(
  508. "length_penalty is not effective and must be the "
  509. "default value of 1.0 when not using beam search.")
  510. def _verify_greedy_sampling(self) -> None:
  511. assert isinstance(self.best_of, int)
  512. if self.best_of > 1:
  513. raise ValueError("best_of must be 1 when using greedy sampling."
  514. f"Got {self.best_of}.")
  515. if self.top_p < 1.0 - _SAMPLING_EPS:
  516. raise ValueError("top_p must be 1 when using greedy sampling.")
  517. if self.top_k != -1:
  518. raise ValueError("top_k must be -1 when using greedy sampling.")
  519. def _verify_with_scheduler_config(
  520. self, scheduler_config: "SchedulerConfig") -> None:
  521. if scheduler_config.single_user_mode:
  522. if self.n > 1:
  523. raise ValueError("n must be 1 in single user mode.")
  524. if self.use_beam_search:
  525. raise ValueError(
  526. "beam search is not supported in single user mode.")
  527. def update_from_generation_config(
  528. self,
  529. generation_config: Dict[str, Any],
  530. model_eos_token_id: Optional[int] = None) -> None:
  531. """Update if there are non-default values from generation_config"""
  532. if model_eos_token_id is not None:
  533. # Add the eos token id into the sampling_params to support
  534. # min_tokens processing.
  535. self._all_stop_token_ids.add(model_eos_token_id)
  536. # Update eos_token_id for generation
  537. if (eos_ids := generation_config.get("eos_token_id")) is not None:
  538. # it can be either int or list of int
  539. eos_ids = {eos_ids} if isinstance(eos_ids, int) else set(eos_ids)
  540. if model_eos_token_id is not None:
  541. # We don't need to include the primary eos_token_id in
  542. # stop_token_ids since it's handled separately for stopping
  543. # purposes.
  544. eos_ids.discard(model_eos_token_id)
  545. if eos_ids:
  546. self._all_stop_token_ids.update(eos_ids)
  547. if not self.ignore_eos:
  548. assert isinstance(self.stop_token_ids, list)
  549. eos_ids.update(self.stop_token_ids)
  550. self.stop_token_ids = list(eos_ids)
  551. @cached_property
  552. def sampling_type(self) -> SamplingType:
  553. if self.use_beam_search:
  554. return SamplingType.BEAM
  555. if self.temperature < _SAMPLING_EPS:
  556. return SamplingType.GREEDY
  557. if self.seed is not None:
  558. return SamplingType.RANDOM_SEED
  559. return SamplingType.RANDOM
  560. @property
  561. def all_stop_token_ids(self) -> Set[int]:
  562. return self._all_stop_token_ids
  563. def clone(self) -> "SamplingParams":
  564. """Deep copy excluding LogitsProcessor objects.
  565. LogitsProcessor objects are excluded because they may contain an
  566. arbitrary, nontrivial amount of data.
  567. """
  568. logit_processor_refs = None if self.logits_processors is None else {
  569. id(lp): lp
  570. for lp in self.logits_processors
  571. }
  572. return copy.deepcopy(self, memo=logit_processor_refs)
  573. def __repr__(self) -> str:
  574. repr_str = "SamplingParams("
  575. for param, default_value in self.default_values.items():
  576. current_value = getattr(self, param)
  577. if current_value != default_value:
  578. repr_str += f"{param}={current_value}, "
  579. repr_str = repr_str.rstrip(', ') + ")"
  580. return repr_str