# Text Generation

## Generation

Each framework has a generate method for text generation implemented in their respective `GenerationMixin` class:

* PyTorch [generate()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.generate) is implemented in [GenerationMixin](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin).
* TensorFlow [generate()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.TFGenerationMixin.generate) is implemented in [TFGenerationMixin](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.TFGenerationMixin).
* Flax/JAX [generate()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.FlaxGenerationMixin.generate) is implemented in [FlaxGenerationMixin](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.FlaxGenerationMixin).

Regardless of your framework of choice, you can parameterize the generate method with a [GenerationConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig) class instance. Please refer to this class for the complete list of generation parameters, which control the behavior of the generation method.

To learn how to inspect a model’s generation configuration, what are the defaults, how to change the parameters ad hoc, and how to create and save a customized generation configuration, refer to the [text generation strategies guide](https://huggingface.co/docs/transformers/generation_strategies). The guide also explains how to use related features, like token streaming.

### GenerationConfig

#### class transformers.GenerationConfig

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/configuration_utils.py#L40)

( \*\*kwargs )

Parameters that control the length of the output

* **max\_length** (`int`, _optional_, defaults to 20) — The maximum length the generated tokens can have. Corresponds to the length of the input prompt + `max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set.
* **max\_new\_tokens** (`int`, _optional_) — The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
* **min\_length** (`int`, _optional_, defaults to 0) — The minimum length of the sequence to be generated. Corresponds to the length of the input prompt + `min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set.
* **min\_new\_tokens** (`int`, _optional_) — The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.
* **early\_stopping** (`bool` or `str`, _optional_, defaults to `False`) — Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values: `True`, where the generation stops as soon as there are `num_beams` complete candidates; `False`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates; `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).
* **max\_time(`float`,** _optional_) — The maximum amount of time you allow the computation to run for in seconds. generation will still finish the current pass after allocated time has been passed.

Parameters that control the generation strategy used

* **do\_sample** (`bool`, _optional_, defaults to `False`) — Whether or not to use sampling ; use greedy decoding otherwise.
* **num\_beams** (`int`, _optional_, defaults to 1) — Number of beams for beam search. 1 means no beam search.
* **num\_beam\_groups** (`int`, _optional_, defaults to 1) — Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams. [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
* **penalty\_alpha** (`float`, _optional_) — The values balance the model confidence and the degeneration penalty in contrastive search decoding.
* **use\_cache** (`bool`, _optional_, defaults to `True`) — Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.

Parameters for manipulation of the model output logits

* **temperature** (`float`, _optional_, defaults to 1.0) — The value used to modulate the next token probabilities.
* **top\_k** (`int`, _optional_, defaults to 50) — The number of highest probability vocabulary tokens to keep for top-k-filtering.
* **top\_p** (`float`, _optional_, defaults to 1.0) — If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.
* **typical\_p** (`float`, _optional_, defaults to 1.0) — Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.
* **epsilon\_cutoff** (`float`, _optional_, defaults to 0.0) — If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
* **eta\_cutoff** (`float`, _optional_, defaults to 0.0) — Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
* **diversity\_penalty** (`float`, _optional_, defaults to 0.0) — This value is subtracted from a beam’s score if it generates a token same as any beam from other group at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled.
* **repetition\_penalty** (`float`, _optional_, defaults to 1.0) — The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
* **encoder\_repetition\_penalty** (`float`, _optional_, defaults to 1.0) — The paramater for encoder\_repetition\_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
* **length\_penalty** (`float`, _optional_, defaults to 1.0) — Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.
* **no\_repeat\_ngram\_size** (`int`, _optional_, defaults to 0) — If set to int > 0, all ngrams of that size can only occur once.
* **bad\_words\_ids(`List[List[int]]`,** _optional_) — List of list of token ids that are not allowed to be generated. Check [NoBadWordsLogitsProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.NoBadWordsLogitsProcessor) for further documentation and examples.
* **force\_words\_ids(`List[List[int]]`** or `List[List[List[int]]]`, _optional_) — List of token ids that must be generated. If given a `List[List[int]]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. If given `List[List[List[int]]]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word.
* **renormalize\_logits** (`bool`, _optional_, defaults to `False`) — Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). It’s highly recommended to set this flag to `True` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization.
* **constraints** (`List[Constraint]`, _optional_) — Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible.
* **forced\_bos\_token\_id** (`int`, _optional_, defaults to `model.config.forced_bos_token_id`) — The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for multilingual models like [mBART](https://huggingface.co/docs/transformers/model_doc/mbart) where the first generated token needs to be the target language token.
* **forced\_eos\_token\_id** (`Union[int, List[int]]`, _optional_, defaults to `model.config.forced_eos_token_id`) — The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a list to set multiple _end-of-sequence_ tokens.
* **remove\_invalid\_values** (`bool`, _optional_, defaults to `model.config.remove_invalid_values`) — Whether to remove possible _nan_ and _inf_ outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation.
* **exponential\_decay\_length\_penalty** (`tuple(int, float)`, _optional_) — This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay
* **suppress\_tokens** (`List[int]`, _optional_) — A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
* **begin\_suppress\_tokens** (`List[int]`, _optional_) — A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
* **forced\_decoder\_ids** (`List[List[int]]`, _optional_) — A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token of index 123.
* **sequence\_bias** (`Dict[Tuple[int], float]`, _optional_)) — Dictionary that maps a sequence of tokens to its bias term. Positive biases increase the odds of the sequence being selected, while negative biases do the opposite. Check [SequenceBiasLogitsProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.SequenceBiasLogitsProcessor) for further documentation and examples.
* **guidance\_scale** (`float`, _optional_) — The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages the model to generate samples that are more closely linked to the input prompt, usually at the expense of poorer quality.
* **low\_memory** (`bool`, _optional_) — Switch to sequential topk for contrastive search to reduce peak memory. Used with contrastive search.

Parameters that define the output variables of \`generate\`

* **num\_return\_sequences(`int`,** _optional_, defaults to 1) — The number of independently computed returned sequences for each element in the batch.
* **output\_attentions** (`bool`, _optional_, defaults to `False`) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
* **output\_hidden\_states** (`bool`, _optional_, defaults to `False`) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
* **output\_scores** (`bool`, _optional_, defaults to `False`) — Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
* **return\_dict\_in\_generate** (`bool`, _optional_, defaults to `False`) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.

Special tokens that can be used at generation time

* **pad\_token\_id** (`int`, _optional_) — The id of the _padding_ token.
* **bos\_token\_id** (`int`, _optional_) — The id of the _beginning-of-sequence_ token.
* **eos\_token\_id** (`Union[int, List[int]]`, _optional_) — The id of the _end-of-sequence_ token. Optionally, use a list to set multiple _end-of-sequence_ tokens.

Generation parameters exclusive to encoder-decoder models

* **encoder\_no\_repeat\_ngram\_size** (`int`, _optional_, defaults to 0) — If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.
* **decoder\_start\_token\_id** (`int`, _optional_) — If an encoder-decoder model starts decoding with a different token than _bos_, the id of that token.

Wild card

*

Class that holds a configuration for a generation task. A `generate` call supports the following generation methods for text-decoder, text-to-text, speech-to-text, and vision-to-text models:

* _greedy decoding_ by calling [greedy\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.greedy_search) if `num_beams=1` and `do_sample=False`
* _contrastive search_ by calling [contrastive\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.contrastive_search) if `penalty_alpha>0.` and `top_k>1`
* _multinomial sampling_ by calling [sample()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.sample) if `num_beams=1` and `do_sample=True`
* _beam-search decoding_ by calling [beam\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.beam_search) if `num_beams>1` and `do_sample=False`
* _beam-search multinomial sampling_ by calling [beam\_sample()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.beam_sample) if `num_beams>1` and `do_sample=True`
* _diverse beam-search decoding_ by calling [group\_beam\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.group_beam_search), if `num_beams>1` and `num_beam_groups>1`
* _constrained beam-search decoding_ by calling [constrained\_beam\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.constrained_beam_search), if `constraints!=None` or `force_words_ids!=None`
* _assisted decoding_ by calling `assisted_decoding()`, if `assistant_model` is passed to `.generate()`

You do not need to call any of the above methods directly. Pass custom parameter values to ‘.generate()‘. To learn more about decoding strategies refer to the [text generation strategies guide](https://huggingface.co/docs/transformers/generation_strategies).

**from\_pretrained**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/configuration_utils.py#L555)

( pretrained\_model\_name: typing.Union\[str, os.PathLike]config\_file\_name: typing.Union\[str, os.PathLike, NoneType] = Nonecache\_dir: typing.Union\[str, os.PathLike, NoneType] = Noneforce\_download: bool = Falselocal\_files\_only: bool = Falsetoken: typing.Union\[str, bool, NoneType] = Nonerevision: str = 'main'\*\*kwargs ) → [GenerationConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig)

Parameters

* **pretrained\_model\_name** (`str` or `os.PathLike`) — This can be either:
  * a string, the _model id_ of a pretrained model configuration hosted inside a model repo on boincai.com. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`.
  * a path to a _directory_ containing a configuration file saved using the [save\_pretrained()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig.save_pretrained) method, e.g., `./my_model_directory/`.
* **config\_file\_name** (`str` or `os.PathLike`, _optional_, defaults to `"generation_config.json"`) — Name of the generation configuration JSON file to be loaded from `pretrained_model_name`.
* **cache\_dir** (`str` or `os.PathLike`, _optional_) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.
* **force\_download** (`bool`, _optional_, defaults to `False`) — Whether or not to force to (re-)download the configuration files and override the cached versions if they exist.
* **resume\_download** (`bool`, _optional_, defaults to `False`) — Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists.
* **proxies** (`Dict[str, str]`, _optional_) — A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
* **token** (`str` or `bool`, _optional_) — The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use the token generated when running `boincai-cli login` (stored in `~/.boincai`).
*   **revision** (`str`, _optional_, defaults to `"main"`) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on boincai.com, so `revision` can be any identifier allowed by git.

    To test a pull request you made on the Hub, you can pass \`revision=“refs/pr/“.
*   **return\_unused\_kwargs** (`bool`, _optional_, defaults to `False`) — If `False`, then this function returns just the final configuration object.

    If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where _unused\_kwargs_ is a dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the part of `kwargs` which has not been used to update `config` and is otherwise ignored.
* **subfolder** (`str`, _optional_, defaults to `""`) — In case the relevant files are located inside a subfolder of the model repo on boincai.com, you can specify the folder name here.
* **kwargs** (`Dict[str, Any]`, _optional_) — The values in kwargs of any keys which are configuration attributes will be used to override the loaded values. Behavior concerning key/value pairs whose keys are _not_ configuration attributes is controlled by the `return_unused_kwargs` keyword parameter.

Returns

[GenerationConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig)

The configuration object instantiated from this pretrained model.

Instantiate a [GenerationConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig) from a generation configuration file.



Examples:

Copied

```
>>> from transformers import GenerationConfig

>>> # Download configuration from boincai.com and cache.
>>> generation_config = GenerationConfig.from_pretrained("gpt2")

>>> # E.g. config was saved using *save_pretrained('./test/saved_model/')*
>>> generation_config.save_pretrained("./test/saved_model/")
>>> generation_config = GenerationConfig.from_pretrained("./test/saved_model/")

>>> # You can also specify configuration names to your generation configuration file
>>> generation_config.save_pretrained("./test/saved_model/", config_file_name="my_configuration.json")
>>> generation_config = GenerationConfig.from_pretrained("./test/saved_model/", "my_configuration.json")

>>> # If you'd like to try a minor variation to an existing configuration, you can also pass generation
>>> # arguments to `.from_pretrained()`. Be mindful that typos and unused arguments will be ignored
>>> generation_config, unused_kwargs = GenerationConfig.from_pretrained(
...     "gpt2", top_k=1, foo=False, do_sample=True, return_unused_kwargs=True
... )
>>> generation_config.top_k
1

>>> unused_kwargs
{'foo': False}
```

**from\_model\_config**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/configuration_utils.py#L871)

( model\_config: PretrainedConfig ) → [GenerationConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig)

Parameters

* **model\_config** (`PretrainedConfig`) — The model config that will be used to instantiate the generation config.

Returns

[GenerationConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig)

The configuration object instantiated from those parameters.

Instantiates a [GenerationConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig) from a [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig). This function is useful to convert legacy [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) objects, which may contain generation parameters, into a stand-alone [GenerationConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig).

**save\_pretrained**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/configuration_utils.py#L477)

( save\_directory: typing.Union\[str, os.PathLike]config\_file\_name: typing.Union\[str, os.PathLike, NoneType] = Nonepush\_to\_hub: bool = False\*\*kwargs )

Parameters

* **save\_directory** (`str` or `os.PathLike`) — Directory where the configuration JSON file will be saved (will be created if it does not exist).
* **config\_file\_name** (`str` or `os.PathLike`, _optional_, defaults to `"generation_config.json"`) — Name of the generation configuration JSON file to be saved in `save_directory`.
* **push\_to\_hub** (`bool`, _optional_, defaults to `False`) — Whether or not to push your model to the BOINC AI model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace).
* **kwargs** (`Dict[str, Any]`, _optional_) — Additional key word arguments passed along to the [push\_to\_hub()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/processors#transformers.ProcessorMixin.push_to_hub) method.

Save a generation configuration object to the directory `save_directory`, so that it can be re-loaded using the [from\_pretrained()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig.from_pretrained) class method.

### GenerationMixin

#### class transformers.GenerationMixin

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/utils.py#L491)

( )

A class containing all functions for auto-regressive text generation, to be used as a mixin in [PreTrainedModel](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.PreTrainedModel).

The class exposes [generate()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.generate), which can be used for:

* _greedy decoding_ by calling [greedy\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.greedy_search) if `num_beams=1` and `do_sample=False`
* _contrastive search_ by calling [contrastive\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.contrastive_search) if `penalty_alpha>0` and `top_k>1`
* _multinomial sampling_ by calling [sample()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.sample) if `num_beams=1` and `do_sample=True`
* _beam-search decoding_ by calling [beam\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.beam_search) if `num_beams>1` and `do_sample=False`
* _beam-search multinomial sampling_ by calling [beam\_sample()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.beam_sample) if `num_beams>1` and `do_sample=True`
* _diverse beam-search decoding_ by calling [group\_beam\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.group_beam_search), if `num_beams>1` and `num_beam_groups>1`
* _constrained beam-search decoding_ by calling [constrained\_beam\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.constrained_beam_search), if `constraints!=None` or `force_words_ids!=None`

You do not need to call any of the above methods directly. Pass custom parameter values to ‘generate’ instead. To learn more about decoding strategies refer to the [text generation strategies guide](https://huggingface.co/docs/transformers/generation_strategies).

**generate**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/utils.py#L1300)

( inputs: typing.Optional\[torch.Tensor] = Nonegeneration\_config: typing.Optional\[transformers.generation.configuration\_utils.GenerationConfig] = Nonelogits\_processor: typing.Optional\[transformers.generation.logits\_process.LogitsProcessorList] = Nonestopping\_criteria: typing.Optional\[transformers.generation.stopping\_criteria.StoppingCriteriaList] = Noneprefix\_allowed\_tokens\_fn: typing.Union\[typing.Callable\[\[int, torch.Tensor], typing.List\[int]], NoneType] = Nonesynced\_gpus: typing.Optional\[bool] = Noneassistant\_model: typing.Optional\[ForwardRef('PreTrainedModel')] = Nonestreamer: typing.Optional\[ForwardRef('BaseStreamer')] = Nonenegative\_prompt\_ids: typing.Optional\[torch.Tensor] = Nonenegative\_prompt\_attention\_mask: typing.Optional\[torch.Tensor] = None\*\*kwargs ) → [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) or `torch.LongTensor`

Parameters

* **inputs** (`torch.Tensor` of varying shape depending on the modality, _optional_) — The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs` should of in the format of `input_ids`. For encoder-decoder models _inputs_ can represent any of `input_ids`, `input_values`, `input_features`, or `pixel_values`.
* **generation\_config** (`~generation.GenerationConfig`, _optional_) — The generation configuration to be used as base parametrization for the generation call. `**kwargs` passed to generate matching the attributes of `generation_config` will override them. If `generation_config` is not provided, the default will be used, which had the following loading priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit [GenerationConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig)’s default values, whose documentation should be checked to parameterize generation.
* **logits\_processor** (`LogitsProcessorList`, _optional_) — Custom logits processors that complement the default logits processors built from arguments and generation config. If a logit processor is passed that is already created with the arguments or a generation config an error is thrown. This feature is intended for advanced users.
* **stopping\_criteria** (`StoppingCriteriaList`, _optional_) — Custom stopping criteria that complement the default stopping criteria built from arguments and a generation config. If a stopping criteria is passed that is already created with the arguments or a generation config an error is thrown. This feature is intended for advanced users.
* **prefix\_allowed\_tokens\_fn** (`Callable[[int, torch.Tensor], List[int]]`, _optional_) — If provided, this function constraints the beam search to allowed tokens only at each step. If not provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful for constrained generation conditioned on the prefix, as described in [Autoregressive Entity Retrieval](https://arxiv.org/abs/2010.00904).
* **synced\_gpus** (`bool`, _optional_) — Whether to continue running the while loop until max\_length. Unless overridden this flag will be set to `True` under DeepSpeed ZeRO Stage 3 multiple GPUs environment to avoid hanging if one GPU finished generating before other GPUs. Otherwise it’ll be set to `False`.
* **assistant\_model** (`PreTrainedModel`, _optional_) — An assistant model that can be used to accelerate generation. The assistant model must have the exact same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistent model is much faster than running generation with the model you’re calling generate from. As such, the assistant model should be much smaller.
* **streamer** (`BaseStreamer`, _optional_) — Streamer object that will be used to stream the generated sequences. Generated tokens are passed through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
* **negative\_prompt\_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, _optional_) — The negative prompt needed for some processors such as CFG. The batch size must match the input batch size. This is an experimental feature, subject to breaking API changes in future versions.
* **negative\_prompt\_attention\_mask** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, _optional_) — Attention\_mask for `negative_prompt_ids`.
* **kwargs** (`Dict[str, Any]`, _optional_) — Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with _decoder\__.

