source
stringclasses
470 values
url
stringlengths
49
167
file_type
stringclasses
1 value
chunk
stringlengths
1
512
chunk_id
stringlengths
5
9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
the repetition of n-grams present in the prompt. It was designed to promote chattiness in a language model, by preventing the generation of n-grams present in previous conversation rounds. Args: encoder_ngram_size (`int`): All ngrams of size `ngram_size` can only occur within the encoder input ids. encoder_input_ids (`int`): The encoder_input_ids that should not be repeated within the decoder ids. Examples: ```py >>> from transformers import AutoTokenizer, AutoModelForCausalLM
427_7_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m") >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m") >>> inputs = tokenizer("Alice: I love cats. What do you love?\nBob:", return_tensors="pt")
427_7_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> inputs = tokenizer("Alice: I love cats. What do you love?\nBob:", return_tensors="pt") >>> # With greedy decoding, we see Bob repeating Alice's opinion. If Bob was a chatbot, it would be a poor one. >>> outputs = model.generate(**inputs) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) Alice: I love cats. What do you love? Bob: I love cats. What do you
427_7_9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # With this logits processor, we can prevent Bob from repeating Alice's opinion. >>> outputs = model.generate(**inputs, encoder_no_repeat_ngram_size=2) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) Alice: I love cats. What do you love? Bob: My cats are very cute. ``` - __call__ [`LogitsProcessor`] that works similarly to [`RepetitionPenaltyLogitsProcessor`], but with an *inverse* penalty
427_7_10
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
- __call__ [`LogitsProcessor`] that works similarly to [`RepetitionPenaltyLogitsProcessor`], but with an *inverse* penalty that is applied to the tokens present in the prompt. In other words, a penalty above 1.0 increases the odds of selecting tokens that were present in the prompt. It was designed to avoid hallucination in input-grounded tasks, like summarization. Although originally intended for encoder-decoder models, it can also be used with decoder-only models like LLMs. Args: penalty (`float`):
427_7_11
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
for encoder-decoder models, it can also be used with decoder-only models like LLMs. Args: penalty (`float`): The parameter for repetition penalty. 1.0 means no penalty. Above 1.0 rewards prompt tokens. Between 0.0 and 1.0 penalizes prompt tokens. encoder_input_ids (`torch.LongTensor`): The encoder_input_ids that should be repeated within the decoder ids. Examples: ```python >>> from transformers import AutoModelForCausalLM, AutoTokenizer
427_7_12
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m") >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m") >>> inputs = tokenizer(["Alice and Bob. The third member's name was"], return_tensors="pt") >>> gen_out = model.generate(**inputs) >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0]) Alice and Bob. The third member's name was not mentioned.
427_7_13
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # With the `encoder_repetition_penalty` argument we can trigger this logits processor in `generate`, which can >>> # promote the use of prompt tokens ("Bob" in this example) >>> gen_out = model.generate(**inputs, encoder_repetition_penalty=1.2) >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0]) Alice and Bob. The third member's name was Bob. The third member's name was Bob. ``` - __call__
427_7_14
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
Alice and Bob. The third member's name was Bob. The third member's name was Bob. ``` - __call__ [`LogitsProcessor`] that performs epsilon-sampling, i.e. restricting to tokens with `prob >= epsilon`. Takes the largest min_tokens_to_keep tokens if no tokens satisfy this constraint. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more information. Args: epsilon (`float`):
427_7_15
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
Desmoothing](https://arxiv.org/abs/2210.15191) for more information. Args: epsilon (`float`): If set to > 0, only the most tokens with probabilities `epsilon` or higher are kept for generation. filter_value (`float`, *optional*, defaults to -inf): All filtered values will be set to this float value. min_tokens_to_keep (`int`, *optional*, defaults to 1): Minimum number of tokens that cannot be filtered. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
427_7_16
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> set_seed(1) >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt") >>> # With sampling, the output is unexpected -- sometimes too unexpected. >>> outputs = model.generate(**inputs, do_sample=True) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) A sequence: 1, 2, 3 | < 4 (left-hand pointer) ; <BLANKLINE> <BLANKLINE>
427_7_17
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # With epsilon sampling, the output gets restricted to high-probability tokens. Note that this is similar to >>> # Top P sampling, which restricts tokens based on their cumulative probability. >>> # Pro tip: The paper recomends using `epsilon_cutoff` values between 3e-4 and 9e-4 >>> outputs = model.generate(**inputs, do_sample=True, epsilon_cutoff=0.1) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9 ``` - __call__
427_7_18
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9 ``` - __call__ [`LogitsProcessor`] that performs eta-sampling, a technique to filter out tokens with probabilities below a dynamic cutoff value, `eta`, which is calculated based on a combination of the hyperparameter `epsilon` and the entropy of the token probabilities, i.e. `eta := min(epsilon, sqrt(epsilon * e^-entropy(probabilities)))`. Takes the largest
427_7_19
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
the token probabilities, i.e. `eta := min(epsilon, sqrt(epsilon * e^-entropy(probabilities)))`. Takes the largest min_tokens_to_keep tokens if no tokens satisfy this constraint. It addresses the issue of poor quality in long samples of text generated by neural language models leading to more coherent and fluent text. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more information. Note: `do_sample` must be set to `True` for this `LogitsProcessor` to work.
427_7_20
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
must be set to `True` for this `LogitsProcessor` to work. Args: epsilon (`float`): A float value in the range (0, 1). Hyperparameter used to calculate the dynamic cutoff value, `eta`. The suggested values from the paper ranges from 3e-4 to 4e-3 depending on the size of the model. filter_value (`float`, *optional*, defaults to -inf): All values that are found to be below the dynamic cutoff value, `eta`, are set to this float value. This
427_7_21
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
All values that are found to be below the dynamic cutoff value, `eta`, are set to this float value. This parameter is useful when logits need to be modified for very low probability tokens that should be excluded from generation entirely. min_tokens_to_keep (`int`, *optional*, defaults to 1): Specifies the minimum number of tokens that must be kept for generation, regardless of their probabilities. For example, if `min_tokens_to_keep` is set to 1, at least one token will always be kept for generation,
427_7_22
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
For example, if `min_tokens_to_keep` is set to 1, at least one token will always be kept for generation, even if all tokens have probabilities below the cutoff `eta`. device (`str`, *optional*, defaults to `"cpu"`): The device to allocate the tensors. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
427_7_23
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> set_seed(1) >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt") >>> # With sampling, the output is unexpected -- sometimes too unexpected. >>> outputs = model.generate(**inputs, do_sample=True) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) A sequence: 1, 2, 3 | < 4 (left-hand pointer) ; <BLANKLINE> <BLANKLINE>
427_7_24
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # With eta sampling, the output gets restricted to high-probability tokens. You can see it as a dynamic form of >>> # epsilon sampling that adapts its cutoff probability based on the entropy (high entropy = lower cutoff). >>> # Pro tip: The paper recomends using `eta_cutoff` values between 3e-4 to 4e-3 >>> outputs = model.generate(**inputs, do_sample=True, eta_cutoff=0.1) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9 ``` - __call__
427_7_25
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9 ``` - __call__ [`LogitsProcessor`] that exponentially increases the score of the `eos_token_id` after `start_index` has been reached. This allows generating shorter sequences without having a hard cutoff, allowing the `eos_token` to be predicted in a meaningful position. Args: exponential_decay_length_penalty (`tuple(int, float)`): This tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty
427_7_26
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
This tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay eos_token_id (`Union[int, List[int], torch.Tensor]`): The id(s) of the *end-of-sequence* token. input_ids_seq_length (`int`): The length of the input sequence. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
427_7_27
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") >>> text = "Just wanted to let you know, I" >>> inputs = tokenizer(text, return_tensors="pt")
427_7_28
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # Let's consider that we want short sentences, so we limit `max_length=30`. However, we observe that the answer >>> # tends to end abruptly. >>> set_seed(1) >>> outputs = model.generate(**inputs, do_sample=True, temperature=0.9, max_length=30, pad_token_id=50256) >>> print(tokenizer.batch_decode(outputs)[0]) Just wanted to let you know, I received a link to an ebook, the book How To Start A Social Network which was published in 2010. Although
427_7_29
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # To promote the appearance of the EOS token at the right time, we add the `exponential_decay_length_penalty = >>> # (start_index, decay_factor)`. Instead of cutting at max_tokens, the output comes to an end before and usually >>> # with more meaning. What happens is that starting from `start_index` the EOS token score will be increased >>> # by `decay_factor` exponentially. However, if you set a high decay factor, you may also end up with abruptly >>> # ending sequences. >>> set_seed(1)
427_7_30
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # ending sequences. >>> set_seed(1) >>> outputs = model.generate( ... **inputs, ... do_sample=True, ... temperature=0.9, ... max_length=30, ... pad_token_id=50256, ... exponential_decay_length_penalty=(15, 1.6), ... ) >>> print(tokenizer.batch_decode(outputs)[0]) Just wanted to let you know, I received a link to an ebook, the book How To Start A Social Network which<|endoftext|>
427_7_31
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # With a small decay factor, you will have a higher chance of getting a meaningful sequence. >>> set_seed(1) >>> outputs = model.generate( ... **inputs, ... do_sample=True, ... temperature=0.9, ... max_length=30, ... pad_token_id=50256, ... exponential_decay_length_penalty=(15, 1.01), ... ) >>> print(tokenizer.batch_decode(outputs)[0]) Just wanted to let you know, I received a link to an ebook, the book How To Start A Social Network which was published in 2010.<|endoftext|>
427_7_32
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
published in 2010.<|endoftext|> ``` - __call__ [`LogitsProcessor`] that enforces the specified token as the first generated token. Used with encoder-decoder models. Args: bos_token_id (`int`): The id of the token to force as the first generated token. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
427_7_33
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-small") >>> tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-small") >>> inputs = tokenizer("Translate from English to German: I love cats.", return_tensors="pt") >>> # By default, it continues generating according to the model's logits >>> outputs = model.generate(**inputs, max_new_tokens=10) >>> print(tokenizer.batch_decode(outputs)[0]) <pad> Ich liebe Kitty.</s>
427_7_34
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # We can use `forced_bos_token_id` to force the start of generation with an encoder-decoder model >>> # (including forcing it to end straight away with an EOS token) >>> outputs = model.generate(**inputs, max_new_tokens=10, forced_bos_token_id=tokenizer.eos_token_id) >>> print(tokenizer.batch_decode(outputs)[0]) <pad></s> ``` - __call__ [`LogitsProcessor`] that enforces the specified token as the last generated token when `max_length` is reached. Args: max_length (`int`):
427_7_35
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
Args: max_length (`int`): The maximum length of the sequence to be generated. eos_token_id (`Union[int, List[int], torch.Tensor]`): The id(s) of the *end-of-sequence* token. device (`str`, *optional*, defaults to `"cpu"`): The device to allocate the tensors. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM
427_7_36
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") >>> inputs = tokenizer("A sequence: 1, 2, 3", return_tensors="pt") >>> # By default, it continues generating according to the model's logits >>> outputs = model.generate(**inputs, max_new_tokens=10) >>> print(tokenizer.batch_decode(outputs)[0]) A sequence: 1, 2, 3, 4, 5, 6, 7, 8
427_7_37
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # `forced_eos_token_id` ensures the generation ends with a EOS token >>> outputs = model.generate(**inputs, max_new_tokens=10, forced_eos_token_id=tokenizer.eos_token_id) >>> print(tokenizer.batch_decode(outputs)[0]) A sequence: 1, 2, 3, 4, 5, 6, 7,<|endoftext|> ``` - __call__ [`LogitsProcessor`] that enforces diverse beam search. Note that this logits processor is only effective for [`PreTrainedModel.group_beam_search`]. See [Diverse Beam
427_7_38
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
Note that this logits processor is only effective for [`PreTrainedModel.group_beam_search`]. See [Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models](https://arxiv.org/pdf/1610.02424.pdf) for more details. Traditional beam search often generates very similar sequences across different beams. `HammingDiversityLogitsProcessor` addresses this by penalizing beams that generate tokens already chosen by other beams in the same time step. Args: diversity_penalty (`float`):
427_7_39
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
beams in the same time step. Args: diversity_penalty (`float`): 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. A higher `diversity_penalty` will enforce greater diversity among the beams. Adjusting this value can help strike a balance between diversity and natural likelihood. num_beams (`int`): Number of beams for beam search. 1 means no beam search. num_beam_groups (`int`):
427_7_40
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
num_beams (`int`): Number of beams for beam search. 1 means no beam search. num_beam_groups (`int`): 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. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM >>> import torch
427_7_41
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # Initialize the model and tokenizer >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base") >>> model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base")
427_7_42
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # A long text about the solar system >>> text = ( ... "The Solar System is a gravitationally bound system comprising the Sun and the objects that orbit it, " ... "either directly or indirectly. Of the objects that orbit the Sun directly, the largest are the eight " ... "planets, with the remainder being smaller objects, such as the five dwarf planets and small Solar System " ... "bodies. The Solar System formed 4.6 billion years ago from the gravitational collapse of a giant "
427_7_43
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
... "bodies. The Solar System formed 4.6 billion years ago from the gravitational collapse of a giant " ... "interstellar molecular cloud." ... ) >>> inputs = tokenizer("summarize: " + text, return_tensors="pt")
427_7_44
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # Generate diverse summary >>> outputs_diverse = model.generate( ... **inputs, ... num_beam_groups=2, ... diversity_penalty=10.0, ... max_length=100, ... num_beams=4, ... num_return_sequences=2, ... ) >>> summaries_diverse = tokenizer.batch_decode(outputs_diverse, skip_special_tokens=True)
427_7_45
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # Generate non-diverse summary >>> outputs_non_diverse = model.generate( ... **inputs, ... max_length=100, ... num_beams=4, ... num_return_sequences=2, ... ) >>> summary_non_diverse = tokenizer.batch_decode(outputs_non_diverse, skip_special_tokens=True)
427_7_46
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # With `diversity_penalty`, the resulting beams are much more diverse >>> print(summary_non_diverse) ['the solar system formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets.', 'the Solar System formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets.']
427_7_47
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> print(summaries_diverse) ['the solar system formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets.', 'the solar system formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets. the rest of the objects are smaller objects, such as the five dwarf planets and small solar system bodies.']
427_7_48
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
``` - __call__ [`LogitsProcessor`] that removes all `nan` and `inf` values to avoid the generation method to fail. Note that using the logits processor should only be used if necessary since it can slow down the generation method. This logits processor has no `generate` example, as there shouldn't be a correct combination of flags that warrants its use. - __call__ [`LogitsProcessor`] for normalizing the scores using log-softmax. It's important to normalize
427_7_49
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
its use. - __call__ [`LogitsProcessor`] for normalizing the scores using log-softmax. It's important to normalize the scores during beam search, after applying the logits processors or warpers, since the search algorithm used in this library doesn't do it (it only does it before, but they may need re-normalization) but it still supposes that the scores are normalized when comparing the hypotheses. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM >>> import torch
427_7_50
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") >>> inputs = tokenizer("A sequence: 1, 2, 3", return_tensors="pt")
427_7_51
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> inputs = tokenizer("A sequence: 1, 2, 3", return_tensors="pt") >>> # By default, the scores are not normalized -- the sum of their exponentials is NOT a normalized probability >>> # distribution, summing to 1 >>> outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True) >>> print(torch.allclose(torch.sum(torch.exp(outputs.scores[-1])), torch.Tensor((1.000,)), rtol=1e-4)) False
427_7_52
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # Normalizing them may have a positive impact on beam methods, or when using the scores on your application >>> outputs = model.generate(**inputs, renormalize_logits=True, return_dict_in_generate=True, output_scores=True) >>> print(torch.allclose(torch.sum(torch.exp(outputs.scores[-1])), torch.Tensor((1.000,)), rtol=1e-4)) True ``` - __call__ Abstract base class for all logit processors that can be applied during generation. - __call__
427_7_53
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
True ``` - __call__ Abstract base class for all logit processors that can be applied during generation. - __call__ Abstract base class for all logit processors that can be applied during generation.List - __call__ [`LogitsProcessor`] enforcing a min-length by setting EOS probability to 0. Note that, for decoder-only models like most LLMs, the length includes the prompt. Args: min_length (`int`): The minimum length below which the score of `eos_token_id` is set to `-float("Inf")`.
427_7_54
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
Args: min_length (`int`): The minimum length below which the score of `eos_token_id` is set to `-float("Inf")`. eos_token_id (`Union[int, List[int], torch.Tensor]`): The id(s) of the *end-of-sequence* token. device (`str`, *optional*, defaults to `"cpu"`): The device to allocate the tensors. Examples: ```python >>> from transformers import AutoModelForCausalLM, AutoTokenizer
427_7_55
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m") >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m") >>> inputs = tokenizer("A number:", return_tensors="pt") >>> gen_out = model.generate(**inputs) >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0]) A number: one
427_7_56
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # setting `min_length` to a value smaller than the uncontrolled output length has no impact >>> gen_out = model.generate(**inputs, min_length=3) >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0]) A number: one
427_7_57
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # setting a larger `min_length` will force the model to generate beyond its natural ending point, which is not >>> # necessarily incorrect >>> gen_out = model.generate(**inputs, min_length=10) >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0]) A number: one thousand, nine hundred and ninety-four ``` - __call__ [`LogitsProcessor`] enforcing a min-length of new tokens by setting EOS (End-Of-Sequence) token probability to 0.
427_7_58
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
- __call__ [`LogitsProcessor`] enforcing a min-length of new tokens by setting EOS (End-Of-Sequence) token probability to 0. Contrarily to [`MinLengthLogitsProcessor`], this processor ignores the prompt. Args: prompt_length_to_skip (`int`): The input tokens length. Not a valid argument when used with `generate` as it will automatically assign the input length. min_new_tokens (`int`): The minimum *new* tokens length below which the score of `eos_token_id` is set to `-float("Inf")`.
427_7_59
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
min_new_tokens (`int`): The minimum *new* tokens length below which the score of `eos_token_id` is set to `-float("Inf")`. eos_token_id (`Union[int, List[int], torch.Tensor]`): The id(s) of the *end-of-sequence* token. device (`str`, *optional*, defaults to `"cpu"`): The device to allocate the tensors. Examples: ```python >>> from transformers import AutoModelForCausalLM, AutoTokenizer
427_7_60
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m") >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m") >>> inputs = tokenizer(["A number:"], return_tensors="pt") >>> gen_out = model.generate(**inputs) >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0]) A number: one
427_7_61
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # setting `min_new_tokens` will force the model to generate beyond its natural ending point, which is not >>> # necessarily incorrect >>> gen_out = model.generate(**inputs, min_new_tokens=2) >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0]) A number: one thousand ``` - __call__ [`LogitsProcessor`] that performs min-p, i.e. keeps all tokens that are above a minimum probability, scaled by the
427_7_62
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
- __call__ [`LogitsProcessor`] that performs min-p, i.e. keeps all tokens that are above a minimum probability, scaled by the probability of the most likely token. As a result, the filter becomes more agressive in the presence of high-probability tokens, which is a sign of a confident output that we shouldn't deviate from. Often used together with [`TemperatureLogitsWarper`]. Used as an alternative to [`TopPLogitsWarper`] and [`TopKLogitsWarper`].
427_7_63
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
[`TopKLogitsWarper`]. Created by @menhguin and @kalomaze (github handles). Code adapted from [this external PR](https://github.com/oobabooga/text-generation-webui/pull/4449/files) Args: min_p (`float`): Minimum token probability, which will be scaled by the probability of the most likely token. It must be a value between 0 and 1. Typical values are in the 0.01-0.2 range, comparably selective as setting `top_p` in the 0.99-0.8 range (use the opposite of normal `top_p` values).
427_7_64
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
the 0.99-0.8 range (use the opposite of normal `top_p` values). filter_value (`float`, *optional*, defaults to -inf): All filtered values will be set to this float value. min_tokens_to_keep (`int`, *optional*, defaults to 1): Minimum number of tokens that cannot be filtered. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
427_7_65
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> set_seed(1) >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt") >>> # With sampling, the output is unexpected -- sometimes too unexpected. >>> outputs = model.generate(**inputs, do_sample=True) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) A sequence: 1, 2, 3 | < 4 (left-hand pointer) ; <BLANKLINE> <BLANKLINE>
427_7_66
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # With `min_p` sampling, the output gets restricted to high-probability tokens. >>> # Pro tip: In practice, LLMs use `min_p` in the 0.01-0.2 range. >>> outputs = model.generate(**inputs, do_sample=True, min_p=0.1) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9 ``` - __call__ [`LogitsProcessor`] that enforces that specified sequences will never be selected. <Tip>
427_7_67
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
``` - __call__ [`LogitsProcessor`] that enforces that specified sequences will never be selected. <Tip> In order to get the token ids of the words that should not appear in the generated text, make sure to set `add_prefix_space=True` when initializing the tokenizer, and use `tokenizer(bad_words, add_special_tokens=False).input_ids`. The `add_prefix_space` argument is only supported for some slow tokenizers, as fast tokenizers' prefixing behaviours come from `pre tokenizers`. Read more
427_7_68
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
as fast tokenizers' prefixing behaviours come from `pre tokenizers`. Read more [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers). </Tip> Args: bad_words_ids (`List[List[int]]`): List of list of token ids that are not allowed to be generated. eos_token_id (`Union[int, List[int], torch.Tensor]`, *optional*): The id(s) of the *end-of-sequence* token. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM
427_7_69
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") >>> inputs = tokenizer(["In a word, the cake is a"], return_tensors="pt") >>> output_ids = model.generate(inputs["input_ids"], max_new_tokens=5, pad_token_id=tokenizer.eos_token_id) >>> print(tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]) In a word, the cake is a bit of a mess.
427_7_70
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # Now let's take the bad words out. Please note that the tokenizer is initialized differently >>> tokenizer_with_prefix_space = AutoTokenizer.from_pretrained("openai-community/gpt2", add_prefix_space=True)
427_7_71
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> def get_tokens_as_list(word_list): ... "Converts a sequence of words into a list of tokens" ... tokens_list = [] ... for word in word_list: ... tokenized_word = tokenizer_with_prefix_space([word], add_special_tokens=False).input_ids[0] ... tokens_list.append(tokenized_word) ... return tokens_list
427_7_72
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> bad_words_ids = get_tokens_as_list(word_list=["mess"]) >>> output_ids = model.generate( ... inputs["input_ids"], max_new_tokens=5, bad_words_ids=bad_words_ids, pad_token_id=tokenizer.eos_token_id ... ) >>> print(tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]) In a word, the cake is a bit of a surprise. ``` - __call__ N-grams are groups of "n" consecutive words, characters, or tokens taken from a sequence of text. Given the
427_7_73
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
``` - __call__ N-grams are groups of "n" consecutive words, characters, or tokens taken from a sequence of text. Given the sentence: "She runs fast", the bi-grams (n=2) would be ("she", "runs") and ("runs", "fast"). In text generation, avoiding repetitions of word sequences provides a more diverse output. This [`LogitsProcessor`] enforces no repetition of n-grams by setting the scores of banned tokens to negative infinity which eliminates those tokens
427_7_74
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
repetition of n-grams by setting the scores of banned tokens to negative infinity which eliminates those tokens from consideration when further processing the scores. Note that, for decoder-only models like most LLMs, the prompt is also considered to obtain the n-grams. [Fairseq](https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345). <Tip>
427_7_75
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
<Tip> Use n-gram penalties with care. For instance, penalizing 2-grams (bigrams) in an article about the city of New York might lead to undesirable outcomes where the city's name appears only once in the entire text. [Reference](https://huggingface.co/blog/how-to-generate) </Tip> Args: ngram_size (`int`): All ngrams of size `ngram_size` can only occur once. Examples: ```py >>> from transformers import AutoTokenizer, AutoModelForCausalLM
427_7_76
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") >>> inputs = tokenizer(["Today I"], return_tensors="pt") >>> output = model.generate(**inputs) >>> print(tokenizer.decode(output[0], skip_special_tokens=True)) Today I’m not sure if I’m going to be able to do it.
427_7_77
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # Now let's add ngram size using `no_repeat_ngram_size`. This stops the repetitions ("I’m") in the output. >>> output = model.generate(**inputs, no_repeat_ngram_size=2) >>> print(tokenizer.decode(output[0], skip_special_tokens=True)) Today I’m not sure if I can get a better understanding of the nature of this issue ``` - __call__ [`LogitsProcessor`] that enforces constrained generation and is useful for prefix-conditioned constrained
427_7_78
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
``` - __call__ [`LogitsProcessor`] that enforces constrained generation and is useful for prefix-conditioned constrained generation. See [Autoregressive Entity Retrieval](https://arxiv.org/abs/2010.00904) for more information. Args: prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`): This function constraints the beam search to allowed tokens only at each step. This function takes 2
427_7_79
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
This function constraints the beam search to allowed tokens only at each step. This function takes 2 arguments `inputs_ids` and the batch ID `batch_id`. It has to return a list with the allowed tokens for the next generation step conditioned on the previously generated tokens `inputs_ids` and the batch ID `batch_id`. Examples: ```py >>> from transformers import AutoTokenizer, AutoModelForCausalLM
427_7_80
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m") >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m") >>> inputs = tokenizer("Alice and Bob", return_tensors="pt") >>> # By default, it continues generating according to the model's logits >>> outputs = model.generate(**inputs, max_new_tokens=5) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) Alice and Bob are friends
427_7_81
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # We can contrain it with `prefix_allowed_tokens_fn` to force a certain behavior based on a prefix. >>> # For instance, we can force an entire entity to be generated when its beginning is detected. >>> entity = tokenizer(" Bob Marley", return_tensors="pt").input_ids[0] # 3 tokens >>> def prefix_allowed_tokens_fn(batch_id, input_ids): ... ''' ... Attempts to generate 'Bob Marley' when 'Bob' is detected. ... In this case, `batch_id` is not used, but you can set rules for each batch member.
427_7_82
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
... In this case, `batch_id` is not used, but you can set rules for each batch member. ... ''' ... if input_ids[-1] == entity[0]: ... return [entity[1].item()] ... elif input_ids[-2] == entity[0] and input_ids[-1] == entity[1]: ... return [entity[2].item()] ... return list(range(tokenizer.vocab_size)) # If no match, allow all tokens
427_7_83
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> outputs = model.generate(**inputs, max_new_tokens=5, prefix_allowed_tokens_fn=prefix_allowed_tokens_fn) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) Alice and Bob Marley ``` - __call__ [`LogitsProcessor`] that prevents the repetition of previous tokens through a penalty. This penalty is applied at most once per token. Note that, for decoder-only models like most LLMs, the considered tokens include the prompt.
427_7_84
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
most once per token. Note that, for decoder-only models like most LLMs, the considered tokens include the prompt. In the original [paper](https://arxiv.org/pdf/1909.05858.pdf), the authors suggest the use of a penalty of around 1.2 to achieve a good balance between truthful generation and lack of repetition. To penalize and reduce repetition, use `penalty` values above 1.0, where a higher value penalizes more strongly. To reward and encourage
427_7_85
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
repetition, use `penalty` values above 1.0, where a higher value penalizes more strongly. To reward and encourage repetition, use `penalty` values between 0.0 and 1.0, where a lower value rewards more strongly. Args: penalty (`float`): The parameter for repetition penalty. 1.0 means no penalty. Above 1.0 penalizes previously generated tokens. Between 0.0 and 1.0 rewards previously generated tokens. Examples: ```py >>> from transformers import AutoTokenizer, AutoModelForCausalLM
427_7_86
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # Initializing the model and tokenizer for it >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") >>> inputs = tokenizer(["I'm not going to"], return_tensors="pt")
427_7_87
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # This shows a normal generate without any specific parameters >>> summary_ids = model.generate(**inputs) >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0]) I'm not going to be able to do that. I'm going to be able to do that
427_7_88
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # This generates a penalty for repeated tokens >>> penalized_ids = model.generate(**inputs, repetition_penalty=1.1) >>> print(tokenizer.batch_decode(penalized_ids, skip_special_tokens=True)[0]) I'm not going to be able to do that. I'll just have to go out and play ``` - __call__ [`LogitsProcessor`] that applies an additive bias on sequences. The bias is applied to the last token of a sequence
427_7_89
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
[`LogitsProcessor`] that applies an additive bias on sequences. The bias is applied to the last token of a sequence when the next generated token can complete it. Consequently, to take the most of biasing sequences with more than one token, consider using beam methods (to gracefully work around partially completed sequences that have a negative bias) and applying the bias to their prefixes (to ensure the bias is applied earlier). <Tip>
427_7_90
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
negative bias) and applying the bias to their prefixes (to ensure the bias is applied earlier). <Tip> In order to get the token ids of the sequences that you want to bias, make sure to set `add_prefix_space=True` when initializing the tokenizer, and use `tokenizer(bad_words, add_special_tokens=False).input_ids`. The `add_prefix_space` argument is only supported for some slow tokenizers, as fast tokenizers' prefixing behaviours
427_7_91
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
`add_prefix_space` argument is only supported for some slow tokenizers, as fast tokenizers' prefixing behaviours come from `pre tokenizers`. Read more [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers). </Tip> Args: sequence_bias (`List[List[Union[List[int], float]]]`): List of lists that maps a sequence of tokens to its bias term (e.g. `[[[10, 45], -2.0], [[64], -7.5]]`). Positive biases increase the odds of the
427_7_92
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
[[64], -7.5]]`). Positive biases increase the odds of the sequence being selected, while negative biases do the opposite. If a sequence has a length of 1, its bias will always be applied. Otherwise, the bias will only be applied if the sequence in question is about to be completed (in the token selection step after this processor is applied). Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM
427_7_93
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") >>> inputs = tokenizer(["The full name of Donald is Donald"], return_tensors="pt") >>> summary_ids = model.generate(inputs["input_ids"], max_new_tokens=4) >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0]) The full name of Donald is Donald J. Trump Jr
427_7_94
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # Now let's control generation through a bias. Please note that the tokenizer is initialized differently! >>> tokenizer_with_prefix_space = AutoTokenizer.from_pretrained("openai-community/gpt2", add_prefix_space=True) >>> def get_tokens(word): ... return tokenizer_with_prefix_space([word], add_special_tokens=False).input_ids[0]
427_7_95
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> def get_tokens(word): ... return tokenizer_with_prefix_space([word], add_special_tokens=False).input_ids[0] >>> # If we add a negative bias without beam search, it may become "stuck" in a prefix without good continuations >>> sequence_bias = [get_tokens("Trump"), -10.0] >>> biased_ids = model.generate(inputs["input_ids"], max_new_tokens=4, sequence_bias=sequence_bias) >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0]) The full name of Donald is Donald J. Donald,
427_7_96
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> biased_ids = model.generate(inputs["input_ids"], max_new_tokens=4, num_beams=4, sequence_bias=sequence_bias) >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0]) The full name of Donald is Donald Rumsfeld,
427_7_97
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # We can also add a positive bias to nudge the model towards specific tokens or continuations >>> sequence_bias = [get_tokens("Donald Duck"), 10.0] >>> biased_ids = model.generate(inputs["input_ids"], max_new_tokens=4, num_beams=4, sequence_bias=sequence_bias) >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0]) The full name of Donald is Donald Duck. ``` - __call__ [`SuppressTokensAtBeginLogitsProcessor`] supresses a list of tokens as soon as the `generate` function starts
427_7_98
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
- __call__ [`SuppressTokensAtBeginLogitsProcessor`] supresses a list of tokens as soon as the `generate` function starts generating using `begin_index` tokens. This should ensure that the tokens defined by `begin_suppress_tokens` are not generated at the beginning. Originally created for [Whisper](https://huggingface.co/docs/transformers/model_doc/whisper). Examples: ```python >>> from transformers import AutoProcessor, WhisperForConditionalGeneration >>> from datasets import load_dataset
427_7_99
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en") >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
427_7_100
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # Whisper has `begin_suppress_tokens` set by default (= `[220, 50256]`). 50256 is the EOS token, so this means >>> # it can't generate and EOS token in the first iteration, but it can in the others. >>> outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True) >>> print(outputs.scores[0][0, 50256]) tensor(-inf) >>> print(outputs.scores[-1][0, 50256]) # in other places we can see some probability mass for EOS tensor(29.9010)
427_7_101
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # If we disable `begin_suppress_tokens`, we can generate EOS in the first iteration. >>> outputs = model.generate( ... **inputs, return_dict_in_generate=True, output_scores=True, begin_suppress_tokens=None ... ) >>> print(outputs.scores[0][0, 50256]) tensor(11.2027) ``` - __call__ This processor can be used to suppress a list of tokens. The processor will set their log probs to `-inf` so that they are not generated. Originally created for
427_7_102
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
that they are not generated. Originally created for [Whisper](https://huggingface.co/docs/transformers/model_doc/whisper). Examples: ```python >>> from transformers import AutoProcessor, WhisperForConditionalGeneration >>> from datasets import load_dataset
427_7_103
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en") >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
427_7_104
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # Whisper has a long list of suppressed tokens. For instance, in this case, the token 1 is suppressed by default. >>> outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True) >>> print(outputs.scores[1][0, 1]) # 1 (and not 0) is the first freely generated token tensor(-inf)
427_7_105
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/internal/generation_utils.md
https://huggingface.co/docs/transformers/en/internal/generation_utils/#pytorch
.md
>>> # If we disable `suppress_tokens`, we can generate it. >>> outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True, suppress_tokens=None) >>> print(outputs.scores[1][0, 1]) tensor(6.0678) ``` - __call__ Logits processor that implements watermarking techniques for text generation models. This class facilitates the application of SynthID text watermarking, a method for embedding imperceptible signals
427_7_106