sampling_params.py 27 KB

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