Returns

[ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) or `torch.LongTensor`

A [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) (if `return_dict_in_generate=True` or when `config.return_dict_in_generate=True`) or a `torch.FloatTensor`.

If the model is _not_ an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) types are:

* [GreedySearchDecoderOnlyOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.GreedySearchDecoderOnlyOutput),
* [SampleDecoderOnlyOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.SampleDecoderOnlyOutput),
* [BeamSearchDecoderOnlyOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.BeamSearchDecoderOnlyOutput),
* [BeamSampleDecoderOnlyOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.BeamSampleDecoderOnlyOutput)

If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) types are:

* [GreedySearchEncoderDecoderOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.GreedySearchEncoderDecoderOutput),
* [SampleEncoderDecoderOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.SampleEncoderDecoderOutput),
* [BeamSearchEncoderDecoderOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.BeamSearchEncoderDecoderOutput),
* [BeamSampleEncoderDecoderOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.BeamSampleEncoderDecoderOutput)

Generates sequences of token ids for models with a language modeling head.

Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the model’s default generation configuration. You can override any `generation_config` by passing the corresponding parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.

For an overview of generation strategies and code examples, check out the [following guide](https://huggingface.co/docs/transformers/generation_strategies).

**compute\_transition\_scores**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/utils.py#L1058)

( sequences: Tensorscores: typing.Tuple\[torch.Tensor]beam\_indices: typing.Optional\[torch.Tensor] = Nonenormalize\_logits: bool = False ) → `torch.Tensor`

Parameters

* **sequences** (`torch.LongTensor`) — The generated sequences. The second dimension (sequence\_length) is either equal to `max_length` or shorter if all batches finished early due to the `eos_token_id`.
* **scores** (`tuple(torch.FloatTensor)`) — Transition scores for each vocabulary token at each generation step. Beam transition scores consisting of log probabilities of tokens conditioned on log softmax of previously generated tokens Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token), with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
* **beam\_indices** (`torch.LongTensor`, _optional_) — Beam indices of generated token id at each generation step. `torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at generate-time.
* **normalize\_logits** (`bool`, _optional_, defaults to `False`) — Whether to normalize the logits (which, for legacy reasons, may be unnormalized).

Returns

`torch.Tensor`

A `torch.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)` containing the transition scores (logits)

Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was used). This is a convenient method to quicky obtain the scores of the selected tokens at generation time.



Examples:

Copied

```
>>> from transformers import GPT2Tokenizer, AutoModelForCausalLM
>>> import numpy as np

