Utilities for Generation (original) (raw)

This page lists all the utility functions used by generate().

Generate Outputs

The output of generate() is an instance of a subclass ofModelOutput. This output is a data structure containing all the information returned by generate(), but that can also be used as tuple or dictionary.

Here’s an example:

from transformers import GPT2Tokenizer, GPT2LMHeadModel

tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2") model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2")

inputs = tokenizer("Hello, my dog is cute and ", return_tensors="pt") generation_output = model.generate(**inputs, return_dict_in_generate=True, output_scores=True)

The generation_output object is a GenerateDecoderOnlyOutput, as we can see in the documentation of that class below, it means it has the following attributes:

Here we have the scores since we passed along output_scores=True, but we don’t have hidden_states andattentions because we didn’t pass output_hidden_states=True or output_attentions=True.

You can access each attribute as you would usually do, and if that attribute has not been returned by the model, you will get None. Here for instance generation_output.scores are all the generated prediction scores of the language modeling head, and generation_output.attentions is None.

When using our generation_output object as a tuple, it only keeps the attributes that don’t have None values. Here, for instance, it has two elements, loss then logits, so

will return the tuple (generation_output.sequences, generation_output.scores) for instance.

When using our generation_output object as a dictionary, it only keeps the attributes that don’t have Nonevalues. Here, for instance, it has two keys that are sequences and scores.

We document here all output types.

PyTorch

class transformers.generation.GenerateDecoderOnlyOutput

< source >

( sequences: LongTensor scores: typing.Optional[typing.Tuple[torch.FloatTensor]] = None logits: typing.Optional[typing.Tuple[torch.FloatTensor]] = None attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[typing.Tuple[torch.FloatTensor]]]] = None )

Parameters

Outputs of decoder-only generation models, when using non-beam methods.

class transformers.generation.GenerateEncoderDecoderOutput

< source >

( sequences: LongTensor scores: typing.Optional[typing.Tuple[torch.FloatTensor]] = None logits: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None cross_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None decoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[typing.Tuple[torch.FloatTensor]]]] = None )

Parameters

Outputs of encoder-decoder generation models, when using non-beam methods.

class transformers.generation.GenerateBeamDecoderOnlyOutput

< source >

( sequences: LongTensor sequences_scores: typing.Optional[torch.FloatTensor] = None scores: typing.Optional[typing.Tuple[torch.FloatTensor]] = None logits: typing.Optional[typing.Tuple[torch.FloatTensor]] = None beam_indices: typing.Optional[torch.LongTensor] = None attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[typing.Tuple[torch.FloatTensor]]]] = None )

Parameters

Outputs of decoder-only generation models, when using beam methods.

class transformers.generation.GenerateBeamEncoderDecoderOutput

< source >

( sequences: LongTensor sequences_scores: typing.Optional[torch.FloatTensor] = None scores: typing.Optional[typing.Tuple[torch.FloatTensor]] = None logits: typing.Optional[typing.Tuple[torch.FloatTensor]] = None beam_indices: typing.Optional[torch.LongTensor] = None encoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None cross_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None decoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[typing.Tuple[torch.FloatTensor]]]] = None )

Parameters

Outputs of encoder-decoder generation models, when using beam methods.

TensorFlow

class transformers.generation.TFGreedySearchEncoderDecoderOutput

< source >

( sequences: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None scores: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None encoder_attentions: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None decoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None cross_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None decoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None )

Parameters

Base class for outputs of encoder-decoder generation models using greedy search. Hidden states and attention weights of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the encoder_hidden_states attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)

class transformers.generation.TFGreedySearchDecoderOnlyOutput

< source >

( sequences: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None scores: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None )

Parameters

Base class for outputs of decoder-only generation models using greedy search.

class transformers.generation.TFSampleEncoderDecoderOutput

< source >

( sequences: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None scores: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None encoder_attentions: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None decoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None cross_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None decoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None )

Parameters

Base class for outputs of encoder-decoder generation models using sampling. Hidden states and attention weights of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the encoder_hidden_states attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)

class transformers.generation.TFSampleDecoderOnlyOutput

< source >

( sequences: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None scores: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None )

Parameters

Base class for outputs of decoder-only generation models using sampling.

class transformers.generation.TFBeamSearchEncoderDecoderOutput

< source >

( sequences: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None sequences_scores: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None scores: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None beam_indices: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None encoder_attentions: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None decoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None cross_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None decoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None )

Parameters

Base class for outputs of encoder-decoder generation models using beam search. Hidden states and attention weights of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the encoder_hidden_states attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)

class transformers.generation.TFBeamSearchDecoderOnlyOutput

< source >

( sequences: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None sequences_scores: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None scores: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None beam_indices: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None )

Parameters

Base class for outputs of decoder-only generation models using beam search.

class transformers.generation.TFBeamSampleEncoderDecoderOutput

< source >

( sequences: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None sequences_scores: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None scores: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None beam_indices: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None encoder_attentions: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None decoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None cross_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None decoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None )

Parameters

Base class for outputs of encoder-decoder generation models using beam sampling. Hidden states and attention weights of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the encoder_hidden_states attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)

class transformers.generation.TFBeamSampleDecoderOnlyOutput

< source >

( sequences: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None sequences_scores: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None scores: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None beam_indices: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None )

Parameters

Base class for outputs of decoder-only generation models using beam sample.

class transformers.generation.TFContrastiveSearchEncoderDecoderOutput

< source >

( sequences: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None scores: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None encoder_attentions: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None decoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None cross_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None decoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None )

Parameters

Base class for outputs of encoder-decoder generation models using contrastive search. Hidden states and attention weights of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the encoder_hidden_states attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)

class transformers.generation.TFContrastiveSearchDecoderOnlyOutput

< source >

( sequences: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None scores: typing.Optional[typing.Tuple[tensorflow.python.framework.tensor.Tensor]] = None attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.tensor.Tensor]]] = None )

Parameters

Base class for outputs of decoder-only generation models using contrastive search.

FLAX

class transformers.generation.FlaxSampleOutput

< source >

( sequences: typing.Optional[jax.Array] = None )

Parameters

Flax Base class for outputs of decoder-only generation models using sampling.

“Returns a new object replacing the specified fields with new values.

class transformers.generation.FlaxGreedySearchOutput

< source >

( sequences: typing.Optional[jax.Array] = None )

Parameters

Flax Base class for outputs of decoder-only generation models using greedy search.

“Returns a new object replacing the specified fields with new values.

class transformers.generation.FlaxBeamSearchOutput

< source >

( sequences: typing.Optional[jax.Array] = None scores: typing.Optional[jax.Array] = None )

Parameters

Flax Base class for outputs of decoder-only generation models using greedy search.

“Returns a new object replacing the specified fields with new values.

LogitsProcessor

A LogitsProcessor can be used to modify the prediction scores of a language model head for generation.

PyTorch

class transformers.AlternatingCodebooksLogitsProcessor

< source >

( input_start_len: int semantic_vocab_size: int codebook_size: int )

Parameters

LogitsProcessor enforcing alternated generation between the two codebooks of Bark.

This logits processor is exclusively compatible withBark’s fine submodel. See the model documentation for examples.

__call__

< source >

( input_ids: LongTensor scores: FloatTensor )

class transformers.ClassifierFreeGuidanceLogitsProcessor

< source >

( guidance_scale )

Parameters

LogitsProcessor for classifier free guidance (CFG). The scores are split over the batch dimension, where the first half correspond to the conditional logits (predicted from the input prompt) and the second half correspond to the unconditional logits (predicted from an empty or ‘null’ prompt). The processor computes a weighted average across the conditional and unconditional logits, parameterised by the guidance_scale.

See the paper for more information.

This logits processor is exclusively compatible withMusicGen

Examples:

from transformers import AutoProcessor, MusicgenForConditionalGeneration

processor = AutoProcessor.from_pretrained("facebook/musicgen-small") model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")

inputs = processor( ... text=["80s pop track with bassy drums and synth", "90s rock song with loud guitars and heavy drums"], ... padding=True, ... return_tensors="pt", ... ) audio_values = model.generate(**inputs, do_sample=True, guidance_scale=3, max_new_tokens=256)

__call__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.EncoderNoRepeatNGramLogitsProcessor

< source >

( encoder_ngram_size: int encoder_input_ids: LongTensor )

Parameters

LogitsProcessor that works similarly to NoRepeatNGramLogitsProcessor, but applied exclusively to prevent 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.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM

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")

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

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.EncoderRepetitionPenaltyLogitsProcessor

< source >

( penalty: float encoder_input_ids: LongTensor )

Parameters

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.

Examples:

from transformers import AutoModelForCausalLM, AutoTokenizer

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.

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.EpsilonLogitsWarper

< source >

( epsilon: float filter_value: float = -inf min_tokens_to_keep: int = 1 )

Parameters

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 for more information.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed

set_seed(1) model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")

inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")

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) ;

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.EtaLogitsWarper

< source >

( epsilon: float filter_value: float = -inf min_tokens_to_keep: int = 1 device: str = 'cpu' )

Parameters

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 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 for more information. Note: do_samplemust be set to True for this LogitsProcessor to work.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed

