sampling_params.py 26 KB

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