>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> model = AutoModelForCausalLM.from_pretrained("gpt2")
>>> tokenizer.pad_token_id = tokenizer.eos_token_id
>>> inputs = tokenizer(["Today is"], return_tensors="pt")

>>> # Example 1: Print the scores for each token generated with Greedy Search
>>> outputs = model.generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)
>>> transition_scores = model.compute_transition_scores(
...     outputs.sequences, outputs.scores, normalize_logits=True
... )
>>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for
>>> # encoder-decoder models, like BART or T5.
>>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]
>>> generated_tokens = outputs.sequences[:, input_length:]
>>> for tok, score in zip(generated_tokens[0], transition_scores[0]):
...     # | token | token string | logits | probability
...     print(f"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}")
|   262 |  the     | -1.414 | 24.33%
|  1110 |  day     | -2.609 | 7.36%
|   618 |  when    | -2.010 | 13.40%
|   356 |  we      | -1.859 | 15.58%
|   460 |  can     | -2.508 | 8.14%

>>> # Example 2: Reconstruct the sequence scores from Beam Search
>>> outputs = model.generate(
...     **inputs,
...     max_new_tokens=5,
...     num_beams=4,
...     num_return_sequences=4,
...     return_dict_in_generate=True,
...     output_scores=True,
... )
>>> transition_scores = model.compute_transition_scores(
...     outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False
... )
>>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.
>>> # Tip: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the
>>> # use case, you might want to recompute it with `normalize_logits=True`.
>>> output_length = input_length + np.sum(transition_scores.numpy() < 0, axis=1)
>>> length_penalty = model.generation_config.length_penalty
>>> reconstructed_scores = transition_scores.sum(axis=1) / (output_length**length_penalty)
>>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))
True
```

**greedy\_search**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/utils.py#L2286)

( input\_ids: LongTensorlogits\_processor: typing.Optional\[transformers.generation.logits\_process.LogitsProcessorList] = Nonestopping\_criteria: typing.Optional\[transformers.generation.stopping\_criteria.StoppingCriteriaList] = Nonemax\_length: typing.Optional\[int] = Nonepad\_token\_id: typing.Optional\[int] = Noneeos\_token\_id: typing.Union\[int, typing.List\[int], NoneType] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Noneoutput\_scores: typing.Optional\[bool] = Nonereturn\_dict\_in\_generate: typing.Optional\[bool] = Nonesynced\_gpus: bool = Falsestreamer: typing.Optional\[ForwardRef('BaseStreamer')] = None\*\*model\_kwargs )

Parameters

* **input\_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`) — The sequence used as a prompt for the generation.
* **logits\_processor** (`LogitsProcessorList`, _optional_) — An instance of [LogitsProcessorList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessorList). List of instances of class derived from [LogitsProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessor) used to modify the prediction scores of the language modeling head applied at each generation step.
* **stopping\_criteria** (`StoppingCriteriaList`, _optional_) — An instance of [StoppingCriteriaList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteriaList). List of instances of class derived from [StoppingCriteria](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteria) used to tell if the generation loop should stop.
* **max\_length** (`int`, _optional_, defaults to 20) — **DEPRECATED**. Use `logits_processor` or `stopping_criteria` directly to cap the number of generated tokens. The maximum length of the sequence to be generated.
* **pad\_token\_id** (`int`, _optional_) — The id of the _padding_ token.
* **eos\_token\_id** (`Union[int, List[int]]`, _optional_) — The id of the _end-of-sequence_ token. Optionally, use a list to set multiple _end-of-sequence_ tokens.
* **output\_attentions** (`bool`, _optional_, defaults to `False`) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
* **output\_hidden\_states** (`bool`, _optional_, defaults to `False`) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
* **output\_scores** (`bool`, _optional_, defaults to `False`) — Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
* **return\_dict\_in\_generate** (`bool`, _optional_, defaults to `False`) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.
* **synced\_gpus** (`bool`, _optional_, defaults to `False`) — Whether to continue running the while loop until max\_length (needed for ZeRO stage 3)
* **streamer** (`BaseStreamer`, _optional_) — Streamer object that will be used to stream the generated sequences. Generated tokens are passed through `streamer.put(token_ids)` and the streamer is responsible for any further processing. model\_kwargs — Additional model specific keyword arguments will be forwarded to the `forward` function of the model. If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