set_seed(1) model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")

inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")

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) ;

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.ExponentialDecayLengthPenalty

< source >

( exponential_decay_length_penalty: typing.Tuple[int, float] eos_token_id: typing.Union[int, typing.List[int], torch.Tensor] input_ids_seq_length: int )

Parameters

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.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed

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")

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

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|>

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|>

__call__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.ForcedBOSTokenLogitsProcessor

< source >

( bos_token_id: int )

Parameters

LogitsProcessor that enforces the specified token as the first generated token. Used with encoder-decoder models.

Examples:

from transformers import AutoTokenizer, AutoModelForSeq2SeqLM

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")

outputs = model.generate(**inputs, max_new_tokens=10) print(tokenizer.batch_decode(outputs)[0]) Ich liebe Kitty.

outputs = model.generate(**inputs, max_new_tokens=10, forced_bos_token_id=tokenizer.eos_token_id) print(tokenizer.batch_decode(outputs)[0])

__call__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.ForcedEOSTokenLogitsProcessor

< source >

( max_length: int eos_token_id: typing.Union[int, typing.List[int], torch.Tensor] device: str = 'cpu' )

Parameters

LogitsProcessor that enforces the specified token as the last generated token when max_length is reached.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")

inputs = tokenizer("A sequence: 1, 2, 3", return_tensors="pt")

outputs = model.generate(**inputs, max_new_tokens=10) print(tokenizer.batch_decode(outputs)[0]) A sequence: 1, 2, 3, 4, 5, 6, 7, 8

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.HammingDiversityLogitsProcessor

< source >

( diversity_penalty: float num_beams: int num_beam_groups: int )

Parameters

LogitsProcessor that enforces diverse beam search.

Note that this logits processor is only effective for PreTrainedModel.group_beam_search. See Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models 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.

Examples:

from transformers import AutoTokenizer, AutoModelForSeq2SeqLM import torch

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

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 " ... "interstellar molecular cloud." ... ) inputs = tokenizer("summarize: " + text, return_tensors="pt")

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)

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)

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.']

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.']

__call__

< source >

( input_ids: LongTensor scores: FloatTensor current_tokens: LongTensor beam_group_idx: int ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.InfNanRemoveLogitsProcessor

< source >

( )

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.LogitNormalization

< source >

( )

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:

from transformers import AutoTokenizer, AutoModelForCausalLM import torch

model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")

inputs = tokenizer("A sequence: 1, 2, 3", return_tensors="pt")

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

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

Abstract base class for all logit processors that can be applied during generation.

__call__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.LogitsProcessorList

< source >

( iterable = () )

This class can be used to create a list of LogitsProcessor to subsequently process a scores input tensor. This class inherits from list and adds a specific call method to apply each LogitsProcessor to the inputs.

__call__

< source >

( input_ids: LongTensor scores: FloatTensor **kwargs ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.MinLengthLogitsProcessor

< source >

( min_length: int eos_token_id: typing.Union[int, typing.List[int], torch.Tensor] device: str = 'cpu' )

Parameters

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.

Examples:

from transformers import AutoModelForCausalLM, AutoTokenizer

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

gen_out = model.generate(**inputs, min_length=3) print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0]) A number: one

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.MinNewTokensLengthLogitsProcessor

< source >

( prompt_length_to_skip: int min_new_tokens: int eos_token_id: typing.Union[int, typing.List[int], torch.Tensor] device: str = 'cpu' )

Parameters

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.

Examples:

from transformers import AutoModelForCausalLM, AutoTokenizer

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

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.MinPLogitsWarper

< source >

( min_p: float filter_value: float = -inf min_tokens_to_keep: int = 1 )

Parameters

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 aggressive 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 andTopKLogitsWarper.

Created by @menhguin and @kalomaze (github handles). Code adapted from this external PR

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed

set_seed(1) model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")

inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")

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) ;

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__

< source >

( input_ids: LongTensor scores: FloatTensor )

class transformers.NoBadWordsLogitsProcessor

< source >

( bad_words_ids: typing.List[typing.List[int]] eos_token_id: typing.Union[int, typing.List[int], torch.Tensor, NoneType] = None )

Parameters

LogitsProcessor that enforces that specified sequences will never be selected.

In order to get the token ids of the words that should not appear in the generated text, make sure to setadd_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 morehere.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM

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.

tokenizer_with_prefix_space = AutoTokenizer.from_pretrained("openai-community/gpt2", add_prefix_space=True)

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

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.NoRepeatNGramLogitsProcessor

< source >

( ngram_size: int )

Parameters

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 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.

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

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM

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.

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.PrefixConstrainedLogitsProcessor

< source >

( prefix_allowed_tokens_fn: typing.Callable[[int, torch.Tensor], typing.List[int]] num_beams: int )

Parameters

LogitsProcessor that enforces constrained generation and is useful for prefix-conditioned constrained generation. See Autoregressive Entity Retrieval for more information.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m") tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")

inputs = tokenizer("Alice and Bob", return_tensors="pt")

outputs = model.generate(**inputs, max_new_tokens=5) print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) Alice and Bob are friends

