1
0

sampling_params.py 24 KB

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