Generates sequences of token ids for models with a language modeling head using **greedy decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

In most cases, you do not need to call [greedy\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.greedy_search) directly. Use generate() instead. For an overview of generation strategies and code examples, check the [following guide](https://huggingface.co/docs/transformers/generation_strategies).



Examples:

Copied

```
>>> from transformers import (
...     AutoTokenizer,
...     AutoModelForCausalLM,
...     LogitsProcessorList,
...     MinLengthLogitsProcessor,
...     StoppingCriteriaList,
...     MaxLengthCriteria,
... )

>>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
>>> model = AutoModelForCausalLM.from_pretrained("gpt2")

>>> # set pad_token_id to eos_token_id because GPT2 does not have a PAD token
>>> model.generation_config.pad_token_id = model.generation_config.eos_token_id

>>> input_prompt = "It might be possible to"
>>> input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids

>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [
...         MinLengthLogitsProcessor(10, eos_token_id=model.generation_config.eos_token_id),
...     ]
... )
>>> stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length=20)])

>>> outputs = model.greedy_search(
...     input_ids, logits_processor=logits_processor, stopping_criteria=stopping_criteria
... )

>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
["It might be possible to get a better understanding of the nature of the problem, but it's not"]
```

**sample**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/utils.py#L2545)

( input\_ids: LongTensorlogits\_processor: typing.Optional\[transformers.generation.logits\_process.LogitsProcessorList] = Nonestopping\_criteria: typing.Optional\[transformers.generation.stopping\_criteria.StoppingCriteriaList] = Nonelogits\_warper: typing.Optional\[transformers.generation.logits\_process.LogitsProcessorList] = Nonemax\_length: typing.Optional\[int] = Nonepad\_token\_id: typing.Optional\[int] = Noneeos\_token\_id: typing.Union\[int, typing.List\[int], NoneType] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Noneoutput\_scores: typing.Optional\[bool] = Nonereturn\_dict\_in\_generate: typing.Optional\[bool] = Nonesynced\_gpus: bool = Falsestreamer: typing.Optional\[ForwardRef('BaseStreamer')] = None\*\*model\_kwargs ) → [SampleDecoderOnlyOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.SampleDecoderOnlyOutput), [SampleEncoderDecoderOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.SampleEncoderDecoderOutput) or `torch.LongTensor`

Parameters

* **input\_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`) — The sequence used as a prompt for the generation.
* **logits\_processor** (`LogitsProcessorList`, _optional_) — An instance of [LogitsProcessorList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessorList). List of instances of class derived from [LogitsProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessor) used to modify the prediction scores of the language modeling head applied at each generation step.
* **stopping\_criteria** (`StoppingCriteriaList`, _optional_) — An instance of [StoppingCriteriaList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteriaList). List of instances of class derived from [StoppingCriteria](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteria) used to tell if the generation loop should stop.
* **logits\_warper** (`LogitsProcessorList`, _optional_) — An instance of [LogitsProcessorList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessorList). List of instances of class derived from [LogitsWarper](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsWarper) used to warp the prediction score distribution of the language modeling head applied before multinomial sampling at each generation step.
* **max\_length** (`int`, _optional_, defaults to 20) — **DEPRECATED**. Use `logits_processor` or `stopping_criteria` directly to cap the number of generated tokens. The maximum length of the sequence to be generated.
* **pad\_token\_id** (`int`, _optional_) — The id of the _padding_ token.
* **eos\_token\_id** (`Union[int, List[int]]`, _optional_) — The id of the _end-of-sequence_ token. Optionally, use a list to set multiple _end-of-sequence_ tokens.
* **output\_attentions** (`bool`, _optional_, defaults to `False`) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
* **output\_hidden\_states** (`bool`, _optional_, defaults to `False`) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
* **output\_scores** (`bool`, _optional_, defaults to `False`) — Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
* **return\_dict\_in\_generate** (`bool`, _optional_, defaults to `False`) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.
* **synced\_gpus** (`bool`, _optional_, defaults to `False`) — Whether to continue running the while loop until max\_length (needed for ZeRO stage 3)
* **streamer** (`BaseStreamer`, _optional_) — Streamer object that will be used to stream the generated sequences. Generated tokens are passed through `streamer.put(token_ids)` and the streamer is responsible for any further processing. model\_kwargs — Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

Returns

[SampleDecoderOnlyOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.SampleDecoderOnlyOutput), [SampleEncoderDecoderOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.SampleEncoderDecoderOutput) or `torch.LongTensor`

A `torch.LongTensor` containing the generated tokens (default behaviour) or a [SampleDecoderOnlyOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.SampleDecoderOnlyOutput) if `model.config.is_encoder_decoder=False` and `return_dict_in_generate=True` or a [SampleEncoderDecoderOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.SampleEncoderDecoderOutput) if `model.config.is_encoder_decoder=True`.

Generates sequences of token ids for models with a language modeling head using **multinomial sampling** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

In most cases, you do not need to call [sample()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.sample) directly. Use generate() instead. For an overview of generation strategies and code examples, check the [following guide](https://huggingface.co/docs/transformers/generation_strategies).



Examples:

Copied

```
>>> from transformers import (
...     AutoTokenizer,
...     AutoModelForCausalLM,
...     LogitsProcessorList,
...     MinLengthLogitsProcessor,
...     TopKLogitsWarper,
...     TemperatureLogitsWarper,
...     StoppingCriteriaList,
...     MaxLengthCriteria,
... )
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
>>> model = AutoModelForCausalLM.from_pretrained("gpt2")

>>> # set pad_token_id to eos_token_id because GPT2 does not have a EOS token
>>> model.config.pad_token_id = model.config.eos_token_id
>>> model.generation_config.pad_token_id = model.config.eos_token_id

>>> input_prompt = "Today is a beautiful day, and"
>>> input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids

>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [
...         MinLengthLogitsProcessor(15, eos_token_id=model.generation_config.eos_token_id),
...     ]
... )
>>> # instantiate logits processors
>>> logits_warper = LogitsProcessorList(
...     [
...         TopKLogitsWarper(50),
...         TemperatureLogitsWarper(0.7),
...     ]
... )

>>> stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length=20)])

>>> torch.manual_seed(0)
>>> outputs = model.sample(
...     input_ids,
...     logits_processor=logits_processor,
...     logits_warper=logits_warper,
...     stopping_criteria=stopping_criteria,
... )

