configuration_utils.py 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  1. # coding=utf-8
  2. # Copyright 2022 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Generation configuration class and utilities."""
  16. import copy
  17. import json
  18. import os
  19. import warnings
  20. from abc import ABC, abstractmethod
  21. from dataclasses import dataclass, is_dataclass
  22. from typing import TYPE_CHECKING, Any, Callable, Optional, Union
  23. from .. import __version__
  24. from ..configuration_utils import PretrainedConfig
  25. from ..utils import (
  26. GENERATION_CONFIG_NAME,
  27. ExplicitEnum,
  28. PushToHubMixin,
  29. cached_file,
  30. download_url,
  31. extract_commit_hash,
  32. is_remote_url,
  33. is_torch_available,
  34. logging,
  35. )
  36. if TYPE_CHECKING:
  37. from ..modeling_utils import PreTrainedModel
  38. logger = logging.get_logger(__name__)
  39. METADATA_FIELDS = ("_from_model_config", "_commit_hash", "_original_object_hash", "transformers_version")
  40. STATIC_CACHE_IMPLEMENTATIONS = ("static", "offloaded_static")
  41. DYNAMIC_CACHE_IMPLEMENTATIONS = ("dynamic", "dynamic_full", "offloaded", "quantized")
  42. # All the following are redundant and deprecated, but kept for BC
  43. DEPRECATED_STATIC_CACHE_IMPLEMENTATIONS = (
  44. "sliding_window",
  45. "hybrid",
  46. "hybrid_chunked",
  47. "offloaded_hybrid",
  48. "offloaded_hybrid_chunked",
  49. )
  50. ALL_STATIC_CACHE_IMPLEMENTATIONS = STATIC_CACHE_IMPLEMENTATIONS + DEPRECATED_STATIC_CACHE_IMPLEMENTATIONS
  51. ALL_CACHE_IMPLEMENTATIONS = ALL_STATIC_CACHE_IMPLEMENTATIONS + DYNAMIC_CACHE_IMPLEMENTATIONS
  52. if is_torch_available():
  53. from .logits_process import SynthIDTextWatermarkLogitsProcessor, WatermarkLogitsProcessor
  54. class GenerationMode(ExplicitEnum):
  55. """
  56. Possible generation modes, downstream of the [`~generation.GenerationMixin.generate`] method.
  57. """
  58. # Non-beam methods
  59. CONTRASTIVE_SEARCH = "contrastive_search"
  60. GREEDY_SEARCH = "greedy_search"
  61. SAMPLE = "sample"
  62. ASSISTED_GENERATION = "assisted_generation"
  63. DOLA_GENERATION = "dola_generation"
  64. # Beam methods
  65. BEAM_SEARCH = "beam_search"
  66. BEAM_SAMPLE = "beam_sample"
  67. CONSTRAINED_BEAM_SEARCH = "constrained_beam_search"
  68. GROUP_BEAM_SEARCH = "group_beam_search"
  69. class GenerationConfig(PushToHubMixin):
  70. # no-format
  71. """
  72. Class that holds a configuration for a generation task. A `generate` call supports the following generation methods
  73. for text-decoder, text-to-text, speech-to-text, and vision-to-text models:
  74. - *greedy decoding* if `num_beams=1` and `do_sample=False`
  75. - *multinomial sampling* if `num_beams=1` and `do_sample=True`
  76. - *beam-search decoding* if `num_beams>1` and `do_sample=False`
  77. - *beam-search multinomial sampling* if `num_beams>1` and `do_sample=True`
  78. - *assisted decoding* if `assistant_model` or `prompt_lookup_num_tokens` is passed to `.generate()`
  79. To learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
  80. <Tip>
  81. A large number of these flags control the logits or the stopping criteria of the generation. Make sure you check
  82. the [generate-related classes](https://huggingface.co/docs/transformers/internal/generation_utils) for a full
  83. description of the possible manipulations, as well as examples of their usage.
  84. </Tip>
  85. Arg:
  86. > Parameters that control the length of the output
  87. max_length (`int`, *optional*, defaults to 20):
  88. The maximum length the generated tokens can have. Corresponds to the length of the input prompt +
  89. `max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set.
  90. max_new_tokens (`int`, *optional*):
  91. The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
  92. min_length (`int`, *optional*, defaults to 0):
  93. The minimum length of the sequence to be generated. Corresponds to the length of the input prompt +
  94. `min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set.
  95. min_new_tokens (`int`, *optional*):
  96. The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.
  97. early_stopping (`bool` or `str`, *optional*, defaults to `False`):
  98. Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
  99. `True`, where the generation stops as soon as there are `num_beams` complete candidates; `False`, where an
  100. heuristic is applied and the generation stops when is it very unlikely to find better candidates;
  101. `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical
  102. beam search algorithm).
  103. max_time (`float`, *optional*):
  104. The maximum amount of time you allow the computation to run for in seconds. generation will still finish
  105. the current pass after allocated time has been passed.
  106. stop_strings (`str or list[str]`, *optional*):
  107. A string or a list of strings that should terminate generation if the model outputs them.
  108. > Parameters that control the generation strategy used
  109. do_sample (`bool`, *optional*, defaults to `False`):
  110. Whether or not to use sampling ; use greedy decoding otherwise.
  111. num_beams (`int`, *optional*, defaults to 1):
  112. Number of beams for beam search. 1 means no beam search.
  113. > Parameters that control the cache
  114. use_cache (`bool`, *optional*, defaults to `True`):
  115. Whether or not the model should use the past last key/values attentions (if applicable to the model) to
  116. speed up decoding.
  117. cache_implementation (`str`, *optional*, default to `None`):
  118. Name of the cache class that will be instantiated in `generate`, for faster decoding. Possible values are:
  119. - `"dynamic"`: [`DynamicCache`]
  120. - `"static"`: [`StaticCache`]
  121. - `"offloaded"`: [`DynamicCache(offloaded=True)`]
  122. - `"offloaded_static"`: [`StaticCache(offloaded=True)`]
  123. - `"quantized"`: [`QuantizedCache`]
  124. If none is specified, we will use the default cache for the model (which is often [`DynamicCache`]). See
  125. our [cache documentation](https://huggingface.co/docs/transformers/en/kv_cache) for further information.
  126. cache_config (`dict`, *optional*, default to `None`):
  127. Arguments used in the key-value cache class can be passed in `cache_config`.
  128. return_legacy_cache (`bool`, *optional*, default to `True`):
  129. Whether to return the legacy or new format of the cache when `DynamicCache` is used by default.
  130. > Parameters for manipulation of the model output logits
  131. temperature (`float`, *optional*, defaults to 1.0):
  132. The value used to module the next token probabilities. This value is set in a model's `generation_config.json` file. If it isn't set, the default value is 1.0
  133. top_k (`int`, *optional*, defaults to 50):
  134. The number of highest probability vocabulary tokens to keep for top-k-filtering. This value is set in a model's `generation_config.json` file. If it isn't set, the default value is 50.
  135. top_p (`float`, *optional*, defaults to 1.0):
  136. If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to
  137. `top_p` or higher are kept for generation. This value is set in a model's `generation_config.json` file. If it isn't set, the default value is 1.0
  138. min_p (`float`, *optional*):
  139. Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
  140. value between 0 and 1. Typical values are in the 0.01-0.2 range, comparably selective as setting `top_p` in
  141. the 0.99-0.8 range (use the opposite of normal `top_p` values).
  142. typical_p (`float`, *optional*, defaults to 1.0):
  143. Local typicality measures how similar the conditional probability of predicting a target token next is to
  144. the expected conditional probability of predicting a random token next, given the partial text already
  145. generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that
  146. add up to `typical_p` or higher are kept for generation. See [this
  147. paper](https://huggingface.co/papers/2202.00666) for more details.
  148. epsilon_cutoff (`float`, *optional*, defaults to 0.0):
  149. If set to float strictly between 0 and 1, only tokens with a conditional probability greater than
  150. `epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the
  151. size of the model. See [Truncation Sampling as Language Model
  152. Desmoothing](https://huggingface.co/papers/2210.15191) for more details.
  153. eta_cutoff (`float`, *optional*, defaults to 0.0):
  154. Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between
  155. 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) *
  156. exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token
  157. probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3,
  158. depending on the size of the model. See [Truncation Sampling as Language Model
  159. Desmoothing](https://huggingface.co/papers/2210.15191) for more details.
  160. repetition_penalty (`float`, *optional*, defaults to 1.0):
  161. The parameter for repetition penalty. 1.0 means no penalty. See [this
  162. paper](https://huggingface.co/papers/1909.05858) for more details.
  163. encoder_repetition_penalty (`float`, *optional*, defaults to 1.0):
  164. The parameter for encoder_repetition_penalty. An exponential penalty on sequences that are not in the
  165. original input. 1.0 means no penalty.
  166. length_penalty (`float`, *optional*, defaults to 1.0):
  167. Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to
  168. the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log
  169. likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while
  170. `length_penalty` < 0.0 encourages shorter sequences.
  171. no_repeat_ngram_size (`int`, *optional*, defaults to 0):
  172. If set to int > 0, all ngrams of that size can only occur once.
  173. bad_words_ids (`list[list[int]]`, *optional*):
  174. List of list of token ids that are not allowed to be generated. Check
  175. [`~generation.NoBadWordsLogitsProcessor`] for further documentation and examples.
  176. renormalize_logits (`bool`, *optional*, defaults to `False`):
  177. Whether to renormalize the logits after applying all the logits processors (including the custom
  178. ones). It's highly recommended to set this flag to `True` as the search algorithms suppose the score logits
  179. are normalized but some logit processors break the normalization.
  180. forced_bos_token_id (`int`, *optional*, defaults to `model.config.forced_bos_token_id`):
  181. The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for
  182. multilingual models like [mBART](../model_doc/mbart) where the first generated token needs to be the target
  183. language token.
  184. forced_eos_token_id (`int` or list[int]`, *optional*, defaults to `model.config.forced_eos_token_id`):
  185. The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a
  186. list to set multiple *end-of-sequence* tokens.
  187. remove_invalid_values (`bool`, *optional*, defaults to `model.config.remove_invalid_values`):
  188. Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash.
  189. Note that using `remove_invalid_values` can slow down generation.
  190. exponential_decay_length_penalty (`tuple(int, float)`, *optional*):
  191. This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been
  192. generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where
  193. penalty starts and `decay_factor` represents the factor of exponential decay
  194. suppress_tokens (`list[int]`, *optional*):
  195. A list of tokens that will be suppressed at generation. The `SuppressTokens` logit processor will set their
  196. log probs to `-inf` so that they are not sampled.
  197. begin_suppress_tokens (`list[int]`, *optional*):
  198. A list of tokens that will be suppressed at the beginning of the generation. The `SuppressBeginTokens` logit
  199. processor will set their log probs to `-inf` so that they are not sampled.
  200. sequence_bias (`dict[tuple[int], float]`, *optional*)):
  201. Dictionary that maps a sequence of tokens to its bias term. Positive biases increase the odds of the
  202. sequence being selected, while negative biases do the opposite. Check
  203. [`~generation.SequenceBiasLogitsProcessor`] for further documentation and examples.
  204. token_healing (`bool`, *optional*, defaults to `False`):
  205. Heal tail tokens of prompts by replacing them with their appropriate extensions.
  206. This enhances the quality of completions for prompts affected by greedy tokenization bias.
  207. guidance_scale (`float`, *optional*):
  208. The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.
  209. Higher guidance scale encourages the model to generate samples that are more closely linked to the input
  210. prompt, usually at the expense of poorer quality.
  211. watermarking_config (`BaseWatermarkingConfig` or `dict`, *optional*):
  212. Arguments used to watermark the model outputs by adding a small bias to randomly selected set of "green"
  213. tokens. See the docs of [`SynthIDTextWatermarkingConfig`] and [`WatermarkingConfig`] for more
  214. details. If passed as `Dict`, it will be converted to a `WatermarkingConfig` internally.
  215. > Parameters that define the output variables of generate
  216. num_return_sequences (`int`, *optional*, defaults to 1):
  217. The number of independently computed returned sequences for each element in the batch.
  218. output_attentions (`bool`, *optional*, defaults to `False`):
  219. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  220. tensors for more details.
  221. output_hidden_states (`bool`, *optional*, defaults to `False`):
  222. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  223. more details.
  224. output_scores (`bool`, *optional*, defaults to `False`):
  225. Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
  226. output_logits (`bool`, *optional*):
  227. Whether or not to return the unprocessed prediction logit scores. See `logits` under returned tensors for
  228. more details.
  229. return_dict_in_generate (`bool`, *optional*, defaults to `False`):
  230. Whether or not to return a [`~utils.ModelOutput`], as opposed to returning exclusively the generated
  231. sequence. This flag must be set to `True` to return the generation cache (when `use_cache` is `True`)
  232. or optional outputs (see flags starting with `output_`)
  233. > Special tokens that can be used at generation time
  234. pad_token_id (`int`, *optional*):
  235. The id of the *padding* token.
  236. bos_token_id (`int`, *optional*):
  237. The id of the *beginning-of-sequence* token.
  238. eos_token_id (`Union[int, list[int]]`, *optional*):
  239. The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
  240. > Generation parameters exclusive to encoder-decoder models
  241. encoder_no_repeat_ngram_size (`int`, *optional*, defaults to 0):
  242. If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the
  243. `decoder_input_ids`.
  244. decoder_start_token_id (`int` or `list[int]`, *optional*):
  245. If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token or a list of length
  246. `batch_size`. Indicating a list enables different start ids for each element in the batch
  247. (e.g. multilingual models with different target languages in one batch)
  248. > Generation parameters exclusive to assistant generation
  249. is_assistant (`bool`, *optional*, defaults to `False`):
  250. Whether the model is an assistant (draft) model.
  251. num_assistant_tokens (`int`, *optional*, defaults to 20):
  252. Defines the number of _speculative tokens_ that shall be generated by the assistant model before being
  253. checked by the target model at each iteration. Higher values for `num_assistant_tokens` make the generation
  254. more _speculative_ : If the assistant model is performant larger speed-ups can be reached, if the assistant
  255. model requires lots of corrections, lower speed-ups are reached.
  256. num_assistant_tokens_schedule (`str`, *optional*, defaults to `"constant"`):
  257. Defines the schedule at which max assistant tokens shall be changed during inference.
  258. - `"heuristic"`: When all speculative tokens are correct, increase `num_assistant_tokens` by 2 else
  259. reduce by 1. `num_assistant_tokens` value is persistent over multiple generation calls with the same assistant model.
  260. - `"heuristic_transient"`: Same as `"heuristic"` but `num_assistant_tokens` is reset to its initial value after each generation call.
  261. - `"constant"`: `num_assistant_tokens` stays unchanged during generation
  262. assistant_confidence_threshold (`float`, *optional*, defaults to 0.4):
  263. The confidence threshold for the assistant model. If the assistant model's confidence in its prediction for the current token is lower
  264. than this threshold, the assistant model stops the current token generation iteration, even if the number of _speculative tokens_
  265. (defined by `num_assistant_tokens`) is not yet reached. The assistant's confidence threshold is adjusted throughout the speculative iterations to reduce the number of unnecessary draft and target forward passes, biased towards avoiding false negatives.
  266. `assistant_confidence_threshold` value is persistent over multiple generation calls with the same assistant model.
  267. It is an unsupervised version of the dynamic speculation lookahead
  268. from Dynamic Speculation Lookahead Accelerates Speculative Decoding of Large Language Models <https://huggingface.co/papers/2405.04304>.
  269. prompt_lookup_num_tokens (`int`, *optional*):
  270. The number of tokens to be output as candidate tokens.
  271. max_matching_ngram_size (`int`, *optional*):
  272. The maximum ngram size to be considered for matching in the prompt. Default to 2 if not provided.
  273. assistant_early_exit(`int`, *optional*):
  274. If set to a positive integer, early exit of the model will be used as an assistant. Can only be used with
  275. models that support early exit (i.e. models where logits from intermediate layers can be interpreted by the LM head).
  276. assistant_lookbehind(`int`, *optional*, defaults to 10):
  277. If set to a positive integer, the re-encodeing process will additionally consider the last `assistant_lookbehind` assistant tokens
  278. to correctly align tokens. Can only be used with different tokenizers in speculative decoding.
  279. See this [blog](https://huggingface.co/blog/universal_assisted_generation) for more details.
  280. target_lookbehind(`int`, *optional*, defaults to 10):
  281. If set to a positive integer, the re-encodeing process will additionally consider the last `target_lookbehind` target tokens
  282. to correctly align tokens. Can only be used with different tokenizers in speculative decoding.
  283. See this [blog](https://huggingface.co/blog/universal_assisted_generation) for more details.
  284. > Parameters related to performances and compilation
  285. compile_config (CompileConfig, *optional*):
  286. If using a compilable cache, this controls how `generate` will `compile` the forward pass for faster
  287. inference.
  288. disable_compile (`bool`, *optional*):
  289. Whether to disable the automatic compilation of the forward pass. Automatic compilation happens when
  290. specific criteria are met, including using a compilable cache. Please open an issue if you find the
  291. need to use this flag.
  292. """
  293. extra_output_flags = ("output_attentions", "output_hidden_states", "output_scores", "output_logits")
  294. def __init__(self, **kwargs):
  295. # Parameters that control the length of the output
  296. self.max_length = kwargs.pop("max_length", 20)
  297. self.max_new_tokens = kwargs.pop("max_new_tokens", None)
  298. self.min_length = kwargs.pop("min_length", 0)
  299. self.min_new_tokens = kwargs.pop("min_new_tokens", None)
  300. self.early_stopping = kwargs.pop("early_stopping", False)
  301. self.max_time = kwargs.pop("max_time", None)
  302. self.stop_strings = kwargs.pop("stop_strings", None)
  303. # Parameters that control the generation strategy used
  304. self.do_sample = kwargs.pop("do_sample", False)
  305. self.num_beams = kwargs.pop("num_beams", 1)
  306. # Parameters that control the cache
  307. self.use_cache = kwargs.pop("use_cache", True)
  308. self.cache_implementation = kwargs.pop("cache_implementation", None)
  309. self.cache_config = kwargs.pop("cache_config", None)
  310. self.return_legacy_cache = kwargs.pop("return_legacy_cache", None)
  311. self.prefill_chunk_size = kwargs.pop("prefill_chunk_size", None)
  312. # Parameters for manipulation of the model output logits
  313. self.temperature = kwargs.pop("temperature", 1.0)
  314. self.top_k = kwargs.pop("top_k", 50)
  315. self.top_p = kwargs.pop("top_p", 1.0)
  316. self.min_p = kwargs.pop("min_p", None)
  317. self.typical_p = kwargs.pop("typical_p", 1.0)
  318. self.epsilon_cutoff = kwargs.pop("epsilon_cutoff", 0.0)
  319. self.eta_cutoff = kwargs.pop("eta_cutoff", 0.0)
  320. self.repetition_penalty = kwargs.pop("repetition_penalty", 1.0)
  321. self.encoder_repetition_penalty = kwargs.pop("encoder_repetition_penalty", 1.0)
  322. self.length_penalty = kwargs.pop("length_penalty", 1.0)
  323. self.no_repeat_ngram_size = kwargs.pop("no_repeat_ngram_size", 0)
  324. self.bad_words_ids = kwargs.pop("bad_words_ids", None)
  325. self.renormalize_logits = kwargs.pop("renormalize_logits", False)
  326. self.forced_bos_token_id = kwargs.pop("forced_bos_token_id", None)
  327. self.forced_eos_token_id = kwargs.pop("forced_eos_token_id", None)
  328. self.remove_invalid_values = kwargs.pop("remove_invalid_values", False)
  329. self.exponential_decay_length_penalty = kwargs.pop("exponential_decay_length_penalty", None)
  330. self.suppress_tokens = kwargs.pop("suppress_tokens", None)
  331. self.begin_suppress_tokens = kwargs.pop("begin_suppress_tokens", None)
  332. self.sequence_bias = kwargs.pop("sequence_bias", None)
  333. self.token_healing = kwargs.pop("token_healing", False)
  334. self.guidance_scale = kwargs.pop("guidance_scale", None)
  335. watermarking_config = kwargs.pop("watermarking_config", None)
  336. if watermarking_config is None:
  337. self.watermarking_config = None
  338. elif isinstance(watermarking_config, BaseWatermarkingConfig):
  339. self.watermarking_config = watermarking_config
  340. else:
  341. self.watermarking_config = WatermarkingConfig.from_dict(watermarking_config)
  342. # Parameters that define the output variables of `generate`
  343. self.num_return_sequences = kwargs.pop("num_return_sequences", 1)
  344. self.output_attentions = kwargs.pop("output_attentions", False)
  345. self.output_hidden_states = kwargs.pop("output_hidden_states", False)
  346. self.output_scores = kwargs.pop("output_scores", False)
  347. self.output_logits = kwargs.pop("output_logits", None)
  348. self.return_dict_in_generate = kwargs.pop("return_dict_in_generate", False)
  349. # Special tokens that can be used at generation time
  350. self.pad_token_id = kwargs.pop("pad_token_id", None)
  351. self.bos_token_id = kwargs.pop("bos_token_id", None)
  352. self.eos_token_id = kwargs.pop("eos_token_id", None)
  353. # Generation parameters exclusive to encoder-decoder models
  354. self.encoder_no_repeat_ngram_size = kwargs.pop("encoder_no_repeat_ngram_size", 0)
  355. self.decoder_start_token_id = kwargs.pop("decoder_start_token_id", None)
  356. # Assistant generation
  357. self.is_assistant = False
  358. self.num_assistant_tokens = kwargs.pop("num_assistant_tokens", 20)
  359. self.num_assistant_tokens_schedule = kwargs.pop("num_assistant_tokens_schedule", "constant")
  360. self.assistant_confidence_threshold = kwargs.pop("assistant_confidence_threshold", 0.4)
  361. self.prompt_lookup_num_tokens = kwargs.pop("prompt_lookup_num_tokens", None)
  362. self.max_matching_ngram_size = kwargs.pop("max_matching_ngram_size", None)
  363. self.assistant_early_exit = kwargs.pop("assistant_early_exit", None)
  364. ## assistant generation for different tokenizers, the windows size for assistant/target model
  365. self.assistant_lookbehind = kwargs.pop("assistant_lookbehind", 10)
  366. self.target_lookbehind = kwargs.pop("target_lookbehind", 10)
  367. # Performance
  368. self.compile_config = kwargs.pop("compile_config", None)
  369. self.disable_compile = kwargs.pop("disable_compile", False)
  370. # Deprecated (moved to the Hub). TODO joao, manuel: remove in v4.62.0
  371. self.low_memory = kwargs.pop("low_memory", None)
  372. self.penalty_alpha = kwargs.pop("penalty_alpha", None)
  373. self.dola_layers = kwargs.pop("dola_layers", None)
  374. self.diversity_penalty = kwargs.pop("diversity_penalty", 0.0)
  375. self.num_beam_groups = kwargs.pop("num_beam_groups", 1)
  376. self.constraints = kwargs.pop("constraints", None)
  377. self.force_words_ids = kwargs.pop("force_words_ids", None)
  378. # The remaining attributes do not parametrize `.generate()`, but are informative and/or used by the hub
  379. # interface.
  380. self._from_model_config = kwargs.pop("_from_model_config", False)
  381. self._commit_hash = kwargs.pop("_commit_hash", None)
  382. self.transformers_version = kwargs.pop("transformers_version", __version__)
  383. # Additional attributes without default values
  384. if not self._from_model_config:
  385. # we don't want to copy values from the model config if we're initializing a `GenerationConfig` from a
  386. # model's default configuration file
  387. for key, value in kwargs.items():
  388. try:
  389. setattr(self, key, value)
  390. except AttributeError as err:
  391. logger.error(f"Can't set {key} with value {value} for {self}")
  392. raise err
  393. # Validate the values of the attributes
  394. self.validate()
  395. def __hash__(self):
  396. return hash(self.to_json_string(ignore_metadata=True))
  397. def __eq__(self, other):
  398. if not isinstance(other, GenerationConfig):
  399. return False
  400. self_without_metadata = self.to_json_string(use_diff=False, ignore_metadata=True)
  401. other_without_metadata = other.to_json_string(use_diff=False, ignore_metadata=True)
  402. return self_without_metadata == other_without_metadata
  403. def __repr__(self):
  404. return f"{self.__class__.__name__} {self.to_json_string(ignore_metadata=True)}"
  405. def get_generation_mode(self, assistant_model: Optional["PreTrainedModel"] = None) -> GenerationMode:
  406. """
  407. Returns the generation mode triggered by the [`GenerationConfig`] instance.
  408. Arg:
  409. assistant_model (`PreTrainedModel`, *optional*):
  410. The assistant model to be used for assisted generation. If set, the generation mode will be
  411. assisted generation.
  412. Returns:
  413. `GenerationMode`: The generation mode triggered by the instance.
  414. """
  415. # TODO joao: find out a way of not depending on external fields (e.g. `assistant_model`), then make this a
  416. # property and part of the `__repr__`
  417. if self.constraints is not None or self.force_words_ids is not None:
  418. generation_mode = GenerationMode.CONSTRAINED_BEAM_SEARCH
  419. elif self.num_beams == 1:
  420. if self.do_sample is False:
  421. if (
  422. self.top_k is not None
  423. and self.top_k > 1
  424. and self.penalty_alpha is not None
  425. and self.penalty_alpha > 0
  426. ):
  427. generation_mode = GenerationMode.CONTRASTIVE_SEARCH
  428. else:
  429. generation_mode = GenerationMode.GREEDY_SEARCH
  430. else:
  431. generation_mode = GenerationMode.SAMPLE
  432. else:
  433. if self.num_beam_groups > 1:
  434. generation_mode = GenerationMode.GROUP_BEAM_SEARCH
  435. elif self.do_sample is True:
  436. generation_mode = GenerationMode.BEAM_SAMPLE
  437. else:
  438. generation_mode = GenerationMode.BEAM_SEARCH
  439. # Assisted generation may extend some generation modes
  440. if (
  441. assistant_model is not None
  442. or self.prompt_lookup_num_tokens is not None
  443. or self.assistant_early_exit is not None
  444. ):
  445. if generation_mode in ("greedy_search", "sample"):
  446. generation_mode = GenerationMode.ASSISTED_GENERATION
  447. else:
  448. logger.warning(
  449. "You've set `assistant_model`, which triggers assisted generate. Currently, assisted generate "
  450. "is only supported with Greedy Search and Sample. However, the base decoding mode (based on "
  451. f"current flags) is {generation_mode} -- some of the set flags will be ignored."
  452. )
  453. # DoLa generation may extend some generation modes
  454. # TODO joao, manuel: remove this in v4.62.0
  455. if self.dola_layers is not None:
  456. if generation_mode in ("greedy_search", "sample"):
  457. generation_mode = GenerationMode.DOLA_GENERATION
  458. else:
  459. logger.warning(
  460. "You've set `dola_layers`, which triggers DoLa generate. Currently, DoLa generate "
  461. "is only supported with Greedy Search and Sample. However, the base decoding mode (based on "
  462. f"current flags) is {generation_mode} -- some of the set flags will be ignored."
  463. )
  464. return generation_mode
  465. def validate(self, strict=False):
  466. """
  467. Validates the values of the attributes of the [`GenerationConfig`] instance. Raises exceptions in the presence
  468. of parameterization that can be detected as incorrect from the configuration instance alone.
  469. Note that some parameters not validated here are best validated at generate runtime, as they may depend on
  470. other inputs and/or the model, such as parameters related to the generation length.
  471. Args:
  472. strict (bool): If True, raise an exception for any issues found. If False, only log issues.
  473. """
  474. minor_issues = {} # format: {attribute_name: issue_description}
  475. # 1. Validation of individual attributes
  476. # 1.1. Decoding attributes
  477. if self.early_stopping not in {True, False, "never"}:
  478. raise ValueError(f"`early_stopping` must be a boolean or 'never', but is {self.early_stopping}.")
  479. if self.max_new_tokens is not None and self.max_new_tokens <= 0:
  480. raise ValueError(f"`max_new_tokens` must be greater than 0, but is {self.max_new_tokens}.")
  481. if self.pad_token_id is not None and self.pad_token_id < 0:
  482. minor_issues["pad_token_id"] = (
  483. f"`pad_token_id` should be positive but got {self.pad_token_id}. This will cause errors when batch "
  484. "generating, if there is padding. Please set `pad_token_id` explicitly as "
  485. "`model.generation_config.pad_token_id=PAD_TOKEN_ID` to avoid errors in generation"
  486. )
  487. # 1.2. Cache attributes
  488. if self.cache_implementation is not None and self.cache_implementation not in ALL_CACHE_IMPLEMENTATIONS:
  489. raise ValueError(
  490. f"Invalid `cache_implementation` ({self.cache_implementation}). Choose one of: "
  491. f"{ALL_CACHE_IMPLEMENTATIONS}"
  492. )
  493. # 1.3. Performance attributes
  494. if self.compile_config is not None and not isinstance(self.compile_config, CompileConfig):
  495. raise ValueError(
  496. f"You provided `compile_config` as an instance of {type(self.compile_config)}, but it must be an "
  497. "instance of `CompileConfig`."
  498. )
  499. # 1.4. Watermarking attributes
  500. if self.watermarking_config is not None:
  501. self.watermarking_config.validate()
  502. # 2. Validation of attribute combinations
  503. # 2.1. detect sampling-only parameterization when not in sampling mode
  504. if self.do_sample is False:
  505. greedy_wrong_parameter_msg = (
  506. "`do_sample` is set to `False`. However, `{flag_name}` is set to `{flag_value}` -- this flag is only "
  507. "used in sample-based generation modes. You should set `do_sample=True` or unset `{flag_name}`."
  508. )
  509. if self.temperature is not None and self.temperature != 1.0:
  510. minor_issues["temperature"] = greedy_wrong_parameter_msg.format(
  511. flag_name="temperature", flag_value=self.temperature
  512. )
  513. if self.top_p is not None and self.top_p != 1.0:
  514. minor_issues["top_p"] = greedy_wrong_parameter_msg.format(flag_name="top_p", flag_value=self.top_p)
  515. if self.min_p is not None:
  516. minor_issues["min_p"] = greedy_wrong_parameter_msg.format(flag_name="min_p", flag_value=self.min_p)
  517. if self.typical_p is not None and self.typical_p != 1.0:
  518. minor_issues["typical_p"] = greedy_wrong_parameter_msg.format(
  519. flag_name="typical_p", flag_value=self.typical_p
  520. )
  521. if self.top_k is not None and self.top_k != 50:
  522. minor_issues["top_k"] = greedy_wrong_parameter_msg.format(flag_name="top_k", flag_value=self.top_k)
  523. if self.epsilon_cutoff is not None and self.epsilon_cutoff != 0.0:
  524. minor_issues["epsilon_cutoff"] = greedy_wrong_parameter_msg.format(
  525. flag_name="epsilon_cutoff", flag_value=self.epsilon_cutoff
  526. )
  527. if self.eta_cutoff is not None and self.eta_cutoff != 0.0:
  528. minor_issues["eta_cutoff"] = greedy_wrong_parameter_msg.format(
  529. flag_name="eta_cutoff", flag_value=self.eta_cutoff
  530. )
  531. # 2.2. detect beam-only parameterization when not in beam mode
  532. if self.num_beams == 1:
  533. single_beam_wrong_parameter_msg = (
  534. "`num_beams` is set to 1. However, `{flag_name}` is set to `{flag_value}` -- this flag is only used "
  535. "in beam-based generation modes. You should set `num_beams>1` or unset `{flag_name}`."
  536. )
  537. if self.early_stopping is not False:
  538. minor_issues["early_stopping"] = single_beam_wrong_parameter_msg.format(
  539. flag_name="early_stopping", flag_value=self.early_stopping
  540. )
  541. if self.length_penalty is not None and self.length_penalty != 1.0:
  542. minor_issues["length_penalty"] = single_beam_wrong_parameter_msg.format(
  543. flag_name="length_penalty", flag_value=self.length_penalty
  544. )
  545. # 2.4. check `num_return_sequences`
  546. if self.num_return_sequences != 1:
  547. if self.num_beams == 1:
  548. if self.do_sample is False:
  549. raise ValueError(
  550. "Greedy methods without beam search do not support `num_return_sequences` different than 1 "
  551. f"(got {self.num_return_sequences})."
  552. )
  553. elif self.num_return_sequences > self.num_beams:
  554. raise ValueError(
  555. f"`num_return_sequences` ({self.num_return_sequences}) has to be smaller or equal to `num_beams` "
  556. f"({self.num_beams})."
  557. )
  558. # 2.5. check cache-related arguments
  559. if self.use_cache is False:
  560. # In this case, all cache-related arguments should be unset. However, since `use_cache=False` is often used
  561. # passed to `generate` directly to hot-fix cache issues, let's raise a warning instead of an error
  562. # (otherwise a user might need to overwrite several parameters).
  563. no_cache_warning = (
  564. "You have set `use_cache` to `False`, but {cache_arg} is set to {cache_arg_value}. {cache_arg} will "
  565. "have no effect."
  566. )
  567. for arg_name in ("cache_implementation", "cache_config", "return_legacy_cache"):
  568. if getattr(self, arg_name) is not None:
  569. minor_issues[arg_name] = no_cache_warning.format(
  570. cache_arg=arg_name, cache_arg_value=getattr(self, arg_name)
  571. )
  572. # 2.6. other incorrect combinations
  573. if self.return_dict_in_generate is not True:
  574. for extra_output_flag in self.extra_output_flags:
  575. if getattr(self, extra_output_flag) is True:
  576. minor_issues[extra_output_flag] = (
  577. f"`return_dict_in_generate` is NOT set to `True`, but `{extra_output_flag}` is. When "
  578. f"`return_dict_in_generate` is not `True`, `{extra_output_flag}` is ignored."
  579. )
  580. # 3. Check common issue: passing `generate` arguments inside the generation config
  581. generate_arguments = (
  582. "logits_processor",
  583. "stopping_criteria",
  584. "prefix_allowed_tokens_fn",
  585. "synced_gpus",
  586. "assistant_model",
  587. "streamer",
  588. "negative_prompt_ids",
  589. "negative_prompt_attention_mask",
  590. "use_model_defaults",
  591. )
  592. for arg in generate_arguments:
  593. if hasattr(self, arg):
  594. raise ValueError(
  595. f"Argument `{arg}` is not a valid argument of `GenerationConfig`. It should be passed to "
  596. "`generate()` (or a pipeline) directly."
  597. )
  598. # Finally, handle caught minor issues. With default parameterization, we will throw a minimal warning.
  599. if len(minor_issues) > 0:
  600. # Full list of issues with potential fixes
  601. info_message = []
  602. for attribute_name, issue_description in minor_issues.items():
  603. info_message.append(f"- `{attribute_name}`: {issue_description}")
  604. info_message = "\n".join(info_message)
  605. info_message += (
  606. "\nIf you're using a pretrained model, note that some of these attributes may be set through the "
  607. "model's `generation_config.json` file."
  608. )
  609. if strict:
  610. raise ValueError("GenerationConfig is invalid: \n" + info_message)
  611. else:
  612. attributes_with_issues = list(minor_issues.keys())
  613. warning_message = (
  614. f"The following generation flags are not valid and may be ignored: {attributes_with_issues}."
  615. )
  616. if logging.get_verbosity() >= logging.WARNING:
  617. warning_message += " Set `TRANSFORMERS_VERBOSITY=info` for more details."
  618. logger.warning_once(warning_message)
  619. logger.info_once(info_message)
  620. def save_pretrained(
  621. self,
  622. save_directory: Union[str, os.PathLike],
  623. config_file_name: Optional[Union[str, os.PathLike]] = None,
  624. push_to_hub: bool = False,
  625. **kwargs,
  626. ):
  627. r"""
  628. Save a generation configuration object to the directory `save_directory`, so that it can be re-loaded using the
  629. [`~GenerationConfig.from_pretrained`] class method.
  630. Args:
  631. save_directory (`str` or `os.PathLike`):
  632. Directory where the configuration JSON file will be saved (will be created if it does not exist).
  633. config_file_name (`str` or `os.PathLike`, *optional*, defaults to `"generation_config.json"`):
  634. Name of the generation configuration JSON file to be saved in `save_directory`.
  635. push_to_hub (`bool`, *optional*, defaults to `False`):
  636. Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
  637. repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
  638. namespace).
  639. kwargs (`dict[str, Any]`, *optional*):
  640. Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
  641. """
  642. # At save time, validate the instance enforcing strictness -- if any warning/exception would be thrown, we
  643. # refuse to save the instance.
  644. # This strictness is enforced to prevent bad configurations from being saved and re-used.
  645. try:
  646. self.validate(strict=True)
  647. except ValueError as exc:
  648. raise ValueError(str(exc) + "\n\nFix these issues to save the configuration.")
  649. use_auth_token = kwargs.pop("use_auth_token", None)
  650. if use_auth_token is not None:
  651. warnings.warn(
  652. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. "
  653. "Please use `token` instead.",
  654. FutureWarning,
  655. )
  656. if kwargs.get("token") is not None:
  657. raise ValueError(
  658. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  659. )
  660. kwargs["token"] = use_auth_token
  661. config_file_name = config_file_name if config_file_name is not None else GENERATION_CONFIG_NAME
  662. if os.path.isfile(save_directory):
  663. raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
  664. os.makedirs(save_directory, exist_ok=True)
  665. if push_to_hub:
  666. commit_message = kwargs.pop("commit_message", None)
  667. repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
  668. repo_id = self._create_repo(repo_id, **kwargs)
  669. files_timestamps = self._get_files_timestamps(save_directory)
  670. output_config_file = os.path.join(save_directory, config_file_name)
  671. self.to_json_file(output_config_file, use_diff=True)
  672. logger.info(f"Configuration saved in {output_config_file}")
  673. if push_to_hub:
  674. self._upload_modified_files(
  675. save_directory,
  676. repo_id,
  677. files_timestamps,
  678. commit_message=commit_message,
  679. token=kwargs.get("token"),
  680. )
  681. @classmethod
  682. def from_pretrained(
  683. cls,
  684. pretrained_model_name: Union[str, os.PathLike],
  685. config_file_name: Optional[Union[str, os.PathLike]] = None,
  686. cache_dir: Optional[Union[str, os.PathLike]] = None,
  687. force_download: bool = False,
  688. local_files_only: bool = False,
  689. token: Optional[Union[str, bool]] = None,
  690. revision: str = "main",
  691. **kwargs,
  692. ) -> "GenerationConfig":
  693. r"""
  694. Instantiate a [`GenerationConfig`] from a generation configuration file.
  695. Args:
  696. pretrained_model_name (`str` or `os.PathLike`):
  697. This can be either:
  698. - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
  699. huggingface.co.
  700. - a path to a *directory* containing a configuration file saved using the
  701. [`~GenerationConfig.save_pretrained`] method, e.g., `./my_model_directory/`.
  702. config_file_name (`str` or `os.PathLike`, *optional*, defaults to `"generation_config.json"`):
  703. Name of the generation configuration JSON file to be loaded from `pretrained_model_name`.
  704. cache_dir (`str` or `os.PathLike`, *optional*):
  705. Path to a directory in which a downloaded pretrained model configuration should be cached if the
  706. standard cache should not be used.
  707. force_download (`bool`, *optional*, defaults to `False`):
  708. Whether or not to force to (re-)download the configuration files and override the cached versions if
  709. they exist.
  710. resume_download:
  711. Deprecated and ignored. All downloads are now resumed by default when possible.
  712. Will be removed in v5 of Transformers.
  713. proxies (`dict[str, str]`, *optional*):
  714. A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
  715. 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
  716. token (`str` or `bool`, *optional*):
  717. The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
  718. the token generated when running `hf auth login` (stored in `~/.huggingface`).
  719. revision (`str`, *optional*, defaults to `"main"`):
  720. The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
  721. git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
  722. identifier allowed by git.
  723. <Tip>
  724. To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.
  725. </Tip>
  726. return_unused_kwargs (`bool`, *optional*, defaults to `False`):
  727. If `False`, then this function returns just the final configuration object.
  728. If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
  729. dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
  730. part of `kwargs` which has not been used to update `config` and is otherwise ignored.
  731. subfolder (`str`, *optional*, defaults to `""`):
  732. In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
  733. specify the folder name here.
  734. kwargs (`dict[str, Any]`, *optional*):
  735. The values in kwargs of any keys which are configuration attributes will be used to override the loaded
  736. values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
  737. by the `return_unused_kwargs` keyword parameter.
  738. Returns:
  739. [`GenerationConfig`]: The configuration object instantiated from this pretrained model.
  740. Examples:
  741. ```python
  742. >>> from transformers import GenerationConfig
  743. >>> # Download configuration from huggingface.co and cache.
  744. >>> generation_config = GenerationConfig.from_pretrained("openai-community/gpt2")
  745. >>> # E.g. config was saved using *save_pretrained('./test/saved_model/')*
  746. >>> generation_config.save_pretrained("./test/saved_model/")
  747. >>> generation_config = GenerationConfig.from_pretrained("./test/saved_model/")
  748. >>> # You can also specify configuration names to your generation configuration file
  749. >>> generation_config.save_pretrained("./test/saved_model/", config_file_name="my_configuration.json")
  750. >>> generation_config = GenerationConfig.from_pretrained("./test/saved_model/", "my_configuration.json")
  751. >>> # If you'd like to try a minor variation to an existing configuration, you can also pass generation
  752. >>> # arguments to `.from_pretrained()`. Be mindful that typos and unused arguments will be ignored
  753. >>> generation_config, unused_kwargs = GenerationConfig.from_pretrained(
  754. ... "openai-community/gpt2", top_k=1, foo=False, do_sample=True, return_unused_kwargs=True
  755. ... )
  756. >>> generation_config.top_k
  757. 1
  758. >>> unused_kwargs
  759. {'foo': False}
  760. ```"""
  761. config_file_name = config_file_name if config_file_name is not None else GENERATION_CONFIG_NAME
  762. resume_download = kwargs.pop("resume_download", None)
  763. proxies = kwargs.pop("proxies", None)
  764. use_auth_token = kwargs.pop("use_auth_token", None)
  765. subfolder = kwargs.pop("subfolder", "")
  766. from_pipeline = kwargs.pop("_from_pipeline", None)
  767. from_auto_class = kwargs.pop("_from_auto", False)
  768. commit_hash = kwargs.pop("_commit_hash", None)
  769. if use_auth_token is not None:
  770. warnings.warn(
  771. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  772. FutureWarning,
  773. )
  774. if token is not None:
  775. raise ValueError(
  776. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  777. )
  778. token = use_auth_token
  779. user_agent = {"file_type": "config", "from_auto_class": from_auto_class}
  780. if from_pipeline is not None:
  781. user_agent["using_pipeline"] = from_pipeline
  782. config_path = os.path.join(pretrained_model_name, config_file_name)
  783. config_path = str(config_path)
  784. is_local = os.path.exists(config_path)
  785. if os.path.isfile(os.path.join(subfolder, config_path)):
  786. # Special case when config_path is a local file
  787. resolved_config_file = config_path
  788. is_local = True
  789. elif is_remote_url(config_path):
  790. configuration_file = config_path
  791. resolved_config_file = download_url(config_path)
  792. else:
  793. configuration_file = config_file_name
  794. try:
  795. # Load from local folder or from cache or download from model Hub and cache
  796. resolved_config_file = cached_file(
  797. pretrained_model_name,
  798. configuration_file,
  799. cache_dir=cache_dir,
  800. force_download=force_download,
  801. proxies=proxies,
  802. resume_download=resume_download,
  803. local_files_only=local_files_only,
  804. token=token,
  805. user_agent=user_agent,
  806. revision=revision,
  807. subfolder=subfolder,
  808. _commit_hash=commit_hash,
  809. )
  810. commit_hash = extract_commit_hash(resolved_config_file, commit_hash)
  811. except OSError:
  812. # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
  813. # the original exception.
  814. raise
  815. except Exception:
  816. # For any other exception, we throw a generic error.
  817. raise OSError(
  818. f"Can't load the configuration of '{pretrained_model_name}'. If you were trying to load it"
  819. " from 'https://huggingface.co/models', make sure you don't have a local directory with the same"
  820. f" name. Otherwise, make sure '{pretrained_model_name}' is the correct path to a directory"
  821. f" containing a {configuration_file} file"
  822. )
  823. try:
  824. # Load config dict
  825. config_dict = cls._dict_from_json_file(resolved_config_file)
  826. config_dict["_commit_hash"] = commit_hash
  827. except (json.JSONDecodeError, UnicodeDecodeError):
  828. raise OSError(f"It looks like the config file at '{resolved_config_file}' is not a valid JSON file.")
  829. if is_local:
  830. logger.info(f"loading configuration file {resolved_config_file}")
  831. else:
  832. logger.info(f"loading configuration file {configuration_file} from cache at {resolved_config_file}")
  833. if kwargs.get("return_unused_kwargs") is True:
  834. config, unused_kwargs = cls.from_dict(config_dict, **kwargs)
  835. config._original_object_hash = hash(config) # Hash to detect whether the instance was modified
  836. return config, unused_kwargs
  837. else:
  838. config = cls.from_dict(config_dict, **kwargs)
  839. config._original_object_hash = hash(config) # Hash to detect whether the instance was modified
  840. return config
  841. @classmethod
  842. def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
  843. with open(json_file, "r", encoding="utf-8") as reader:
  844. text = reader.read()
  845. return json.loads(text)
  846. @classmethod
  847. def from_dict(cls, config_dict: dict[str, Any], **kwargs) -> "GenerationConfig":
  848. """
  849. Instantiates a [`GenerationConfig`] from a Python dictionary of parameters.
  850. Args:
  851. config_dict (`dict[str, Any]`):
  852. Dictionary that will be used to instantiate the configuration object.
  853. kwargs (`dict[str, Any]`):
  854. Additional parameters from which to initialize the configuration object.
  855. Returns:
  856. [`GenerationConfig`]: The configuration object instantiated from those parameters.
  857. """
  858. return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
  859. # Those arguments may be passed along for our internal telemetry.
  860. # We remove them so they don't appear in `return_unused_kwargs`.
  861. kwargs.pop("_from_auto", None)
  862. kwargs.pop("_from_pipeline", None)
  863. # The commit hash might have been updated in the `config_dict`, we don't want the kwargs to erase that update.
  864. if "_commit_hash" in kwargs and "_commit_hash" in config_dict:
  865. kwargs["_commit_hash"] = config_dict["_commit_hash"]
  866. # The line below allows model-specific config to be loaded as well through kwargs, with safety checks.
  867. # See https://github.com/huggingface/transformers/pull/21269
  868. config = cls(**{**config_dict, **kwargs})
  869. unused_kwargs = config.update(**kwargs)
  870. logger.info(f"Generate config {config}")
  871. if return_unused_kwargs:
  872. return config, unused_kwargs
  873. else:
  874. return config
  875. def dict_dtype_to_str(self, d: dict[str, Any]) -> None:
  876. """
  877. Checks whether the passed dictionary and its nested dicts have a *dtype* key and if it's not None,
  878. converts torch.dtype to a string of just the type. For example, `torch.float32` get converted into *"float32"*
  879. string, which can then be stored in the json format.
  880. """
  881. if d.get("dtype") is not None and not isinstance(d["dtype"], str):
  882. d["dtype"] = str(d["dtype"]).split(".")[1]
  883. for value in d.values():
  884. if isinstance(value, dict):
  885. self.dict_dtype_to_str(value)
  886. def to_diff_dict(self) -> dict[str, Any]:
  887. """
  888. Removes all attributes from config which correspond to the default config attributes for better readability and
  889. serializes to a Python dictionary.
  890. Returns:
  891. `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
  892. """
  893. config_dict = self.to_dict()
  894. # get the default config dict
  895. default_config_dict = GenerationConfig().to_dict()
  896. serializable_config_dict = {}
  897. # only serialize values that differ from the default config
  898. for key, value in config_dict.items():
  899. if key not in default_config_dict or key == "transformers_version" or value != default_config_dict[key]:
  900. serializable_config_dict[key] = value
  901. self.dict_dtype_to_str(serializable_config_dict)
  902. return serializable_config_dict
  903. def to_dict(self) -> dict[str, Any]:
  904. """
  905. Serializes this instance to a Python dictionary.
  906. Returns:
  907. `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  908. """
  909. output = copy.deepcopy(self.__dict__)
  910. # Fields to ignore at serialization time
  911. if "_commit_hash" in output:
  912. del output["_commit_hash"]
  913. if "_original_object_hash" in output:
  914. del output["_original_object_hash"]
  915. if "compile_config" in output:
  916. del output["compile_config"]
  917. # Transformers version when serializing this file
  918. output["transformers_version"] = __version__
  919. self.dict_dtype_to_str(output)
  920. return output
  921. def to_json_string(self, use_diff: bool = True, ignore_metadata: bool = False) -> str:
  922. """
  923. Serializes this instance to a JSON string.
  924. Args:
  925. use_diff (`bool`, *optional*, defaults to `True`):
  926. If set to `True`, only the difference between the config instance and the default `GenerationConfig()`
  927. is serialized to JSON string.
  928. ignore_metadata (`bool`, *optional*, defaults to `False`):
  929. Whether to ignore the metadata fields present in the instance
  930. Returns:
  931. `str`: String containing all the attributes that make up this configuration instance in JSON format.
  932. """
  933. if use_diff is True:
  934. config_dict = self.to_diff_dict()
  935. else:
  936. config_dict = self.to_dict()
  937. if ignore_metadata:
  938. for metadata_field in METADATA_FIELDS:
  939. config_dict.pop(metadata_field, None)
  940. def convert_keys_to_string(obj):
  941. if isinstance(obj, dict):
  942. return {str(key): convert_keys_to_string(value) for key, value in obj.items()}
  943. elif isinstance(obj, list):
  944. return [convert_keys_to_string(item) for item in obj]
  945. else:
  946. return obj
  947. def convert_dataclass_to_dict(obj):
  948. if isinstance(obj, dict):
  949. return {key: convert_dataclass_to_dict(value) for key, value in obj.items()}
  950. elif is_dataclass(obj):
  951. return obj.to_dict()
  952. else:
  953. return obj
  954. config_dict = convert_keys_to_string(config_dict)
  955. config_dict = convert_dataclass_to_dict(config_dict)
  956. return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
  957. def to_json_file(self, json_file_path: Union[str, os.PathLike], use_diff: bool = True):
  958. """
  959. Save this instance to a JSON file.
  960. Args:
  961. json_file_path (`str` or `os.PathLike`):
  962. Path to the JSON file in which this configuration instance's parameters will be saved.
  963. use_diff (`bool`, *optional*, defaults to `True`):
  964. If set to `True`, only the difference between the config instance and the default `GenerationConfig()`
  965. is serialized to JSON file.
  966. """
  967. with open(json_file_path, "w", encoding="utf-8") as writer:
  968. writer.write(self.to_json_string(use_diff=use_diff))
  969. @classmethod
  970. def from_model_config(cls, model_config: PretrainedConfig) -> "GenerationConfig":
  971. """
  972. Instantiates a [`GenerationConfig`] from a [`PretrainedConfig`]. This function is useful to convert legacy
  973. [`PretrainedConfig`] objects, which may contain generation parameters, into a stand-alone [`GenerationConfig`].
  974. Args:
  975. model_config (`PretrainedConfig`):
  976. The model config that will be used to instantiate the generation config.
  977. Returns:
  978. [`GenerationConfig`]: The configuration object instantiated from those parameters.
  979. """
  980. config_dict = model_config.to_dict()
  981. config_dict.pop("_from_model_config", None)
  982. # Removes all `None` from the model config dict -- this lets the generation config defaults to take hold
  983. config_dict = {key: value for key, value in config_dict.items() if value is not None}
  984. generation_config = cls.from_dict(config_dict, return_unused_kwargs=False, _from_model_config=True)
  985. # Special case: some models have generation attributes set in the decoder. Use them if still unset in the
  986. # generation config (which in turn is defined from the outer attributes of model config).
  987. decoder_config = model_config.get_text_config(decoder=True)
  988. if decoder_config is not model_config:
  989. default_generation_config = GenerationConfig()
  990. decoder_config_dict = decoder_config.to_dict()
  991. for attr in generation_config.to_dict():
  992. is_unset = getattr(generation_config, attr) == getattr(default_generation_config, attr)
  993. if attr in decoder_config_dict and is_unset:
  994. setattr(generation_config, attr, decoder_config_dict[attr])
  995. # If any `output_...` flag is set to `True`, we ensure `return_dict_in_generate` is set to `True`.
  996. if generation_config.return_dict_in_generate is False:
  997. if any(
  998. getattr(generation_config, extra_output_flag, False)
  999. for extra_output_flag in generation_config.extra_output_flags
  1000. ):
  1001. generation_config.return_dict_in_generate = True
  1002. # Hash to detect whether the instance was modified
  1003. generation_config._original_object_hash = hash(generation_config)
  1004. return generation_config
  1005. def update(self, **kwargs):
  1006. """
  1007. Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes,
  1008. returning all the unused kwargs.
  1009. Args:
  1010. kwargs (`dict[str, Any]`):
  1011. Dictionary of attributes to tentatively update this class.
  1012. Returns:
  1013. `dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance.
  1014. """
  1015. to_remove = []
  1016. for key, value in kwargs.items():
  1017. if hasattr(self, key):
  1018. setattr(self, key, value)
  1019. to_remove.append(key)
  1020. # Confirm that the updated instance is still valid
  1021. self.validate()
  1022. # Remove all the attributes that were updated, without modifying the input dict
  1023. unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove}
  1024. return unused_kwargs
  1025. @dataclass
  1026. class BaseWatermarkingConfig(ABC):
  1027. """Generic watermarking config"""
  1028. @classmethod
  1029. def from_dict(cls, config_dict, **kwargs):
  1030. """
  1031. Constructs a BaseWatermarkingConfig instance from a dictionary of parameters.
  1032. Args:
  1033. config_dict (dict[str, Any]): Dictionary containing configuration parameters.
  1034. **kwargs: Additional keyword arguments to override dictionary values.
  1035. Returns:
  1036. BaseWatermarkingConfig: Instance of BaseWatermarkingConfig constructed from the dictionary.
  1037. """
  1038. config = cls(**config_dict)
  1039. to_remove = []
  1040. for key, value in kwargs.items():
  1041. if hasattr(config, key):
  1042. setattr(config, key, value)
  1043. to_remove.append(key)
  1044. for key in to_remove:
  1045. kwargs.pop(key, None)
  1046. return config
  1047. def to_json_file(self, json_file_path: Union[str, os.PathLike]):
  1048. """
  1049. Save this instance to a JSON file.
  1050. Args:
  1051. json_file_path (Union[str, os.PathLike]): Path to the JSON file in which this configuration instance's parameters will be saved.
  1052. """
  1053. with open(json_file_path, "w", encoding="utf-8") as writer:
  1054. config_dict = self.to_dict()
  1055. json_string = json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
  1056. writer.write(json_string)
  1057. def to_dict(self) -> dict[str, Any]:
  1058. """
  1059. Serializes this instance to a Python dictionary.
  1060. Returns:
  1061. dict[str, Any]: Dictionary of all the attributes that make up this configuration instance.
  1062. """
  1063. output = copy.deepcopy(self.__dict__)
  1064. return output
  1065. def __iter__(self):
  1066. for attr, value in copy.deepcopy(self.__dict__).items():
  1067. yield attr, value
  1068. def __repr__(self):
  1069. return f"{self.__class__.__name__} {self.to_json_string()}"
  1070. def to_json_string(self):
  1071. """
  1072. Serializes this instance to a JSON formatted string.
  1073. Returns:
  1074. str: JSON formatted string representing the configuration instance.
  1075. """
  1076. return json.dumps(self.__dict__, indent=2) + "\n"
  1077. def update(self, **kwargs):
  1078. """
  1079. Update the configuration attributes with new values.
  1080. Args:
  1081. **kwargs: Keyword arguments representing configuration attributes and their new values.
  1082. """
  1083. for key, value in kwargs.items():
  1084. if hasattr(self, key):
  1085. setattr(self, key, value)
  1086. @abstractmethod
  1087. def validate(self): ...
  1088. @abstractmethod
  1089. def construct_processor(self, vocab_size): ...
  1090. @dataclass
  1091. class WatermarkingConfig(BaseWatermarkingConfig):
  1092. """
  1093. Class that holds arguments for watermark generation and should be passed into `GenerationConfig` during `generate`.
  1094. See [this paper](https://huggingface.co/papers/2306.04634) for more details on the arguments.
  1095. Accepts the following keys:
  1096. - greenlist_ratio (`float`):
  1097. Used for watermarking. The ratio of "green" tokens used to the vocabulary size. Defaults to 0.25.
  1098. - bias (`float`):
  1099. Used with watermarking. The bias added to the selected "green" tokens' logits. Defaults to 2.0.
  1100. - hashing_key (`int`):
  1101. Hashing key used for watermarking. Defaults to 15485863 (the millionth prime).
  1102. - seeding_scheme (`str`):
  1103. Algorithm to use for watermarking. Accepts values:
  1104. - "lefthash" (default): "green" tokens selection depend on the last token (Algorithm 2 from the paper)
  1105. - "selfhash": "green" tokens selection depends on the current token itself (Algorithm 3 from the paper)
  1106. The downside of this scheme is that it considers all possible next tokens and can be slower than "lefthash".
  1107. - context_width(`int`):
  1108. The context length of previous tokens to use in seeding. Higher context length makes watermarking more robust.
  1109. """
  1110. def __init__(
  1111. self,
  1112. greenlist_ratio: float = 0.25,
  1113. bias: float = 2.0,
  1114. hashing_key: int = 15485863,
  1115. seeding_scheme: str = "lefthash",
  1116. context_width: int = 1,
  1117. ):
  1118. self.greenlist_ratio = greenlist_ratio
  1119. self.bias = bias
  1120. self.hashing_key = hashing_key
  1121. self.seeding_scheme = seeding_scheme
  1122. self.context_width = context_width
  1123. def validate(self):
  1124. watermark_missing_arg_msg = (
  1125. "Some of the keys in `watermarking_config` are defined incorrectly. `{key}` should be {correct_value}` "
  1126. "but found {found_value}"
  1127. )
  1128. if self.seeding_scheme not in ["selfhash", "lefthash"]:
  1129. raise ValueError(
  1130. watermark_missing_arg_msg.format(
  1131. key="seeding_scheme",
  1132. correct_value="[`selfhash`, `lefthash`]",
  1133. found_value=self.seeding_scheme,
  1134. ),
  1135. )
  1136. if not 0.0 <= self.greenlist_ratio <= 1.0:
  1137. raise ValueError(
  1138. watermark_missing_arg_msg.format(
  1139. key="greenlist_ratio",
  1140. correct_value="in range between 0.0 and 1.0",
  1141. found_value=self.seeding_scheme,
  1142. ),
  1143. )
  1144. if not self.context_width >= 1:
  1145. raise ValueError(
  1146. watermark_missing_arg_msg.format(
  1147. key="context_width",
  1148. correct_value="a positive integer",
  1149. found_value=self.context_width,
  1150. ),
  1151. )
  1152. def construct_processor(self, vocab_size: int, device) -> "WatermarkLogitsProcessor":
  1153. return WatermarkLogitsProcessor(
  1154. vocab_size=vocab_size,
  1155. device=device,
  1156. greenlist_ratio=self.greenlist_ratio,
  1157. bias=self.bias,
  1158. hashing_key=self.hashing_key,
  1159. seeding_scheme=self.seeding_scheme,
  1160. context_width=self.context_width,
  1161. )
  1162. @dataclass
  1163. class SynthIDTextWatermarkingConfig(BaseWatermarkingConfig):
  1164. """
  1165. Class that holds arguments for watermark generation and should be passed into `GenerationConfig` during `generate`.
  1166. See [this paper](https://www.nature.com/articles/s41586-024-08025-4) for more details on the arguments.
  1167. Args:
  1168. ngram_len (`int`):
  1169. Ngram length.
  1170. keys (`list[int]`):
  1171. A sequence of watermarking keys, one for each depth.
  1172. context_history_size (`int`, *optional*, defaults to 1024):
  1173. Size of the tensor to keep track of seen contexts.
  1174. sampling_table_seed (`int`, *optional*, defaults to 0):
  1175. Random seed to generate the sampling table.
  1176. sampling_table_size (`int`, *optional*, defaults to 65536):
  1177. Size of the sampling table.
  1178. skip_first_ngram_calls (`bool`, *optional*, defaults to `False`):
  1179. Whether to skip first ngram calls.
  1180. debug_mode (`bool`, optional, *optional*, defaults to `False`):
  1181. Logits are modified to uniform one got before watermarking modification is applied. This is to test the
  1182. implementation.
  1183. Examples:
  1184. ```python
  1185. >>> from transformers import AutoModelForCausalLM, AutoTokenizer, SynthIDTextWatermarkingConfig
  1186. >>> tokenizer = AutoTokenizer.from_pretrained('google/gemma-2-2b', padding_side="left")
  1187. >>> model = AutoModelForCausalLM.from_pretrained('google/gemma-2-2b')
  1188. >>> # SynthID Text configuration
  1189. >>> watermarking_config = SynthIDTextWatermarkingConfig(
  1190. ... keys=[654, 400, 836, 123, 340, 443, 597, 160, 57],
  1191. ... ngram_len=5,
  1192. ... )
  1193. >>> # Generation with watermarking
  1194. >>> tokenized_prompts = tokenizer(["Once upon a time, "], return_tensors="pt", padding=True)
  1195. >>> output_sequences = model.generate(
  1196. ... **tokenized_prompts, watermarking_config=watermarking_config, do_sample=True, max_new_tokens=10
  1197. ... )
  1198. >>> watermarked_text = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)
  1199. ```
  1200. """
  1201. def __init__(
  1202. self,
  1203. ngram_len: int,
  1204. keys: list[int],
  1205. context_history_size: int = 1024,
  1206. sampling_table_seed: int = 0,
  1207. sampling_table_size: int = 2**16,
  1208. skip_first_ngram_calls: bool = False,
  1209. debug_mode: bool = False,
  1210. ):
  1211. self.ngram_len = ngram_len
  1212. self.keys = keys
  1213. self.sampling_table_size = sampling_table_size
  1214. self.sampling_table_seed = sampling_table_seed
  1215. self.context_history_size = context_history_size
  1216. self.skip_first_ngram_calls = skip_first_ngram_calls
  1217. self.debug_mode = debug_mode
  1218. def validate(self):
  1219. watermark_missing_arg_msg = (
  1220. "Some of the keys in `watermarking_config` are defined incorrectly. `{key}` should be {correct_value}` "
  1221. "but found {found_value}"
  1222. )
  1223. if self.sampling_table_size > 2**24:
  1224. raise ValueError(
  1225. watermark_missing_arg_msg.format(
  1226. key="sampling_table_size",
  1227. correct_value="< 2**24",
  1228. found_value=self.sampling_table_size,
  1229. ),
  1230. )
  1231. def construct_processor(self, vocab_size: int, device) -> "WatermarkLogitsProcessor":
  1232. return SynthIDTextWatermarkLogitsProcessor(
  1233. ngram_len=self.ngram_len,
  1234. keys=self.keys,
  1235. sampling_table_size=self.sampling_table_size,
  1236. sampling_table_seed=self.sampling_table_seed,
  1237. context_history_size=self.context_history_size,
  1238. device=device,
  1239. skip_first_ngram_calls=self.skip_first_ngram_calls,
  1240. debug_mode=self.debug_mode,
  1241. )
  1242. @dataclass
  1243. class CompileConfig:
  1244. """
  1245. Class that holds arguments relative to `torch.compile` behavior, when using automatic compilation in `generate`.
  1246. See [`torch.compile`](https://pytorch.org/docs/stable/generated/torch.compile.html) for more details on the arguments.
  1247. Args:
  1248. fullgraph (`bool`, *optional*, defaults to `False`):
  1249. If False (default), attempts to discover compileable regions that will be optimized. If True, then require
  1250. that the entire function be capturable into a single graph. If this is not possible (that is, if there are
  1251. graph breaks), then an error will be raised.
  1252. dynamic (`bool` or `None`, *optional*):
  1253. Whether to try to use dynamic shape graphs.
  1254. backend (`str` or `Callable`, *optional*, defaults to `"inductor"`):
  1255. Backend to be used.
  1256. mode (`str`, *optional*, defaults to `"reduce-overhead"`):
  1257. Controls balance between performance and overhead.
  1258. options (`dict`, *optional*):
  1259. A dictionary of options to pass to the backend.
  1260. Examples:
  1261. ```python
  1262. >>> from transformers import AutoModelForCausalLM, AutoTokenizer, CompileConfig
  1263. >>> tokenizer = AutoTokenizer.from_pretrained('google/gemma-2-2b')
  1264. >>> model = AutoModelForCausalLM.from_pretrained('google/gemma-2-2b').cuda()
  1265. >>> # Automatic compile configuration, used with static cache
  1266. >>> compile_config = CompileConfig(dynamic=True)
  1267. >>> # Generation with static cache and compile config
  1268. >>> input = tokenizer.encode("Hello there, how", return_tensors="pt").cuda()
  1269. >>> output = model.generate(
  1270. ... input, do_sample=False, max_new_tokens=300, cache_implementation="static", compile_config=compile_config
  1271. ... )
  1272. >>> output_text = tokenizer.batch_decode(output, skip_special_tokens=True)[0]
  1273. ```
  1274. """
  1275. fullgraph: bool = False
  1276. dynamic: Optional[bool] = None
  1277. backend: Union[str, Callable] = "inductor"
  1278. mode: str = "reduce-overhead"
  1279. options: Optional[dict] = None
  1280. # Used to flag our `generate` call to compile on e.g. CPU. Often not optimal, but useful for testing purposes.
  1281. _compile_all_devices = None
  1282. def to_dict(self) -> dict[str, Any]:
  1283. """Serializes this instance to a Python dictionary."""
  1284. return copy.deepcopy({key: value for key, value in self.__dict__.items() if key != "_compile_all_devices"})