entity = tokenizer(" Bob Marley", return_tensors="pt").input_ids[0]
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. ... ''' ... 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))

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.RepetitionPenaltyLogitsProcessor

< source >

( penalty: float prompt_ignore_length: typing.Optional[int] = None )

Parameters

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 by default.

In the original paper, 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 repetition, use penalty values between 0.0 and 1.0, where a lower value rewards more strongly.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM, RepetitionPenaltyLogitsProcessor

model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") inputs = tokenizer(["I'm not going to"], return_tensors="pt")

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

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

rep_pen_processor = RepetitionPenaltyLogitsProcessor( ... penalty=1.1, ... prompt_ignore_length=inputs["input_ids"].shape[-1] ... ) penalized_ids = model.generate(**inputs, logits_processor=[rep_pen_processor]) print(tokenizer.batch_decode(penalized_ids, skip_special_tokens=True)[0]) I'm not going to be able to do that. I'm going to have to go through a lot of things, and

__call__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.SequenceBiasLogitsProcessor

< source >

( sequence_bias: typing.List[typing.List[typing.Union[typing.List[int], float]]] )

Parameters

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).

At a token-level, biasing a word is different from biasing a word with a space before it. If you want to bias “foo” mid-sentence, you’ll likely want to add a prefix space and bias ” foo” instead. Check the tokenizer section of our NLP course to find out why: https://huggingface.co/learn/nlp-course/chapter2/4?fw=pt

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") inputs = tokenizer(["The full name of Donald is Donald"], return_tensors="pt")

summary_ids = model.generate(inputs["input_ids"], max_new_tokens=4, do_sample=False) print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0]) The full name of Donald is Donald John Trump Sr.

def get_tokens(word): ... return tokenizer([word], add_special_tokens=False).input_ids[0]

sequence_bias = [[get_tokens("Trump"), -10.0],]
biased_ids = model.generate( ... inputs["input_ids"], max_new_tokens=4, do_sample=False, sequence_bias=sequence_bias ... ) print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0]) The full name of Donald is Donald John Trump Sr.

sequence_bias = [[get_tokens(" Trump"), -10.0],]
biased_ids = model.generate( ... inputs["input_ids"], max_new_tokens=4, do_sample=False, sequence_bias=sequence_bias ... ) print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0]) The full name of Donald is Donald John Harper. He

sequence_bias = [[get_tokens(" Donald Duck"), 10.0],] biased_ids = model.generate( ... inputs["input_ids"], max_new_tokens=4, num_beams=4, do_sample=False, sequence_bias=sequence_bias ... ) print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0]) The full name of Donald is Donald Duck. He is

__call__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.SuppressTokensAtBeginLogitsProcessor

< source >

( begin_suppress_tokens begin_index device: str = 'cpu' )

SuppressTokensAtBeginLogitsProcessor suppresses 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 forWhisper.

Examples:

from transformers import AutoProcessor, WhisperForConditionalGeneration from datasets import load_dataset

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")

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])
tensor(29.9010)

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.SuppressTokensLogitsProcessor

< source >

( suppress_tokens device: str = 'cpu' )

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 forWhisper.

Examples:

from transformers import AutoProcessor, WhisperForConditionalGeneration from datasets import load_dataset

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")

outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True) print(outputs.scores[1][0, 1])
tensor(-inf)

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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.SynthIDTextWatermarkLogitsProcessor

< source >

( ngram_len: int keys: typing.List[int] sampling_table_size: int sampling_table_seed: int context_history_size: int device: device skip_first_ngram_calls: bool = False debug_mode: bool = False )

Parameters

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 into generated text to aid in detecting synthetic content. It operates by subtly manipulating the probabilities of token selection during text generation in a manner that can be reliably recovered later for verification.

Key Features:

Refer to paper url: https://www.nature.com/articles/s41586-024-08025-4 for more details around this.

Examples:

from transformers import AutoModelForCausalLM, AutoTokenizer, SynthIDTextWatermarkingConfig

tokenizer = AutoTokenizer.from_pretrained('google/gemma-2-2b', padding_side="left") model = AutoModelForCausalLM.from_pretrained('google/gemma-2-2b')

watermarking_config = SynthIDTextWatermarkingConfig( ... keys=[654, 400, 836, 123, 340, 443, 597, 160, 57], ... ngram_len=5, ... )

tokenized_prompts = tokenizer(["Once upon a time, "], return_tensors="pt", padding=True) output_sequences = model.generate( ... **tokenized_prompts, watermarking_config=watermarking_config, do_sample=True, max_new_tokens=10 ... ) watermarked_text = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)

__call__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.TemperatureLogitsWarper

< source >

( temperature: float )

Parameters

LogitsProcessor for temperature (exponential scaling output probability distribution), which effectively means that it can control the randomness of the predicted tokens. Often used together with TopPLogitsWarper andTopKLogitsWarper.

Make sure that do_sample=True is included in the generate arguments otherwise the temperature value won’t have any effect.

Examples:

import torch from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed

set_seed(0)

tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") model.config.pad_token_id = model.config.eos_token_id inputs = tokenizer(["Hugging Face Company is"], return_tensors="pt")

generate_kwargs = {"max_new_tokens": 10, "do_sample": True, "temperature": 1.0, "num_return_sequences": 2} outputs = model.generate(**inputs, **generate_kwargs) print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) ['Hugging Face Company is one of these companies that is going to take a', "Hugging Face Company is a brand created by Brian A. O'Neil"]

generate_kwargs["temperature"] = 0.0001 outputs = model.generate(**inputs, **generate_kwargs) print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) ['Hugging Face Company is a company that has been around for over 20 years', 'Hugging Face Company is a company that has been around for over 20 years']

__call__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.TopKLogitsWarper

< source >

( top_k: int filter_value: float = -inf min_tokens_to_keep: int = 1 )

Parameters

LogitsProcessor that performs top-k, i.e. restricting to the k highest probability elements. Often used together with TemperatureLogitsWarper and TopPLogitsWarper.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed

set_seed(1) model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")

inputs = tokenizer("A sequence: A, B, C, D", return_tensors="pt")

outputs = model.generate(**inputs, do_sample=True) print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) A sequence: A, B, C, D, E — S — O, P — R

outputs = model.generate(**inputs, do_sample=True, top_k=2) print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) A sequence: A, B, C, D, E, F, G, H, I

__call__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.TopPLogitsWarper

< source >

( top_p: float filter_value: float = -inf min_tokens_to_keep: int = 1 )

Parameters

LogitsProcessor that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off. Often used together with TemperatureLogitsWarper and TopKLogitsWarper.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed

set_seed(1) model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")

inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")

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) ;

outputs = model.generate(**inputs, do_sample=True, top_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__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.TypicalLogitsWarper

< source >

( mass: float = 0.9 filter_value: float = -inf min_tokens_to_keep: int = 1 )

Parameters

LogitsProcessor that performs typical decoding. Inspired on how humans use language, it prioritizes tokens whose log probability is close to the entropy of the token probability distribution. This means that the most likely tokens may be discarded in the process.

See Typical Decoding for Natural Language Generation for more information.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed

model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m") tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")

inputs = tokenizer("1, 2, 3", return_tensors="pt")

outputs = model.generate(**inputs) print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

set_seed(18) outputs = model.generate(**inputs, do_sample=True) print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10

set_seed(18) outputs = model.generate( ... **inputs, do_sample=True, typical_p=0.1, return_dict_in_generate=True, output_scores=True ... ) print(tokenizer.batch_decode(outputs.sequences, skip_special_tokens=True)[0]) 1, 2, 3 and 5

print(outputs.scores[1][0, 934]) tensor(-inf)

__call__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.UnbatchedClassifierFreeGuidanceLogitsProcessor

< source >

( guidance_scale: float model unconditional_ids: typing.Optional[torch.LongTensor] = None unconditional_attention_mask: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = True )

Parameters

Logits processor for Classifier-Free Guidance (CFG). The processors computes a weighted average across scores from prompt conditional and prompt unconditional (or negative) logits, parameterized by the guidance_scale. The unconditional scores are computed internally by prompting model with the unconditional_ids branch.

See the paper for more information.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") inputs = tokenizer(["Today, a dragon flew over Paris, France,"], return_tensors="pt") out = model.generate(inputs["input_ids"], guidance_scale=1.5) tokenizer.batch_decode(out, skip_special_tokens=True)[0] 'Today, a dragon flew over Paris, France, killing at least 50 people and injuring more than 100'

neg_inputs = tokenizer(["A very happy event happened,"], return_tensors="pt") out = model.generate(inputs["input_ids"], guidance_scale=2, negative_prompt_ids=neg_inputs["input_ids"]) tokenizer.batch_decode(out, skip_special_tokens=True)[0] 'Today, a dragon flew over Paris, France, killing at least 130 people. French media reported that'

neg_inputs = tokenizer(["A very happy event happened,"], return_tensors="pt") out = model.generate(inputs["input_ids"], guidance_scale=0, negative_prompt_ids=neg_inputs["input_ids"]) tokenizer.batch_decode(out, skip_special_tokens=True)[0] "Today, a dragon flew over Paris, France, and I'm very happy to be here. I"

class transformers.WhisperTimeStampLogitsProcessor

< source >

( generate_config begin_index: typing.Optional[int] = None _detect_timestamp_from_logprob: typing.Optional[bool] = None )

Parameters

LogitsProcessor that modifies the logits for the generation of timestamps in the transcription. When the input tokens are at a specific threshold, the processor sets the scores to negative infinity. The processor makes sure that timestamp tokens appear in pairs, by masking out the logits that would break this pairing pattern. This is done to maintain the consistency and structure of generated timestamps. It also ensures that when the predicted probability of sampling any of the timestamp token is greater than any individual non-timestamp token, those non-timestamp logits are set to negative infinity. This is done to ensure the generation of timestamps over other potential tokens.

See the paper for more information.

Examples:

import torch from transformers import AutoProcessor, WhisperForConditionalGeneration, GenerationConfig from datasets import load_dataset

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[3]["audio"]["array"], return_tensors="pt") input_features = inputs.input_features

generated_ids = model.generate(inputs=input_features, return_timestamps=True) transcription = processor.batch_decode(generated_ids, decode_with_timestamps=True)[0] print("Transcription:", transcription) Transcription: <|startoftranscript|><|0.00|> He has grave doubts whether Sir Frederick Layton's work is really Greek after all, and can<|6.44|><|6.44|> discover in it but little of rocky Ithaca.<|9.44|><|endoftext|>

#No timestamps & change EOS: #This allows the user to select a specific token to terminate the sequence on, in this case it's the word "can"(460) model.generation_config.eos_token_id = 460 generated_ids = model.generate(inputs=input_features,return_timestamps=False) transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] print("Transcription:", transcription) Transcription: He has grave doubts whether Sir Frederick Layton's work is really Greek after all and can

__call__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

class transformers.WatermarkLogitsProcessor

< source >

( vocab_size device greenlist_ratio: float = 0.25 bias: float = 2.0 hashing_key: int = 15485863 seeding_scheme: str = 'lefthash' context_width: int = 1 )

Parameters

Logits processor for watermarking generated text. The processor modifies model output scores by adding a small bias to randomized set of “green” tokens before generating the next token. “Green” tokens selection process depends on theseeding_scheme used. The code was based on the original repo.

The text generated by this LogitsProcessor can be detected using WatermarkDetector. See call() for details,

See the paper for more information.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkingConfig

model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") inputs = tokenizer(["Alice and Bob are"], return_tensors="pt")

out = model.generate(inputs["input_ids"], max_length=20, do_sample=False) tokenizer.batch_decode(out, skip_special_tokens=True)[0] 'Alice and Bob are both in the same room.\n\n"I'm not sure if you're'

watermarking_config = WatermarkingConfig(bias=2.5, context_width=2, seeding_scheme="selfhash") out = model.generate(inputs["input_ids"], watermarking_config=watermarking_config, max_length=20, do_sample=False) tokenizer.batch_decode(out, skip_special_tokens=True)[0] 'Alice and Bob are both still alive and well and the story is pretty much a one-hour adventure'

from transformers import WatermarkDetector detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config= watermarking_config) detection_preds = detector(out) detection_preds array([ True])

__call__

< source >

( input_ids: LongTensor scores: FloatTensor ) → torch.FloatTensor of shape (batch_size, config.vocab_size)

Parameters

Returns

torch.FloatTensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

TensorFlow

class transformers.TFForcedBOSTokenLogitsProcessor

< source >

( bos_token_id: int )

Parameters

TFLogitsProcessor that enforces the specified token as the first generated token.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int )

class transformers.TFForcedEOSTokenLogitsProcessor

< source >

( max_length: int eos_token_id: int )

Parameters

TFLogitsProcessor that enforces the specified token as the last generated token when max_length is reached.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int )

class transformers.TFForceTokensLogitsProcessor

< source >

( force_token_map: typing.List[typing.List[int]] )

This processor takes a list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. The processor will set their log probs to 0 and all other tokens to-inf so that they are sampled at their corresponding index.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int )

class transformers.TFLogitsProcessor

< source >

( )

Abstract base class for all logit processors that can be applied during generation.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int ) → tf.Tensor of shape (batch_size, config.vocab_size)

Parameters

Returns

tf.Tensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

TF method for processing logits.

class transformers.TFLogitsProcessorList

< source >

( iterable = () )

This class can be used to create a list of TFLogitsProcessor to subsequently process a scores input tensor. This class inherits from list and adds a specific call method to apply each TFLogitsProcessor to the inputs.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int **kwargs ) → tf.Tensor of shape (batch_size, config.vocab_size)

Parameters

Returns

tf.Tensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

Abstract base class for all logit warpers that can be applied during generation with multinomial sampling.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int ) → tf.Tensor of shape (batch_size, config.vocab_size)

Parameters

Returns

tf.Tensor of shape (batch_size, config.vocab_size)

The processed prediction scores.

TF method for warping logits.

class transformers.TFMinLengthLogitsProcessor

< source >

( min_length: int eos_token_id: int )

Parameters

TFLogitsProcessor enforcing a min-length by setting EOS probability to 0.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int )

class transformers.TFNoBadWordsLogitsProcessor

< source >

( bad_words_ids: typing.List[typing.List[int]] eos_token_id: int )

Parameters

TFLogitsProcessor that enforces that specified sequences will never be sampled.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int )

class transformers.TFNoRepeatNGramLogitsProcessor

< source >

( ngram_size: int )

Parameters

TFLogitsProcessor that enforces no repetition of n-grams. SeeFairseq.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int )

class transformers.TFRepetitionPenaltyLogitsProcessor

< source >

( penalty: float )

Parameters

TFLogitsProcessor enforcing an exponential penalty on repeated sequences.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int )

class transformers.TFSuppressTokensAtBeginLogitsProcessor

< source >

( begin_suppress_tokens begin_index )

TFSuppressTokensAtBeginLogitsProcessor suppresses 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 at not sampled at the beginning of the generation.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int )

class transformers.TFSuppressTokensLogitsProcessor

< source >

( suppress_tokens )

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 sampled.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int )

class transformers.TFTemperatureLogitsWarper

< source >

( temperature: float )

Parameters

TFLogitsWarper for temperature (exponential scaling output probability distribution).

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int )

class transformers.TFTopKLogitsWarper

< source >

( top_k: int filter_value: float = -inf min_tokens_to_keep: int = 1 )

Parameters

TFLogitsWarper that performs top-k, i.e. restricting to the k highest probability elements.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int )

class transformers.TFTopPLogitsWarper

< source >

( top_p: float filter_value: float = -inf min_tokens_to_keep: int = 1 )

Parameters

TFLogitsWarper that performs top-p, i.e. restricting to top tokens summing to <= prob_cut_off.

__call__

< source >

( input_ids: Tensor scores: Tensor cur_len: int )

FLAX

class transformers.FlaxForcedBOSTokenLogitsProcessor

< source >

( bos_token_id: int )

Parameters

FlaxLogitsProcessor that enforces the specified token as the first generated token.

__call__

< source >

( input_ids: Array scores: Array cur_len: int )

class transformers.FlaxForcedEOSTokenLogitsProcessor

< source >

( max_length: int eos_token_id: int )

Parameters

FlaxLogitsProcessor that enforces the specified token as the last generated token when max_length is reached.

__call__

< source >

( input_ids: Array scores: Array cur_len: int )

class transformers.FlaxForceTokensLogitsProcessor

< source >

( force_token_map )

Parameters

FlaxLogitsProcessor that takes a list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. The processor will set their log probs to 0 and all other tokens to -inf so that they are sampled at their corresponding index.

__call__

< source >

( input_ids: Array scores: Array cur_len: int )

class transformers.FlaxLogitsProcessor

< source >

( )

Abstract base class for all logit processors that can be applied during generation.

__call__

< source >

( input_ids: Array scores: Array ) → jnp.ndarray of shape (batch_size, config.vocab_size)

Parameters

Returns

jnp.ndarray of shape (batch_size, config.vocab_size)

The processed prediction scores.

Flax method for processing logits.

class transformers.FlaxLogitsProcessorList

< source >

( iterable = () )

This class can be used to create a list of FlaxLogitsProcessor or FlaxLogitsWarper to subsequently process a scores input tensor. This class inherits from list and adds a specific call method to apply eachFlaxLogitsProcessor or FlaxLogitsWarper to the inputs.

__call__

< source >

( input_ids: Array scores: Array cur_len: int **kwargs ) → jnp.ndarray of shape (batch_size, config.vocab_size)

Parameters

Returns

jnp.ndarray of shape (batch_size, config.vocab_size)

The processed prediction scores.

Abstract base class for all logit warpers that can be applied during generation with multinomial sampling.

__call__

< source >

( input_ids: Array scores: Array ) → jnp.ndarray of shape (batch_size, config.vocab_size)

Parameters

Returns

jnp.ndarray of shape (batch_size, config.vocab_size)

The processed prediction scores.

Flax method for warping logits.

class transformers.FlaxMinLengthLogitsProcessor

< source >

( min_length: int eos_token_id: int )

Parameters

FlaxLogitsProcessor enforcing a min-length by setting EOS probability to 0.

__call__

< source >

( input_ids: Array scores: Array cur_len: int )

class transformers.FlaxSuppressTokensAtBeginLogitsProcessor

< source >

( begin_suppress_tokens begin_index )

Parameters

FlaxLogitsProcessor suppressing a list of tokens as soon as the generate function starts generating usingbegin_index tokens. This should ensure that the tokens defined by begin_suppress_tokens are not sampled at the beginning of the generation.

__call__

< source >

( input_ids scores cur_len: int )

class transformers.FlaxSuppressTokensLogitsProcessor

< source >

( suppress_tokens: list )

Parameters

FlaxLogitsProcessor suppressing a list of tokens at each decoding step. The processor will set their log probs to be -inf so they are not sampled.

__call__

< source >

( input_ids: Array scores: Array cur_len: int )

class transformers.FlaxTemperatureLogitsWarper

< source >

( temperature: float )

Parameters

FlaxLogitsWarper for temperature (exponential scaling output probability distribution).

__call__

< source >

( input_ids: Array scores: Array cur_len: int )

class transformers.FlaxTopKLogitsWarper

< source >

( top_k: int filter_value: float = -inf min_tokens_to_keep: int = 1 )

Parameters

FlaxLogitsWarper that performs top-k, i.e. restricting to the k highest probability elements.

__call__

< source >

( input_ids: Array scores: Array cur_len: int )

class transformers.FlaxTopPLogitsWarper

< source >

( top_p: float filter_value: float = -inf min_tokens_to_keep: int = 1 )

Parameters

FlaxLogitsWarper that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.

__call__

< source >

( input_ids: Array scores: Array cur_len: int )

class transformers.FlaxWhisperTimeStampLogitsProcessor

< source >

( generate_config model_config decoder_input_length )

Parameters

Whisper specific Processor. This processor can be used to force a list of tokens. The processor will set their log probs to inf so that they are sampled at their corresponding index.

StoppingCriteria

A StoppingCriteria can be used to change when to stop generation (other than EOS token). Please note that this is exclusively available to our PyTorch implementations.

Abstract base class for all stopping criteria that can be applied during generation.

If your stopping criteria depends on the scores input, make sure you pass return_dict_in_generate=True, output_scores=True to generate.

__call__

< source >

( input_ids: LongTensor scores: FloatTensor **kwargs ) → torch.BoolTensor. (torch.BoolTensor of shape (batch_size, 1))

Parameters

Returns

torch.BoolTensor. (torch.BoolTensor of shape (batch_size, 1))

True indicates we stop generation for a particular row.False indicates we should continue.

class transformers.StoppingCriteriaList

< source >

( iterable = () )

__call__

< source >

( input_ids: LongTensor scores: FloatTensor **kwargs ) → torch.BoolTensor. (torch.BoolTensor of shape (batch_size, 1))

Parameters

Returns

torch.BoolTensor. (torch.BoolTensor of shape (batch_size, 1))

True indicates we stop generation for a particular row.False indicates we should continue.

class transformers.MaxLengthCriteria

< source >

( max_length: int max_position_embeddings: typing.Optional[int] = None )

Parameters

This class can be used to stop generation whenever the full generated number of tokens exceeds max_length. Keep in mind for decoder-only type of transformers, this will include the initial prompted tokens.

__call__

< source >

( input_ids: LongTensor scores: FloatTensor **kwargs ) → torch.BoolTensor. (torch.BoolTensor of shape (batch_size, 1))

Parameters

Returns

torch.BoolTensor. (torch.BoolTensor of shape (batch_size, 1))

True indicates we stop generation for a particular row.False indicates we should continue.

class transformers.MaxTimeCriteria

< source >

( max_time: float initial_timestamp: typing.Optional[float] = None )

Parameters

This class can be used to stop generation whenever the full generation exceeds some amount of time. By default, the time will start being counted when you initialize this function. You can override this by passing aninitial_time.

__call__

< source >

( input_ids: LongTensor scores: FloatTensor **kwargs ) → torch.BoolTensor. (torch.BoolTensor of shape (batch_size, 1))

Parameters

Returns

torch.BoolTensor. (torch.BoolTensor of shape (batch_size, 1))

True indicates we stop generation for a particular row.False indicates we should continue.

class transformers.StopStringCriteria

< source >

( tokenizer: PreTrainedTokenizerBase stop_strings: typing.Union[str, typing.List[str]] )

Parameters

This class can be used to stop generation whenever specific string sequences are generated. It preprocesses the strings together with the tokenizer vocab to find positions where tokens can validly complete the stop strings.

Generation is stopped as soon as a token is generated that completes any of the stop strings. We want to catch any instance in which the stop string would be present in the decoded output, which means we must also catch cases with “overhangs” off one or both ends. To make this more concrete, for the stop string “stop”, any of the following token sequences would trigger the match:

Note that a match will only be triggered if the stop string is at the end of the generated sequence. In other words, these sequences will not trigger a match:

The reason these are not a match is that the stop string does not overlap with the final token. If you can remove one or more tokens from the end of the sequence without destroying the stop string, then this criterion will not match that stop string. This is by design; because this check is run after each token is generated, we can’t miss a valid stop string if one is generated, but we don’t want to halt generation just because the stop string exists somewhere in the past input_ids.

How is the match actually performed, though? We do it in quite a confusing way, because we want the entire match process to be compilable with Torch or XLA, which means we cannot use standard string methods. However, it is possible, with some work, to do string matching with pure tensor operations. We’ll begin by describing the algorithm we use with standard string operations, and then at the end we’ll explain how this is converted to pure tensor operations.

The key to the algorithm is an observation: Because the stop string must overlap with the end of the token sequence, we can start at the end of the sequence and work backwards. Specifically, we check that there is an overlap between the start of the final token and the end of the stop_string, or to put it another way, stop_string[-i:] == token[:i] for some i > 0. If you look at the positive examples above, you’ll see the last token in all of them fulfills this property:

It’s impossible to construct a matching sequence that does not have this property (feel free to verify this yourself). However, although this overlap between the start of the final token and the end of the stop string is necessary for a match, it is not sufficient. We also need to check that the rest of the token sequence is consistent with the stop string.

How do we do that? Let’s use [“s”, “to”, “pped”] as an example. We know that the final token, “pped”, has an overlap of 1 with the stop string, “stop”. We then go back to the previous token, “to”. Since we have already matched 1 character from the stop string, the remainder to check is “sto”. We check that the next token “to” matches the end of the remainder, which it does. We have now matched 3 characters from the stop string, and the remainder to match is “s”. We go back to the previous token again, which is also “s”. This is a match, and so we have matched the entire stop string.

How does it work when the tokens run off the start of the stop string, though? Let’s consider the example of [“las”, “topper”]. The final token, “topper”, has an overlap of 3 with the stop string, “stop”. Therefore, the remaining stop string to match is “s”. We go back to the previous token, “las”. Because the remainder to match is just “s”, with length 1, we consider only the final 1 character from the token, which is “s”. This matches the stop string, and so the entire string is matched.

How do we compute these matches with tensor operations, though? Simply: we efficiently precompute the necessary information for all tokens! For every token, we compute:

For example, for the token “pped”, we would compute an end overlap of 1, no internal matching positions, and a length of 4. For the token “to”, we would compute no end overlap, a single internal matching position of 1 (counting from the end), and a length of 2. For the token “s”, we would compute no end overlap, a single internal matching position of 3 (again counting from the end) and a length of 1.

As long as we have this information, we can execute the algorithm above without any string comparison operations. We simply perform the following steps:

Again, consider [“s”, “to”, “pped”] as an example. “pped” has an end overlap of 1, so we can begin a match. We have matched 1 character so far, so we check that the next token “to”, has 1 as a valid position (again, counting from the end). It does, so we add the length of “to” to our position tracker. We have now matched 3 characters, so we check that the next token “s” has 3 as a valid position. It does, so we add its length to the position tracker. The position tracker is now 4, which is the length of the stop string. We have matched the entire stop string.

In the second case, [“las”, “topper”], “topper” has an end overlap of 3, so we can begin a match. We have matched 3 characters so far, so we check that the next token “las” has 3 as a valid position. It does, because we allow tokens to match positions that run off the start of the stop string. We add its length to the position tracker. The position tracker is now 6, which is greater than the length of the stop string! Don’t panic, though - this also counts as a match of the stop string. We have matched the entire stop string.

Examples:

from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-2") model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2") inputs = tokenizer("The biggest states in the USA by land area:", return_tensors="pt")

gen_out = model.generate(**inputs) print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0]) The biggest states in the USA by land area:

gen_out = model.generate(**inputs, stop_strings=["Texas"], tokenizer=tokenizer) print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0]) The biggest states in the USA by land area:

__call__

< source >

( input_ids: LongTensor scores: FloatTensor **kwargs ) → torch.BoolTensor. (torch.BoolTensor of shape (batch_size, 1))

Parameters

Returns

torch.BoolTensor. (torch.BoolTensor of shape (batch_size, 1))

True indicates we stop generation for a particular row.False indicates we should continue.

class transformers.EosTokenCriteria

< source >

( eos_token_id: typing.Union[int, typing.List[int], torch.Tensor] )

Parameters

This class can be used to stop generation whenever the “end-of-sequence” token is generated. By default, it uses the model.generation_config.eos_token_id.

__call__

< source >

( input_ids: LongTensor scores: FloatTensor **kwargs ) → torch.BoolTensor. (torch.BoolTensor of shape (batch_size, 1))

Parameters

Returns

torch.BoolTensor. (torch.BoolTensor of shape (batch_size, 1))

True indicates we stop generation for a particular row.False indicates we should continue.

Constraints

A Constraint can be used to force the generation to include specific tokens or sequences in the output. Please note that this is exclusively available to our PyTorch implementations.

Abstract base class for all constraints that can be applied during generation. It must define how the constraint can be satisfied.

All classes that inherit Constraint must follow the requirement that

completed = False while not completed: _, completed = constraint.update(constraint.advance())

will always terminate (halt).

advance

< source >

( ) → token_ids (Union[int, List[int], None])

Returns

token_ids (Union[int, List[int], None])

When called, returns the token(s) that would take this constraint one step closer to being fulfilled.

copy

< source >

( stateful = False ) → constraint(Constraint)

Parameters

Returns

constraint(Constraint)

The same constraint as the one being called from.

Creates a new instance of this constraint.

Reads in a token and returns whether it creates progress.

Returns the number of remaining steps of advance() in order to complete this constraint.

Resets the state of this constraint to its initialization. We would call this in cases where the fulfillment of a constraint is abrupted by an unwanted token.

Tests whether this constraint has been properly defined.

update

< source >

( token_id: int ) → stepped(bool)

Parameters

Whether this constraint has become one step closer to being fulfuilled. completed(bool): Whether this constraint has been completely fulfilled by this token being generated. reset (bool): Whether this constraint has reset its progress by this token being generated.

Reads in a token and returns booleans that indicate the progress made by it. This function will update the state of this object unlikes does_advance(self, token_id: int).

This isn’t to test whether a certain token will advance the progress; it’s to update its state as if it has been generated. This becomes important if token_id != desired token (refer to else statement in PhrasalConstraint)

class transformers.PhrasalConstraint

< source >

( token_ids: typing.List[int] )

Parameters

Constraint enforcing that an ordered sequence of tokens is included in the output.

class transformers.DisjunctiveConstraint

< source >

( nested_token_ids: typing.List[typing.List[int]] )

Parameters

A special Constraint that is fulfilled by fulfilling just one of several constraints.

class transformers.ConstraintListState

< source >

( constraints: typing.List[transformers.generation.beam_constraints.Constraint] )

Parameters

A class for beam scorers to track its progress through a list of constraints.

The list of tokens to generate such that we can make progress. By “list” we don’t mean the list of token that will fully fulfill a constraint.

Given constraints c_i = {t_ij | j == # of tokens}, If we’re not in the middle of progressing through a specific constraint c_i, we return:

[t_k1 for k in indices of unfulfilled constraints]

If we are in the middle of a constraint, then we return:[t_ij], where i is the index of the inprogress constraint, j is the next step for the constraint.

Though we don’t care which constraint is fulfilled first, if we are in the progress of fulfilling a constraint, that’s the only one we’ll return.

reset

< source >

( token_ids: typing.Optional[typing.List[int]] )

token_ids: the tokens generated thus far to reset the state of the progress through constraints.

BeamSearch

Abstract base class for all beam scorers that are used for ~PreTrainedModel.beam_search and~PreTrainedModel.beam_sample.

process

< source >

( input_ids: LongTensor next_scores: FloatTensor next_tokens: LongTensor next_indices: LongTensor **kwargs ) → UserDict

Parameters

A dictionary composed of the fields as defined above:

finalize

< source >

( input_ids: LongTensor next_scores: FloatTensor next_tokens: LongTensor next_indices: LongTensor max_length: int **kwargs ) → torch.LongTensor of shape (batch_size * num_return_sequences, sequence_length)

Parameters

Returns

torch.LongTensor of shape (batch_size * num_return_sequences, sequence_length)

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.

class transformers.BeamSearchScorer

< source >

( batch_size: int num_beams: int device: device length_penalty: typing.Optional[float] = 1.0 do_early_stopping: typing.Union[bool, str, NoneType] = False num_beam_hyps_to_keep: typing.Optional[int] = 1 num_beam_groups: typing.Optional[int] = 1 max_length: typing.Optional[int] = None )

Parameters

BeamScorer implementing standard beam search decoding.

Adapted in part from Facebook’s XLM beam search code.

Reference for the diverse beam search algorithm and implementation Ashwin Kalyan’s DBS implementation

process

< source >

( input_ids: LongTensor next_scores: FloatTensor next_tokens: LongTensor next_indices: LongTensor pad_token_id: typing.Union[int, torch.Tensor, NoneType] = None eos_token_id: typing.Union[int, typing.List[int], torch.Tensor, NoneType] = None beam_indices: typing.Optional[torch.LongTensor] = None group_index: typing.Optional[int] = 0 decoder_prompt_len: typing.Optional[int] = 0 )

finalize

< source >

( input_ids: LongTensor final_beam_scores: FloatTensor final_beam_tokens: LongTensor final_beam_indices: LongTensor max_length: int pad_token_id: typing.Union[int, torch.Tensor, NoneType] = None eos_token_id: typing.Union[int, typing.List[int], torch.Tensor, NoneType] = None beam_indices: typing.Optional[torch.LongTensor] = None decoder_prompt_len: typing.Optional[int] = 0 )

class transformers.ConstrainedBeamSearchScorer

< source >

( batch_size: int num_beams: int constraints: typing.List[transformers.generation.beam_constraints.Constraint] device: device length_penalty: typing.Optional[float] = 1.0 do_early_stopping: typing.Union[bool, str, NoneType] = False num_beam_hyps_to_keep: typing.Optional[int] = 1 num_beam_groups: typing.Optional[int] = 1 max_length: typing.Optional[int] = None )

Parameters

BeamScorer implementing constrained beam search decoding.

process

< source >

( input_ids: LongTensor next_scores: FloatTensor next_tokens: LongTensor next_indices: LongTensor scores_for_all_vocab: FloatTensor pad_token_id: typing.Union[int, torch.Tensor, NoneType] = None eos_token_id: typing.Union[int, typing.List[int], torch.Tensor, NoneType] = None beam_indices: typing.Optional[torch.LongTensor] = None decoder_prompt_len: typing.Optional[int] = 0 ) → UserDict

Parameters

A dictionary composed of the fields as defined above:

finalize

< source >

( input_ids: LongTensor final_beam_scores: FloatTensor final_beam_tokens: LongTensor final_beam_indices: LongTensor max_length: int pad_token_id: typing.Union[int, torch.Tensor, NoneType] = None eos_token_id: typing.Union[int, typing.List[int], torch.Tensor, NoneType] = None beam_indices: typing.Optional[torch.LongTensor] = None decoder_prompt_len: typing.Optional[int] = 0 )

Streamers

class transformers.TextStreamer

< source >

( tokenizer: 'AutoTokenizer' skip_prompt: bool = False **decode_kwargs )

Parameters

Simple text streamer that prints the token(s) to stdout as soon as entire words are formed.

The API for the streamer classes is still under development and may change in the future.

Examples:

from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer

tok = AutoTokenizer.from_pretrained("openai-community/gpt2") model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") inputs = tok(["An increasing sequence: one,"], return_tensors="pt") streamer = TextStreamer(tok)

_ = model.generate(**inputs, streamer=streamer, max_new_tokens=20) An increasing sequence: one, two, three, four, five, six, seven, eight, nine, ten, eleven,

Flushes any remaining cache and prints a newline to stdout.

on_finalized_text

< source >

( text: str stream_end: bool = False )

Prints the new text to stdout. If the stream is ending, also prints a newline.

Receives tokens, decodes them, and prints them to stdout as soon as they form entire words.

class transformers.TextIteratorStreamer

< source >

( tokenizer: 'AutoTokenizer' skip_prompt: bool = False timeout: Optional[float] = None **decode_kwargs )

Parameters

Streamer that stores print-ready text in a queue, to be used by a downstream application as an iterator. This is useful for applications that benefit from accessing the generated text in a non-blocking way (e.g. in an interactive Gradio demo).

The API for the streamer classes is still under development and may change in the future.

Examples:

from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer from threading import Thread

tok = AutoTokenizer.from_pretrained("openai-community/gpt2") model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") inputs = tok(["An increasing sequence: one,"], return_tensors="pt") streamer = TextIteratorStreamer(tok)

generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=20) thread = Thread(target=model.generate, kwargs=generation_kwargs) thread.start() generated_text = "" for new_text in streamer: ... generated_text += new_text generated_text 'An increasing sequence: one, two, three, four, five, six, seven, eight, nine, ten, eleven,'

on_finalized_text

< source >

( text: str stream_end: bool = False )

Put the new text in the queue. If the stream is ending, also put a stop signal in the queue.

class transformers.AsyncTextIteratorStreamer

< source >

( tokenizer: 'AutoTokenizer' skip_prompt: bool = False timeout: Optional[float] = None **decode_kwargs )

Parameters

Streamer that stores print-ready text in a queue, to be used by a downstream application as an async iterator. This is useful for applications that benefit from accessing the generated text asynchronously (e.g. in an interactive Gradio demo).

The API for the streamer classes is still under development and may change in the future.

Examples:

from transformers import AutoModelForCausalLM, AutoTokenizer, AsyncTextIteratorStreamer from threading import Thread import asyncio

tok = AutoTokenizer.from_pretrained("openai-community/gpt2") model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") inputs = tok(["An increasing sequence: one,"], return_tensors="pt")

async def main(): ...
... streamer = AsyncTextIteratorStreamer(tok) ... generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=20) ... thread = Thread(target=model.generate, kwargs=generation_kwargs) ... thread.start() ... generated_text = "" ... async for new_text in streamer: ... generated_text += new_text print(generated_text) asyncio.run(main()) An increasing sequence: one, two, three, four, five, six, seven, eight, nine, ten, eleven,

on_finalized_text

< source >

( text: str stream_end: bool = False )

Put the new text in the queue. If the stream is ending, also put a stop signal in the queue.

Caches

Base, abstract class for all caches. The actual data structure is specific to each subclass.

update

< source >

( key_states: Tensor value_states: Tensor layer_idx: int cache_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

Parameters

Updates the cache with the new key_states and value_states for the layer layer_idx.

class transformers.CacheConfig

< source >

( cache_implementation: None )

Base class for cache configs

update

< source >

( **kwargs ) → Dict[str, Any]

Parameters

Dictionary containing all the key-value pairs that were not used to update the instance.

Updates attributes of this class instance with attributes from kwargs if they match existing attributes, returning all the unused kwargs.

class transformers.QuantizedCacheConfig

< source >

( backend: str = 'quanto' nbits: typing.Optional[int] = 4 axis_key: typing.Optional[int] = 0 axis_value: typing.Optional[int] = 0 q_group_size: typing.Optional[int] = 64 residual_length: typing.Optional[int] = 128 compute_dtype: typing.Optional[torch.dtype] = torch.float16 device: typing.Optional[str] = 'cpu' )

Parameters

Configuration class for quantized cache settings.

Validates if the arguments passed are correct

class transformers.DynamicCache

< source >

( _distributed_cache_data: typing.Optional[typing.Iterable] = None )

A cache that grows dynamically as more tokens are generated. This is the default for generative models.

It stores the Key and Value states as a list of tensors, one for each layer. The expected shape for each tensor is[batch_size, num_heads, seq_len, head_dim].

Example:

from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache

model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")

inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")

past_key_values = DynamicCache() outputs = model(**inputs, past_key_values=past_key_values, use_cache=True) outputs.past_key_values DynamicCache()

update

< source >

( key_states: Tensor value_states: Tensor layer_idx: int cache_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

Parameters

Updates the cache with the new key_states and value_states for the layer layer_idx.

get_seq_length

< source >

( layer_idx: typing.Optional[int] = 0 )

Returns the sequence length of the cached states. A layer index can be optionally passed.

Reorders the cache for beam search, given the selected beam indices.

Converts the DynamicCache instance into the its equivalent in the legacy cache format. Used for backward compatibility.

from_legacy_cache

< source >

( past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor, torch.FloatTensor]]] = None )

Converts a cache in the legacy cache format into an equivalent DynamicCache. Used for backward compatibility.

class transformers.QuantizedCache

< source >

( cache_config: QuantizedCacheConfig )

A quantizer cache similar to what is described in the KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache paper. It allows the model to generate longer sequence length without allocating too much memory for Key and Value cache by applying quantization.

The cache has two types of storage, one for original precision and one for the quantized cache. A residual length is set as a maximum capacity for the original precision cache. When the length goes beyond maximum capacity, the original precision cache is discarded and moved into the quantized cache. The quantization is done per-channel with a set q_group_size for both Keys and Values, in contrast to what was described in the paper.

It stores Keys and Values a list of quantized tensors (tuples in case we need to store metadata), one for each layer. Additionally, it stores the Key and Value in original precision states as a list of tensors, one for each layer. The size of each tensor is [batch_size, num_heads, seq_len - residual_length, head_dim]

update

< source >

( key_states: Tensor value_states: Tensor layer_idx: int cache_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

get_seq_length

< source >

( layer_idx: typing.Optional[int] = 0 )

Returns the sequence length of the cached states. A layer index can be optionally passed.

class transformers.QuantoQuantizedCache

< source >

( cache_config: CacheConfig )

Parameters

Quantized Cache class that uses quanto as a backend to perform quantization. Current implementation supports int2 and int4 dtypes only.

Example:

from transformers import AutoTokenizer, AutoModelForCausalLM, QuantoQuantizedCache, QuantizedCacheConfig

model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")

inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")

cache_config = QuantizedCacheConfig(nbits=4) past_key_values = QuantoQuantizedCache(cache_config=cache_config) outputs = model(**inputs, past_key_values=past_key_values, use_cache=True) outputs.past_key_values QuantoQuantizedCache()

class transformers.HQQQuantizedCache

< source >

( cache_config: CacheConfig )

Parameters

Quantized Cache class that uses HQQ as a backend to perform quantization. Current implementation supports int2, int4, int8 dtypes.

Example:

from transformers import AutoTokenizer, AutoModelForCausalLM, HQQQuantizedCache, QuantizedCacheConfig

model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")

inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")

cache_config = QuantizedCacheConfig(nbits=4, axis_key=1, axis_value=1) past_key_values = HQQQuantizedCache(cache_config=cache_config) outputs = model(**inputs, past_key_values=past_key_values, use_cache=True) outputs.past_key_values HQQQuantizedCache()

class transformers.SinkCache

< source >

( window_length: int num_sink_tokens: int )

Parameters

Deprecated.

A cache that as described in the Attention Sinks paper. It allows the model to generate beyond the length of its context window, without losing fluency in the conversation. As it discards past tokens, the model will lose the ability to generate tokens that depend on the context that was discarded.

It stores the Key and Value states as a list of tensors, one for each layer. The expected shape for each tensor is[batch_size, num_heads, seq_len, head_dim].

Example:

from transformers import AutoTokenizer, AutoModelForCausalLM, SinkCache

model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")

inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")

past_key_values = SinkCache(window_length=256, num_sink_tokens=4) outputs = model(**inputs, past_key_values=past_key_values, use_cache=True) outputs.past_key_values SinkCache()

update

< source >

( key_states: Tensor value_states: Tensor layer_idx: int cache_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

Parameters

Updates the cache with the new key_states and value_states for the layer layer_idx.

get_seq_length

< source >

( layer_idx: typing.Optional[int] = 0 )

Returns the sequence length of the cached states. A layer index can be optionally passed.

Reorders the cache for beam search, given the selected beam indices.

A drop-in replacement for DynamicCache that conserves accelerator(GPU, XPU) memory at the expense of more CPU memory. Useful for generating from models with very long context.

In addition to the default accelerator stream, where all forward() computations happen, this class uses another stream, the prefetch stream, which it creates itself. Since scheduling of operations on separate streams happens independently, this class uses the prefetch stream to asynchronously prefetch the KV cache of layer k+1 when layer k is executing. The movement of the layer k-1 cache to the CPU is handled by the default stream as a simple way to ensure the eviction is scheduled after all computations on that cache are finished.

update

< source >

( key_states: Tensor value_states: Tensor layer_idx: int cache_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

Parameters

Updates the cache with the new key_states and value_states for the layer layer_idx.

Starts prefetching the next layer cache

Moves the previous layer cache to the CPU

class transformers.StaticCache

< source >

( config: PretrainedConfig max_batch_size: int max_cache_len: typing.Optional[int] = None device: typing.Union[torch.device, str, NoneType] = None dtype: dtype = torch.float32 layer_device_map: typing.Optional[typing.Dict[int, typing.Union[str, torch.device, int]]] = None )

Parameters

Static Cache class to be used with torch.compile(model) and torch.export().

Example:

from transformers import AutoTokenizer, AutoModelForCausalLM, StaticCache

model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf") tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf")

inputs = tokenizer(text="My name is Llama", return_tensors="pt")

max_generated_length = inputs.input_ids.shape[1] + 10 past_key_values = StaticCache(config=model.config, max_batch_size=1, max_cache_len=max_generated_length, device=model.device, dtype=model.dtype) outputs = model(**inputs, past_key_values=past_key_values, use_cache=True) outputs.past_key_values StaticCache()

update

< source >

( key_states: Tensor value_states: Tensor layer_idx: int cache_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

Parameters

Updates the cache with the new key_states and value_states for the layer layer_idx. It is VERY important to index using a tensor, otherwise you introduce a copy to the device.

get_seq_length

< source >

( layer_idx: typing.Optional[int] = 0 )

Returns the sequence length of the cached states that were seen by the model.

Resets the cache values while preserving the objects

class transformers.OffloadedStaticCache

< source >

( config: PretrainedConfig max_batch_size: int max_cache_len: typing.Optional[int] device: typing.Union[str, torch.device] dtype: typing.Optional[torch.dtype] = None offload_device: typing.Union[str, torch.device] = device(type='cpu') layer_device_map: typing.Optional[typing.Dict[int, typing.Union[str, torch.device, int]]] = None )

Parameters

Static cache class to be used with torch.compile(model) that offloads to the CPU or another device.

Example:

from transformers import AutoTokenizer, AutoModelForCausalLM, OffloadedStaticCache

model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")

inputs = tokenizer(text="My name is GPT2", return_tensors="pt")

max_generated_length = inputs.input_ids.shape[1] + 10 past_key_values = OffloadedStaticCache(config=model.config, max_batch_size=1, max_cache_len=max_generated_length, device=model.device, dtype=model.dtype) outputs = model(**inputs, past_key_values=past_key_values, use_cache=True) past_kv_length = outputs.past_key_values

update

< source >

( key_states: Tensor value_states: Tensor layer_idx: int cache_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

Parameters

Updates the cache with the new key_states and value_states for the layer layer_idx. It is VERY important to index using a tensor, otherwise you introduce a copy to the device.

get_seq_length

< source >

( layer_idx: typing.Optional[int] = 0 )

Returns the sequence length of the cached states that were seen by the model.

Resets the cache values while preserving the objects.

class transformers.HybridCache

< source >

( config: PretrainedConfig max_batch_size: int max_cache_len: typing.Optional[int] = None device: typing.Union[torch.device, str, NoneType] = None dtype: dtype = torch.float32 layer_device_map: typing.Optional[typing.Dict[int, typing.Union[str, torch.device, int]]] = None )

Parameters

Hybrid Cache class to be used with torch.compile for models that alternate between a local sliding window attention and global attention in every other layer (originally implemented for Gemma2). Under the hood, Hybrid Cache leverages [“SlidingWindowCache”] for sliding window attention and [“StaticCache”] for global attention.For more information, see the documentation of each subcomponent cache class.

Example:

from transformers import AutoTokenizer, AutoModelForCausalLM, HybridCache

model = AutoModelForCausalLM.from_pretrained("google/gemma-2-2b") tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b")

inputs = tokenizer(text="My name is Gemma", return_tensors="pt")

max_generated_length = inputs.input_ids.shape[1] + 10 past_key_values = HybridCache(config=model.config, max_batch_size=1, max_cache_len=max_generated_length, device=model.device, dtype=model.dtype) outputs = model(**inputs, past_key_values=past_key_values, use_cache=True) outputs.past_key_values HybridCache()

update

< source >

( key_states: Tensor value_states: Tensor layer_idx: int cache_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

get_seq_length

< source >

( layer_idx: typing.Optional[int] = 0 )

Resets the cache values while preserving the objects

class transformers.SlidingWindowCache

< source >

( config: PretrainedConfig max_batch_size: int max_cache_len: typing.Optional[int] = None device: typing.Union[torch.device, str, NoneType] = None dtype: dtype = torch.float32 layer_device_map: typing.Optional[typing.Dict[int, typing.Union[str, torch.device, int]]] = None )

Parameters

Sliding Window Cache class to be used with torch.compile for models like Mistral that support sliding window attention. Every time when we try to update the cache, we compute the indices based on cache_position >= self.config.sliding_window - 1, if true(which means the cache can not hold all the old key value states and new states together because of the sliding window constraint), we need to do a cycle shift based on indices to replace the oldest states by the new key value states passed in.

The to_shift is only true once we are above sliding_window. Thus with sliding_window==64:

indices = (slicing + to_shift[-1].sum()-1) % self.config.sliding_window tensor([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0])

We overwrite the cache using these, then we always write at cache_position (clamped to sliding_window)

Example:

from transformers import AutoTokenizer, AutoModelForCausalLM, SlidingWindowCache

model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3") tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3")

inputs = tokenizer(text="My name is Mistral", return_tensors="pt")

max_generated_length = inputs.input_ids.shape[1] + 10 past_key_values = SlidingWindowCache(config=model.config, max_batch_size=1, max_cache_len=max_generated_length, device=model.device, dtype=model.dtype) outputs = model(**inputs, past_key_values=past_key_values, use_cache=True) outputs.past_key_values SlidingWindowCache()

update

< source >

( key_states: Tensor value_states: Tensor layer_idx: int cache_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

class transformers.EncoderDecoderCache

< source >

( self_attention_cache: Cache cross_attention_cache: Cache )

Base, abstract class for all encoder-decoder caches. Can be used to hold combinations of self-attention and cross-attention caches.

Example:

from transformers import AutoProcessor, AutoModelForCausalLM, DynamicCache, EncoderDecoderCache

model = AutoModelForCausalLM.from_pretrained("openai/whisper-small") processor = AutoProcessor.from_pretrained("openai/whisper-small")

inputs = processor(audio=YOUR-AUDIO, return_tensors="pt")

self_attention_cache = DynamicCache() cross_attention_cache = DynamicCache() past_key_values = EncoderDecoderCache(self_attention_cache, cross_attention_cache) outputs = model(**inputs, past_key_values=past_key_values, use_cache=True) outputs.past_key_values EncoderDecoderCache()

get_seq_length

< source >

( layer_idx: typing.Optional[int] = 0 )

Returns the sequence length of the cached states. A layer index can be optionally passed.

Converts the EncoderDecoderCache instance into its equivalent in the legacy cache format.

from_legacy_cache

< source >

( past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )

Converts a cache in the legacy cache format into an equivalent EncoderDecoderCache.

Reorders the cache for beam search, given the selected beam indices.

class transformers.MambaCache

< source >

( config: PretrainedConfig max_batch_size: int dtype: dtype = torch.float16 device: typing.Union[torch.device, str, NoneType] = None )

Parameters

Cache for mamba model which does not have attention mechanism and key value states.

Example:

from transformers import AutoTokenizer, MambaForCausalLM, MambaCache

model = MambaForCausalLM.from_pretrained("state-spaces/mamba-130m-hf") tokenizer = AutoTokenizer.from_pretrained("state-spaces/mamba-130m-hf")

inputs = tokenizer(text="My name is Mamba", return_tensors="pt")

past_key_values = MambaCache(config=model.config, max_batch_size=1, device=model.device, dtype=model.dtype) outputs = model(**inputs, past_key_values=past_key_values, use_cache=True) outputs.past_key_values MambaCache()

update_conv_state

< source >

( layer_idx: int new_conv_state: Tensor cache_position: LongTensor )

update_ssm_state

< source >

( layer_idx: int new_ssm_state: Tensor )

Watermark Utils

class transformers.WatermarkingConfig

< source >

( greenlist_ratio: typing.Optional[float] = 0.25 bias: typing.Optional[float] = 2.0 hashing_key: typing.Optional[int] = 15485863 seeding_scheme: typing.Optional[str] = 'lefthash' context_width: typing.Optional[int] = 1 )

Class that holds arguments for watermark generation and should be passed into GenerationConfig during generate. See this paper for more details on the arguments.

Accepts the following keys:

__call__

( *args **kwargs )

Call self as a function.

class transformers.WatermarkDetector

< source >

( model_config: PretrainedConfig device: str watermarking_config: typing.Union[transformers.generation.configuration_utils.WatermarkingConfig, typing.Dict] ignore_repeated_ngrams: bool = False max_cache_size: int = 128 )

Parameters

Detector for detection of watermark generated text. The detector needs to be given the exact same settings that were given during text generation to replicate the watermark greenlist generation and so detect the watermark. This includes the correct device that was used during text generation, the correct watermarking arguments and the correct tokenizer vocab size. The code was based on the original repo.

See the paper for more information.

Examples:

from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkDetector, WatermarkingConfig

model_id = "openai-community/gpt2" model = AutoModelForCausalLM.from_pretrained(model_id) tok = AutoTokenizer.from_pretrained(model_id) tok.pad_token_id = tok.eos_token_id tok.padding_side = "left"

inputs = tok(["This is the beginning of a long story", "Alice and Bob are"], padding=True, return_tensors="pt") input_len = inputs["input_ids"].shape[-1]

watermarking_config = WatermarkingConfig(bias=2.5, seeding_scheme="selfhash") out_watermarked = model.generate(**inputs, watermarking_config=watermarking_config, do_sample=False, max_length=20) out = model.generate(**inputs, do_sample=False, max_length=20)

detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config=watermarking_config) detection_out_watermarked = detector(out_watermarked, return_dict=True) detection_out = detector(out, return_dict=True) detection_out_watermarked.prediction array([ True, True])

detection_out.prediction array([False, False])

__call__

< source >

( input_ids: LongTensor z_threshold: float = 3.0 return_dict: bool = False ) → WatermarkDetectorOutput or np.array

Parameters

Returns

WatermarkDetectorOutput or np.array

A WatermarkDetectorOutputif return_dict=True otherwise a np.array.

ma

class transformers.BayesianDetectorConfig

< source >

( watermarking_depth: typing.Optional[int] = None base_rate: float = 0.5 **kwargs )

Parameters

This is the configuration class to store the configuration of a BayesianDetectorModel. It is used to instantiate a Bayesian Detector model according to the specified arguments.

Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.

class transformers.BayesianDetectorModel

< source >

( config )

Parameters

Bayesian classifier for watermark detection.

This detector uses Bayes’ rule to compute a watermarking score, which is the sigmoid of the log of ratio of the posterior probabilities P(watermarked|g_values) and P(unwatermarked|g_values). Please see the section on BayesianScore in the paper for further details. Paper URL: https://www.nature.com/articles/s41586-024-08025-4

Note that this detector only works with non-distortionary Tournament-based watermarking using the Bernoulli(0.5) g-value distribution.

This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward

< source >

( g_values: Tensor mask: Tensor labels: typing.Optional[torch.Tensor] = None loss_batch_weight = 1 return_dict = False )

Parameters

Computes the watermarked posterior P(watermarked|g_values).

class transformers.SynthIDTextWatermarkingConfig

< source >

( ngram_len: int keys: typing.List[int] context_history_size: int = 1024 sampling_table_seed: int = 0 sampling_table_size: int = 65536 skip_first_ngram_calls: bool = False debug_mode: bool = False )

Parameters

Class that holds arguments for watermark generation and should be passed into GenerationConfig during generate. See this paper for more details on the arguments.

Examples:

from transformers import AutoModelForCausalLM, AutoTokenizer, SynthIDTextWatermarkingConfig

tokenizer = AutoTokenizer.from_pretrained('google/gemma-2-2b', padding_side="left") model = AutoModelForCausalLM.from_pretrained('google/gemma-2-2b')

watermarking_config = SynthIDTextWatermarkingConfig( ... keys=[654, 400, 836, 123, 340, 443, 597, 160, 57], ... ngram_len=5, ... )

tokenized_prompts = tokenizer(["Once upon a time, "], return_tensors="pt", padding=True) output_sequences = model.generate( ... **tokenized_prompts, watermarking_config=watermarking_config, do_sample=True, max_new_tokens=10 ... ) watermarked_text = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)

SynthID text watermark detector class.

This class has to be initialized with the trained bayesian detector module check script in examples/synthid_text/detector_training.py for example in training/saving/loading this detector module. The folder also showcases example use case of this detector.

Examples:

from transformers import ( ... AutoTokenizer, BayesianDetectorModel, SynthIDTextWatermarkLogitsProcessor, SynthIDTextWatermarkDetector ... )

detector_model = BayesianDetectorModel.from_pretrained("joaogante/dummy_synthid_detector") logits_processor = SynthIDTextWatermarkLogitsProcessor( ... **detector_model.config.watermarking_config, device="cpu" ... ) tokenizer = AutoTokenizer.from_pretrained(detector_model.config.model_name) detector = SynthIDTextWatermarkDetector(detector_model, logits_processor, tokenizer)

test_input = tokenizer(["This is a test input"], return_tensors="pt") is_watermarked = detector(test_input.input_ids)

Compile Utils

class transformers.CompileConfig

< source >

( fullgraph: bool = True dynamic: typing.Optional[bool] = None backend: typing.Union[str, typing.Callable] = 'inductor' mode: str = 'reduce-overhead' options: typing.Optional[dict] = None )

Parameters

Class that holds arguments relative to torch.compile behavior, when using automatic compilation in generate. See torch.compile for more details on the arguments.

Examples:

from transformers import AutoModelForCausalLM, AutoTokenizer, CompileConfig

tokenizer = AutoTokenizer.from_pretrained('google/gemma-2-2b') model = AutoModelForCausalLM.from_pretrained('google/gemma-2-2b').cuda()

compile_config = CompileConfig(dynamic=True)

input = tokenizer.encode("Hello there, how", return_tensors="pt").cuda() output = model.generate( ... input, do_sample=False, max_new_tokens=300, cache_implementation="static", compile_config=compile_config ... ) output_text = tokenizer.batch_decode(output, skip_special_tokens=True)[0]

__call__

( *args **kwargs )

Call self as a function.

< > Update on GitHub