>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
['Today is a beautiful day, and we must do everything possible to make it a day of celebration.']
```

**beam\_search**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/utils.py#L2827)

( input\_ids: LongTensorbeam\_scorer: BeamScorerlogits\_processor: typing.Optional\[transformers.generation.logits\_process.LogitsProcessorList] = Nonestopping\_criteria: typing.Optional\[transformers.generation.stopping\_criteria.StoppingCriteriaList] = Nonemax\_length: typing.Optional\[int] = Nonepad\_token\_id: typing.Optional\[int] = Noneeos\_token\_id: typing.Union\[int, typing.List\[int], NoneType] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Noneoutput\_scores: typing.Optional\[bool] = Nonereturn\_dict\_in\_generate: typing.Optional\[bool] = Nonesynced\_gpus: bool = False\*\*model\_kwargs )

Parameters

* **input\_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`) — The sequence used as a prompt for the generation.
* **beam\_scorer** (`BeamScorer`) — An derived instance of [BeamScorer](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.BeamScorer) that defines how beam hypotheses are constructed, stored and sorted during generation. For more information, the documentation of [BeamScorer](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.BeamScorer) should be read.
* **logits\_processor** (`LogitsProcessorList`, _optional_) — An instance of [LogitsProcessorList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessorList). List of instances of class derived from [LogitsProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessor) used to modify the prediction scores of the language modeling head applied at each generation step.
* **stopping\_criteria** (`StoppingCriteriaList`, _optional_) — An instance of [StoppingCriteriaList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteriaList). List of instances of class derived from [StoppingCriteria](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteria) used to tell if the generation loop should stop.
* **max\_length** (`int`, _optional_, defaults to 20) — **DEPRECATED**. Use `logits_processor` or `stopping_criteria` directly to cap the number of generated tokens. The maximum length of the sequence to be generated.
* **pad\_token\_id** (`int`, _optional_) — The id of the _padding_ token.
* **eos\_token\_id** (`Union[int, List[int]]`, _optional_) — The id of the _end-of-sequence_ token. Optionally, use a list to set multiple _end-of-sequence_ tokens.
* **output\_attentions** (`bool`, _optional_, defaults to `False`) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
* **output\_hidden\_states** (`bool`, _optional_, defaults to `False`) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
* **output\_scores** (`bool`, _optional_, defaults to `False`) — Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
* **return\_dict\_in\_generate** (`bool`, _optional_, defaults to `False`) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.
* **synced\_gpus** (`bool`, _optional_, defaults to `False`) — Whether to continue running the while loop until max\_length (needed for ZeRO stage 3) model\_kwargs — Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

Generates sequences of token ids for models with a language modeling head using **beam search decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

In most cases, you do not need to call [beam\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.beam_search) directly. Use generate() instead. For an overview of generation strategies and code examples, check the [following guide](https://huggingface.co/docs/transformers/generation_strategies).



Examples:

Copied

```
>>> from transformers import (
...     AutoTokenizer,
...     AutoModelForSeq2SeqLM,
...     LogitsProcessorList,
...     MinLengthLogitsProcessor,
...     BeamSearchScorer,
... )
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")

>>> encoder_input_str = "translate English to German: How old are you?"
>>> encoder_input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids


>>> # lets run beam search using 3 beams
>>> num_beams = 3
>>> # define decoder start token ids
>>> input_ids = torch.ones((num_beams, 1), device=model.device, dtype=torch.long)
>>> input_ids = input_ids * model.config.decoder_start_token_id

>>> # add encoder_outputs to model keyword arguments
>>> model_kwargs = {
...     "encoder_outputs": model.get_encoder()(
...         encoder_input_ids.repeat_interleave(num_beams, dim=0), return_dict=True
...     )
... }

>>> # instantiate beam scorer
>>> beam_scorer = BeamSearchScorer(
...     batch_size=1,
...     num_beams=num_beams,
...     device=model.device,
... )

>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [
...         MinLengthLogitsProcessor(5, eos_token_id=model.config.eos_token_id),
...     ]
... )

>>> outputs = model.beam_search(input_ids, beam_scorer, logits_processor=logits_processor, **model_kwargs)

>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
['Wie alt bist du?']
```

**beam\_sample**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/utils.py#L3150)

( input\_ids: LongTensorbeam\_scorer: BeamScorerlogits\_processor: typing.Optional\[transformers.generation.logits\_process.LogitsProcessorList] = Nonestopping\_criteria: typing.Optional\[transformers.generation.stopping\_criteria.StoppingCriteriaList] = Nonelogits\_warper: typing.Optional\[transformers.generation.logits\_process.LogitsProcessorList] = Nonemax\_length: typing.Optional\[int] = Nonepad\_token\_id: typing.Optional\[int] = Noneeos\_token\_id: typing.Union\[int, typing.List\[int], NoneType] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Noneoutput\_scores: typing.Optional\[bool] = Nonereturn\_dict\_in\_generate: typing.Optional\[bool] = Nonesynced\_gpus: bool = False\*\*model\_kwargs )

Parameters

* **input\_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`) — The sequence used as a prompt for the generation.
* **beam\_scorer** (`BeamScorer`) — A derived instance of [BeamScorer](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.BeamScorer) that defines how beam hypotheses are constructed, stored and sorted during generation. For more information, the documentation of [BeamScorer](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.BeamScorer) should be read.
* **logits\_processor** (`LogitsProcessorList`, _optional_) — An instance of [LogitsProcessorList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessorList). List of instances of class derived from [LogitsProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessor) used to modify the prediction scores of the language modeling head applied at each generation step.
* **stopping\_criteria** (`StoppingCriteriaList`, _optional_) — An instance of [StoppingCriteriaList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteriaList). List of instances of class derived from [StoppingCriteria](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteria) used to tell if the generation loop should stop.
* **logits\_warper** (`LogitsProcessorList`, _optional_) — An instance of [LogitsProcessorList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessorList). List of instances of class derived from [LogitsWarper](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsWarper) used to warp the prediction score distribution of the language modeling head applied before multinomial sampling at each generation step.
* **max\_length** (`int`, _optional_, defaults to 20) — **DEPRECATED**. Use `logits_processor` or `stopping_criteria` directly to cap the number of generated tokens. The maximum length of the sequence to be generated.
* **pad\_token\_id** (`int`, _optional_) — The id of the _padding_ token.
* **eos\_token\_id** (`Union[int, List[int]]`, _optional_) — The id of the _end-of-sequence_ token. Optionally, use a list to set multiple _end-of-sequence_ tokens.
* **output\_attentions** (`bool`, _optional_, defaults to `False`) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
* **output\_hidden\_states** (`bool`, _optional_, defaults to `False`) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
* **output\_scores** (`bool`, _optional_, defaults to `False`) — Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
* **return\_dict\_in\_generate** (`bool`, _optional_, defaults to `False`) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.
* **synced\_gpus** (`bool`, _optional_, defaults to `False`) — Whether to continue running the while loop until max\_length (needed for ZeRO stage 3) model\_kwargs — Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

Generates sequences of token ids for models with a language modeling head using **beam search multinomial sampling** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

In most cases, you do not need to call [beam\_sample()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.beam_sample) directly. Use generate() instead. For an overview of generation strategies and code examples, check the [following guide](https://huggingface.co/docs/transformers/generation_strategies).



Examples:

Copied

```
>>> from transformers import (
...     AutoTokenizer,
...     AutoModelForSeq2SeqLM,
...     LogitsProcessorList,
...     MinLengthLogitsProcessor,
...     TopKLogitsWarper,
...     TemperatureLogitsWarper,
...     BeamSearchScorer,
... )
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")

>>> encoder_input_str = "translate English to German: How old are you?"
>>> encoder_input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids

>>> # lets run beam search using 3 beams
>>> num_beams = 3
>>> # define decoder start token ids
>>> input_ids = torch.ones((num_beams, 1), device=model.device, dtype=torch.long)
>>> input_ids = input_ids * model.config.decoder_start_token_id

>>> # add encoder_outputs to model keyword arguments
>>> model_kwargs = {
...     "encoder_outputs": model.get_encoder()(
...         encoder_input_ids.repeat_interleave(num_beams, dim=0), return_dict=True
...     )
... }

>>> # instantiate beam scorer
>>> beam_scorer = BeamSearchScorer(
...     batch_size=1,
...     max_length=model.config.max_length,
...     num_beams=num_beams,
...     device=model.device,
... )

>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [MinLengthLogitsProcessor(5, eos_token_id=model.config.eos_token_id)]
... )
>>> # instantiate logits processors
>>> logits_warper = LogitsProcessorList(
...     [
...         TopKLogitsWarper(50),
...         TemperatureLogitsWarper(0.7),
...     ]
... )

>>> outputs = model.beam_sample(
...     input_ids, beam_scorer, logits_processor=logits_processor, logits_warper=logits_warper, **model_kwargs
... )

>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
['Wie alt bist du?']
```

**contrastive\_search**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/utils.py#L1842)

( input\_ids: LongTensortop\_k: typing.Optional\[int] = 1penalty\_alpha: typing.Optional\[float] = 0logits\_processor: typing.Optional\[transformers.generation.logits\_process.LogitsProcessorList] = Nonelogits\_warper: typing.Optional\[transformers.generation.logits\_process.LogitsProcessorList] = Nonestopping\_criteria: typing.Optional\[transformers.generation.stopping\_criteria.StoppingCriteriaList] = Nonepad\_token\_id: typing.Optional\[int] = Noneeos\_token\_id: typing.Union\[int, typing.List\[int], NoneType] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Noneoutput\_scores: typing.Optional\[bool] = Nonereturn\_dict\_in\_generate: typing.Optional\[bool] = Nonesynced\_gpus: bool = Falsestreamer: typing.Optional\[ForwardRef('BaseStreamer')] = Nonesequential: typing.Optional\[bool] = None\*\*model\_kwargs )

Parameters

* **input\_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`) — The sequence used as a prompt for the generation.
* **top\_k** (`int`, _optional_, defaults to 1) — The size of the candidate set that is used to re-rank for contrastive search
* **penalty\_alpha** (`float`, _optional_, defaults to 0) — The degeneration penalty for contrastive search; activate when it is larger than 0
* **logits\_processor** (`LogitsProcessorList`, _optional_) — An instance of [LogitsProcessorList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessorList). List of instances of class derived from [LogitsProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessor) used to modify the prediction scores of the language modeling head applied at each generation step.
* **logits\_warper** (`LogitsProcessorList`, _optional_) — An instance of [LogitsProcessorList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessorList). List of instances of class derived from [LogitsWarper](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsWarper) used to warp the prediction score distribution of the language modeling head applied before multinomial sampling at each generation step.
* **stopping\_criteria** (`StoppingCriteriaList`, _optional_) — An instance of [StoppingCriteriaList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteriaList). List of instances of class derived from [StoppingCriteria](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteria) used to tell if the generation loop should stop.
* **pad\_token\_id** (`int`, _optional_) — The id of the _padding_ token.
* **eos\_token\_id** (`Union[int, List[int]]`, _optional_) — The id of the _end-of-sequence_ token. Optionally, use a list to set multiple _end-of-sequence_ tokens.
* **output\_attentions** (`bool`, _optional_, defaults to `False`) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
* **output\_hidden\_states** (`bool`, _optional_, defaults to `False`) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
* **output\_scores** (`bool`, _optional_, defaults to `False`) — Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
* **return\_dict\_in\_generate** (`bool`, _optional_, defaults to `False`) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.
* **synced\_gpus** (`bool`, _optional_, defaults to `False`) — Whether to continue running the while loop until max\_length (needed for ZeRO stage 3)
* **streamer** (`BaseStreamer`, _optional_) — Streamer object that will be used to stream the generated sequences. Generated tokens are passed through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
* **sequential** (`bool`, _optional_) — Switches topk hidden state computation from parallel to sequential to reduce memory if True. model\_kwargs — Additional model specific keyword arguments will be forwarded to the `forward` function of the model. If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

Generates sequences of token ids for models with a language modeling head using **contrastive search** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

In most cases, you do not need to call [contrastive\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.contrastive_search) directly. Use generate() instead. For an overview of generation strategies and code examples, check the [following guide](https://huggingface.co/docs/transformers/generation_strategies).



Examples:

Copied

```
>>> from transformers import (
...     AutoTokenizer,
...     AutoModelForCausalLM,
...     StoppingCriteriaList,
...     MaxLengthCriteria,
... )

>>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m")
>>> model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
>>> # set pad_token_id to eos_token_id because OPT does not have a PAD token
>>> model.config.pad_token_id = model.config.eos_token_id
>>> input_prompt = "DeepMind Company is"
>>> input_ids = tokenizer(input_prompt, return_tensors="pt")
>>> stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length=64)])
>>> outputs = model.contrastive_search(
...     **input_ids, penalty_alpha=0.6, top_k=4, stopping_criteria=stopping_criteria
... )
>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
['DeepMind Company is a company that focuses on the development and commercialization of artificial intelligence (AI). DeepMind’s mission is to help people understand and solve problems that are difficult to solve in the world today.\n\nIn this post, we talk about the benefits of deep learning in business and how it']
```

**group\_beam\_search**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/utils.py#L3482)

( input\_ids: LongTensorbeam\_scorer: BeamScorerlogits\_processor: typing.Optional\[transformers.generation.logits\_process.LogitsProcessorList] = Nonestopping\_criteria: typing.Optional\[transformers.generation.stopping\_criteria.StoppingCriteriaList] = Nonemax\_length: typing.Optional\[int] = Nonepad\_token\_id: typing.Optional\[int] = Noneeos\_token\_id: typing.Union\[int, typing.List\[int], NoneType] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Noneoutput\_scores: typing.Optional\[bool] = Nonereturn\_dict\_in\_generate: typing.Optional\[bool] = Nonesynced\_gpus: bool = False\*\*model\_kwargs )

Parameters

* **input\_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`) — The sequence used as a prompt for the generation.
* **beam\_scorer** (`BeamScorer`) — An derived instance of [BeamScorer](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.BeamScorer) that defines how beam hypotheses are constructed, stored and sorted during generation. For more information, the documentation of [BeamScorer](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.BeamScorer) should be read.
* **logits\_processor** (`LogitsProcessorList`, _optional_) — An instance of [LogitsProcessorList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessorList). List of instances of class derived from [LogitsProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessor) used to modify the prediction scores of the language modeling head applied at each generation step.
* **stopping\_criteria** (`StoppingCriteriaList`, _optional_) — An instance of [StoppingCriteriaList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteriaList). List of instances of class derived from [StoppingCriteria](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteria) used to tell if the generation loop should stop.
* **max\_length** (`int`, _optional_, defaults to 20) — **DEPRECATED**. Use `logits_processor` or `stopping_criteria` directly to cap the number of generated tokens. The maximum length of the sequence to be generated.
* **pad\_token\_id** (`int`, _optional_) — The id of the _padding_ token.
* **eos\_token\_id** (`Union[int, List[int]]`, _optional_) — The id of the _end-of-sequence_ token. Optionally, use a list to set multiple _end-of-sequence_ tokens.
* **output\_attentions** (`bool`, _optional_, defaults to `False`) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
* **output\_hidden\_states** (`bool`, _optional_, defaults to `False`) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
* **output\_scores** (`bool`, _optional_, defaults to `False`) — Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
* **return\_dict\_in\_generate** (`bool`, _optional_, defaults to `False`) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.
*   **synced\_gpus** (`bool`, _optional_, defaults to `False`) — Whether to continue running the while loop until max\_length (needed for ZeRO stage 3)

    model\_kwargs — Additional model specific kwargs that will be forwarded to the `forward` function of the model. If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

Generates sequences of token ids for models with a language modeling head using **diverse beam search decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

In most cases, you do not need to call [group\_beam\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.group_beam_search) directly. Use generate() instead. For an overview of generation strategies and code examples, check the [following guide](https://huggingface.co/docs/transformers/generation_strategies).



Examples:

Copied

```
>>> from transformers import (
...     AutoTokenizer,
...     AutoModelForSeq2SeqLM,
...     LogitsProcessorList,
...     MinLengthLogitsProcessor,
...     HammingDiversityLogitsProcessor,
...     BeamSearchScorer,
... )
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")

>>> encoder_input_str = "translate English to German: How old are you?"
>>> encoder_input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids


>>> # lets run diverse beam search using 6 beams
>>> num_beams = 6
>>> # define decoder start token ids
>>> input_ids = torch.ones((num_beams, 1), device=model.device, dtype=torch.long)
>>> input_ids = input_ids * model.config.decoder_start_token_id

>>> # add encoder_outputs to model keyword arguments
>>> model_kwargs = {
...     "encoder_outputs": model.get_encoder()(
...         encoder_input_ids.repeat_interleave(num_beams, dim=0), return_dict=True
...     )
... }

>>> # instantiate beam scorer
>>> beam_scorer = BeamSearchScorer(
...     batch_size=1,
...     max_length=model.config.max_length,
...     num_beams=num_beams,
...     device=model.device,
...     num_beam_groups=3,
... )

>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [
...         HammingDiversityLogitsProcessor(5.5, num_beams=6, num_beam_groups=3),
...         MinLengthLogitsProcessor(5, eos_token_id=model.config.eos_token_id),
...     ]
... )

>>> outputs = model.group_beam_search(
...     input_ids, beam_scorer, logits_processor=logits_processor, **model_kwargs
... )

>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
['Wie alt bist du?']
```

**constrained\_beam\_search**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/utils.py#L3861)

( input\_ids: LongTensorconstrained\_beam\_scorer: ConstrainedBeamSearchScorerlogits\_processor: typing.Optional\[transformers.generation.logits\_process.LogitsProcessorList] = Nonestopping\_criteria: typing.Optional\[transformers.generation.stopping\_criteria.StoppingCriteriaList] = Nonemax\_length: typing.Optional\[int] = Nonepad\_token\_id: typing.Optional\[int] = Noneeos\_token\_id: typing.Union\[int, typing.List\[int], NoneType] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Noneoutput\_scores: typing.Optional\[bool] = Nonereturn\_dict\_in\_generate: typing.Optional\[bool] = Nonesynced\_gpus: typing.Optional\[bool] = None\*\*model\_kwargs )

Parameters

* **input\_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`) — The sequence used as a prompt for the generation.
* **constrained\_beam\_scorer** (`ConstrainedBeamSearchScorer`) — A derived instance of [BeamScorer](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.BeamScorer) that defines how beam hypotheses are constructed, stored and sorted during generation, while satisfying a list of positive constraints. For more information, the documentation of [ConstrainedBeamSearchScorer](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.ConstrainedBeamSearchScorer) should be read.
* **logits\_processor** (`LogitsProcessorList`, _optional_) — An instance of [LogitsProcessorList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessorList). List of instances of class derived from [LogitsProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessor) used to modify the prediction scores of the language modeling head applied at each generation step.
* **stopping\_criteria** (`StoppingCriteriaList`, _optional_) — An instance of [StoppingCriteriaList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteriaList). List of instances of class derived from [StoppingCriteria](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.StoppingCriteria) used to tell if the generation loop should stop.
* **logits\_warper** (`LogitsProcessorList`, _optional_) — An instance of [LogitsProcessorList](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsProcessorList). List of instances of class derived from [LogitsWarper](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.LogitsWarper) used to warp the prediction score distribution of the language modeling head applied before multinomial sampling at each generation step.
* **max\_length** (`int`, _optional_, defaults to 20) — **DEPRECATED**. Use `logits_processor` or `stopping_criteria` directly to cap the number of generated tokens. The maximum length of the sequence to be generated.
* **pad\_token\_id** (`int`, _optional_) — The id of the _padding_ token.
* **eos\_token\_id** (`Union[int, List[int]]`, _optional_) — The id of the _end-of-sequence_ token. Optionally, use a list to set multiple _end-of-sequence_ tokens.
* **output\_attentions** (`bool`, _optional_, defaults to `False`) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
* **output\_hidden\_states** (`bool`, _optional_, defaults to `False`) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
* **output\_scores** (`bool`, _optional_, defaults to `False`) — Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
* **return\_dict\_in\_generate** (`bool`, _optional_, defaults to `False`) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.
* **synced\_gpus** (`bool`, _optional_, defaults to `False`) — Whether to continue running the while loop until max\_length (needed for ZeRO stage 3) model\_kwargs — Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

Generates sequences of token ids for models with a language modeling head using **constrained beam search decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

In most cases, you do not need to call [constrained\_beam\_search()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.constrained_beam_search) directly. Use generate() instead. For an overview of generation strategies and code examples, check the [following guide](https://huggingface.co/docs/transformers/generation_strategies).



Examples:

Copied

```
>>> from transformers import (
...     AutoTokenizer,
...     AutoModelForSeq2SeqLM,
...     LogitsProcessorList,
...     MinLengthLogitsProcessor,
...     ConstrainedBeamSearchScorer,
...     PhrasalConstraint,
... )
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")

>>> encoder_input_str = "translate English to German: How old are you?"
>>> encoder_input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids


>>> # lets run beam search using 3 beams
>>> num_beams = 3
>>> # define decoder start token ids
>>> input_ids = torch.ones((num_beams, 1), device=model.device, dtype=torch.long)
>>> input_ids = input_ids * model.config.decoder_start_token_id

>>> # add encoder_outputs to model keyword arguments
>>> model_kwargs = {
...     "encoder_outputs": model.get_encoder()(
...         encoder_input_ids.repeat_interleave(num_beams, dim=0), return_dict=True
...     )
... }

>>> constraint_str = "Sie"
>>> constraint_token_ids = tokenizer.encode(constraint_str)[:-1]  # slice to remove eos token
>>> constraints = [PhrasalConstraint(token_ids=constraint_token_ids)]


>>> # instantiate beam scorer
>>> beam_scorer = ConstrainedBeamSearchScorer(
...     batch_size=1, num_beams=num_beams, device=model.device, constraints=constraints
... )

>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [
...         MinLengthLogitsProcessor(5, eos_token_id=model.config.eos_token_id),
...     ]
... )

>>> outputs = model.constrained_beam_search(
...     input_ids, beam_scorer, constraints=constraints, logits_processor=logits_processor, **model_kwargs
... )

>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
['Wie alt sind Sie?']
```

### TFGenerationMixin

#### class transformers.TFGenerationMixin

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/tf_utils.py#L444)

( )

A class containing all of the functions supporting generation, to be used as a mixin in [TFPreTrainedModel](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.TFPreTrainedModel).

The class exposes [generate()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.TFGenerationMixin.generate), which can be used for:

* _greedy decoding_ by calling `greedy_search()` if `num_beams=1` and `do_sample=False`
* _contrastive search_ by calling `contrastive_search()` if `penalty_alpha>0` and `top_k>1`
* _multinomial sampling_ by calling `sample()` if `num_beams=1` and `do_sample=True`
* _beam-search decoding_ by calling `beam_search()` if `num_beams>1`

You do not need to call any of the above methods directly. Pass custom parameter values to ‘generate’ instead. To learn more about decoding strategies refer to the [text generation strategies guide](https://huggingface.co/docs/transformers/generation_strategies).

**generate**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/tf_utils.py#L645)

( inputs: typing.Optional\[tensorflow.python.framework.ops.Tensor] = Nonegeneration\_config: typing.Optional\[transformers.generation.configuration\_utils.GenerationConfig] = Nonelogits\_processor: typing.Optional\[transformers.generation.tf\_logits\_process.TFLogitsProcessorList] = Noneseed = None\*\*kwargs ) → [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) or `tf.Tensor`

Parameters

* **inputs** (`tf.Tensor` of varying shape depending on the modality, _optional_) — The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs` should of in the format of `input_ids`. For encoder-decoder models _inputs_ can represent any of `input_ids`, `input_values`, `input_features`, or `pixel_values`.
* **generation\_config** (`~generation.GenerationConfig`, _optional_) — The generation configuration to be used as base parametrization for the generation call. `**kwargs` passed to generate matching the attributes of `generation_config` will override them. If `generation_config` is not provided, the default will be used, which had the following loading priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit [GenerationConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig)’s default values, whose documentation should be checked to parameterize generation.
* **logits\_processor** (`LogitsProcessorList`, _optional_) — Custom logits processors that complement the default logits processors built from arguments and generation config. If a logit processor is passed that is already created with the arguments or a generation config an error is thrown. This feature is intended for advanced users.
* **seed** (`List[int]`, _optional_) — Random seed to control sampling, containing two integers, used when `do_sample` is `True`. See the `seed` argument from stateless functions in `tf.random`.
* **kwargs** (`Dict[str, Any]`, _optional_) — Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with _decoder\__.

Returns

[ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) or `tf.Tensor`

A [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) (if `return_dict_in_generate=True` or when `config.return_dict_in_generate=True`) or a `tf.Tensor`.

If the model is _not_ an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) types are:

* [TFGreedySearchDecoderOnlyOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.TFGreedySearchDecoderOnlyOutput),
* [TFSampleDecoderOnlyOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.TFSampleDecoderOnlyOutput),
* [TFBeamSearchDecoderOnlyOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.TFBeamSearchDecoderOnlyOutput),
* [TFBeamSampleDecoderOnlyOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.TFBeamSampleDecoderOnlyOutput)

If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) types are:

* [TFGreedySearchEncoderDecoderOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.TFGreedySearchEncoderDecoderOutput),
* [TFSampleEncoderDecoderOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.TFSampleEncoderDecoderOutput),
* [TFBeamSearchEncoderDecoderOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.TFBeamSearchEncoderDecoderOutput),
* [TFBeamSampleEncoderDecoderOutput](https://huggingface.co/docs/transformers/v4.34.1/en/internal/generation_utils#transformers.generation.TFBeamSampleEncoderDecoderOutput)

Generates sequences of token ids for models with a language modeling head.

Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the model’s default generation configuration. You can override any `generation_config` by passing the corresponding parameters to generate, e.g. `.generate(inputs, num_beams=4, do_sample=True)`.

For an overview of generation strategies and code examples, check out the [following guide](https://huggingface.co/docs/transformers/generation_strategies).

**compute\_transition\_scores**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/tf_utils.py#L477)

( sequences: Tensorscores: typing.Tuple\[tensorflow.python.framework.ops.Tensor]beam\_indices: typing.Optional\[tensorflow.python.framework.ops.Tensor] = Nonenormalize\_logits: bool = False ) → `tf.Tensor`

Parameters

* **sequences** (`tf.Tensor`) — The generated sequences. The second dimension (sequence\_length) is either equal to `max_length` or shorter if all batches finished early due to the `eos_token_id`.
* **scores** (`tuple(tf.Tensor)`) — Transition scores for each vocabulary token at each generation step. Beam transition scores consisting of log probabilities of tokens conditioned on log softmax of previously generated tokens Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each generated token), with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
* **beam\_indices** (`tf.Tensor`, _optional_) — Beam indices of generated token id at each generation step. `tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at generate-time.
* **normalize\_logits** (`bool`, _optional_, defaults to `False`) — Whether to normalize the logits (which, for legacy reasons, may be unnormalized).

Returns

`tf.Tensor`

A `tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)` containing the transition scores (logits)

Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was used). This is a convenient method to quicky obtain the scores of the selected tokens at generation time.



Examples:

Copied

```
>>> from transformers import GPT2Tokenizer, TFAutoModelForCausalLM
>>> import numpy as np

>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> model = TFAutoModelForCausalLM.from_pretrained("gpt2")
>>> tokenizer.pad_token_id = tokenizer.eos_token_id
>>> inputs = tokenizer(["Today is"], return_tensors="tf")

>>> # Example 1: Print the scores for each token generated with Greedy Search
>>> outputs = model.generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)
>>> transition_scores = model.compute_transition_scores(
...     outputs.sequences, outputs.scores, normalize_logits=True
... )
>>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for
>>> # encoder-decoder models, like BART or T5.
>>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]
>>> generated_tokens = outputs.sequences[:, input_length:]
>>> for tok, score in zip(generated_tokens[0], transition_scores[0]):
...     # | token | token string | logits | probability
...     print(f"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}")
|   262 |  the     | -1.413 | 24.33%
|  1110 |  day     | -2.609 | 7.36%
|   618 |  when    | -2.009 | 13.41%
|   356 |  we      | -1.859 | 15.58%
|   460 |  can     | -2.508 | 8.14%

>>> # Example 2: Reconstruct the sequence scores from Beam Search
>>> outputs = model.generate(
...     **inputs,
...     max_new_tokens=5,
...     num_beams=4,
...     num_return_sequences=4,
...     return_dict_in_generate=True,
...     output_scores=True,
... )
>>> transition_scores = model.compute_transition_scores(
...     outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False
... )
>>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.
>>> # Tip: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the
>>> # use case, you might want to recompute it with `normalize_logits=True`.
>>> output_length = input_length + np.sum(transition_scores.numpy() < 0, axis=1)
>>> length_penalty = model.generation_config.length_penalty
>>> reconstructed_scores = np.sum(transition_scores, axis=1) / (output_length**length_penalty)
>>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))
True
```

### FlaxGenerationMixin

#### class transformers.FlaxGenerationMixin

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/flax_utils.py#L129)

( )

A class containing all functions for auto-regressive text generation, to be used as a mixin in [FlaxPreTrainedModel](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.FlaxPreTrainedModel).

The class exposes [generate()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.FlaxGenerationMixin.generate), which can be used for:

* _greedy decoding_ by calling `_greedy_search()` if `num_beams=1` and `do_sample=False`
* _multinomial sampling_ by calling `_sample()` if `num_beams=1` and `do_sample=True`
* _beam-search decoding_ by calling `_beam_search()` if `num_beams>1` and `do_sample=False`

You do not need to call any of the above methods directly. Pass custom parameter values to ‘generate’ instead. To learn more about decoding strategies refer to the [text generation strategies guide](https://huggingface.co/docs/transformers/generation_strategies).

**generate**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/generation/flax_utils.py#L267)

( input\_ids: Arraygeneration\_config: typing.Optional\[transformers.generation.configuration\_utils.GenerationConfig] = Noneprng\_key: typing.Optional\[jax.Array] = Nonetrace: bool = Trueparams: typing.Union\[typing.Dict\[str, jax.Array], NoneType] = Nonelogits\_processor: typing.Optional\[transformers.generation.flax\_logits\_process.FlaxLogitsProcessorList] = None\*\*kwargs )

Parameters

* **input\_ids** (`jnp.ndarray` of shape `(batch_size, sequence_length)`) — The sequence used as a prompt for the generation.
* **generation\_config** (`~generation.GenerationConfig`, _optional_) — The generation configuration to be used as base parametrization for the generation call. `**kwargs` passed to generate matching the attributes of `generation_config` will override them. If `generation_config` is not provided, the default will be used, which had the following loading priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit [GenerationConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationConfig)’s default values, whose documentation should be checked to parameterize generation.
* **trace** (`bool`, _optional_, defaults to `True`) — Whether to trace generation. Setting `trace=False` should only be used for debugging and will lead to a considerably slower runtime.
* **params** (`Dict[str, jnp.ndarray]`, _optional_) — Optionally the model parameters can be passed. Can be useful for parallelized generation.
* **logits\_processor** (`FlaxLogitsProcessorList` , _optional_) — Custom logits processors that complement the default logits processors built from arguments and generation config. If a logit processor is passed that is already created with the arguments or a generation config an error is thrown. This feature is intended for advanced users.
* **kwargs** (`Dict[str, Any]`, _optional_) — Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with _decoder\__.

Generates sequences of token ids for models with a language modeling head.
