Utilities for Generation
Last updated
Last updated
This page lists all the utility functions used by , , , , , , , and .
Most of those are only useful if you are studying the code of the generate methods in the library.
The output of is an instance of a subclass of . This output is a data structure containing all the information returned by , but that can also be used as tuple or dictionary.
Hereโs an example:
Copied
The generation_output
object is a , as we can see in the documentation of that class below, it means it has the following attributes:
sequences
: the generated sequences of tokens
scores
(optional): the prediction scores of the language modelling head, for each generation step
hidden_states
(optional): the hidden states of the model, for each generation step
attentions
(optional): the attention weights of the model, for each generation step
Here we have the scores
since we passed along output_scores=True
, but we donโt have hidden_states
and attentions
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
Copied
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 None
values. Here, for instance, it has two keys that are sequences
and scores
.
We document here all output types.
( sequences: LongTensor = Nonescores: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneencoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneencoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonedecoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonecross_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonedecoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
sequences (torch.LongTensor
of shape (batch_size, 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
.
scores (tuple(torch.FloatTensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of torch.FloatTensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size, config.vocab_size)
.
encoder_attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple of torch.FloatTensor
(one for each layer of the decoder) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
encoder_hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple of torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
decoder_attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
cross_attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
decoder_hidden_states (tuple(tuple(torch.FloatTensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, generated_length, hidden_size)
.
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)
( sequences: LongTensor = Nonescores: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneattentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonehidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
sequences (torch.LongTensor
of shape (batch_size, 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
.
scores (tuple(torch.FloatTensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of torch.FloatTensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size, config.vocab_size)
.
attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
hidden_states (tuple(tuple(torch.FloatTensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using greedy search.
( sequences: LongTensor = Nonescores: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneencoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneencoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonedecoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonecross_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonedecoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
sequences (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
.
scores (tuple(torch.FloatTensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of torch.FloatTensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size*num_return_sequences, config.vocab_size)
.
encoder_attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple of torch.FloatTensor
(one for each layer of the decoder) of shape (batch_size*num_return_sequences, num_heads, sequence_length, sequence_length)
.
encoder_hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple of torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape (batch_size*num_return_sequences, sequence_length, hidden_size)
.
decoder_attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size*num_return_sequences, num_heads, generated_length, sequence_length)
.
cross_attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
decoder_hidden_states (tuple(tuple(torch.FloatTensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size*num_return_sequences, generated_length, hidden_size)
.
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)
( sequences: LongTensor = Nonescores: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneattentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonehidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
sequences (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
.
scores (tuple(torch.FloatTensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of torch.FloatTensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size*num_return_sequences, config.vocab_size)
.
attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (num_return_sequences*batch_size, num_heads, generated_length, sequence_length)
.
hidden_states (tuple(tuple(torch.FloatTensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (num_return_sequences*batch_size, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using sampling.
( sequences: LongTensor = Nonesequences_scores: typing.Optional[torch.FloatTensor] = Nonescores: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonebeam_indices: typing.Optional[torch.LongTensor] = Noneencoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneencoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonedecoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonecross_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonedecoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
sequences (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
.
sequences_scores (torch.FloatTensor
of shape (batch_size*num_return_sequences)
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Final beam scores of the generated sequences
.
scores (tuple(torch.FloatTensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam. Tuple of torch.FloatTensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size*num_beams, config.vocab_size)
.
beam_indices (torch.LongTensor
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Beam indices of generated token id at each generation step. torch.LongTensor
of shape (batch_size*num_return_sequences, sequence_length)
.
encoder_attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple of torch.FloatTensor
(one for each layer of the decoder) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
encoder_hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple of torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape (batch_size*num_beams*num_return_sequences, sequence_length, hidden_size)
.
decoder_attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size*num_beams*num_return_sequences, num_heads, generated_length, sequence_length)
.
cross_attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
decoder_hidden_states (tuple(tuple(torch.FloatTensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size*num_beams*num_return_sequences, generated_length, hidden_size)
.
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)
( sequences: LongTensor = Nonesequences_scores: typing.Optional[torch.FloatTensor] = Nonescores: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonebeam_indices: typing.Optional[torch.LongTensor] = Noneattentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonehidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
sequences (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
.
sequences_scores (torch.FloatTensor
of shape (batch_size*num_return_sequences)
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Final beam scores of the generated sequences
.
scores (tuple(torch.FloatTensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam. Tuple of torch.FloatTensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size*num_beams*num_return_sequences, config.vocab_size)
.
beam_indices (torch.LongTensor
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Beam indices of generated token id at each generation step. torch.LongTensor
of shape (batch_size*num_return_sequences, sequence_length)
.
attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size*num_beams, num_heads, generated_length, sequence_length)
.
hidden_states (tuple(tuple(torch.FloatTensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size*num_beams*num_return_sequences, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using beam search.
( sequences: LongTensor = Nonesequences_scores: typing.Optional[torch.FloatTensor] = Nonescores: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonebeam_indices: typing.Optional[torch.LongTensor] = Noneencoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneencoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonedecoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonecross_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonedecoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
sequences (torch.LongTensor
of shape (batch_size*num_beams, 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
.
sequences_scores (torch.FloatTensor
of shape (batch_size * num_return_sequence)
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Final beam scores of the generated sequences
.
scores (tuple(torch.FloatTensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam. Tuple of torch.FloatTensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size*num_beams, config.vocab_size)
).
beam_indices (torch.LongTensor
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Beam indices of generated token id at each generation step. torch.LongTensor
of shape (batch_size*num_return_sequences, sequence_length)
.
encoder_attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple of torch.FloatTensor
(one for each layer of the decoder) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
encoder_hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple of torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape (batch_size*num_beams, sequence_length, hidden_size)
.
decoder_attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size*num_beams, num_heads, generated_length, sequence_length)
.
cross_attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
decoder_hidden_states (tuple(tuple(torch.FloatTensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size*num_beams, generated_length, hidden_size)
.
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)
( sequences: LongTensor = Nonesequences_scores: typing.Optional[torch.FloatTensor] = Nonescores: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonebeam_indices: typing.Optional[torch.LongTensor] = Noneattentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonehidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
sequences (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
.
sequences_scores (torch.FloatTensor
of shape (batch_size * num_return_sequence)
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Final beam scores of the generated sequences
.
scores (tuple(torch.FloatTensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam. Tuple of torch.FloatTensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size*num_beams*num_return_sequences, config.vocab_size)
.
beam_indices (torch.LongTensor
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Beam indices of generated token id at each generation step. torch.LongTensor
of shape (batch_size*num_return_sequences, sequence_length)
.
attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size*num_beams, num_heads, generated_length, sequence_length)
.
hidden_states (tuple(tuple(torch.FloatTensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size*num_beams, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using beam sample.
( sequences: LongTensor = Nonescores: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneencoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneencoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonedecoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonecross_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonedecoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
sequences (torch.LongTensor
of shape (batch_size, 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
.
scores (tuple(torch.FloatTensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of torch.FloatTensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size, config.vocab_size)
.
encoder_attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple of torch.FloatTensor
(one for each layer of the decoder) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
encoder_hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple of torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
decoder_attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
cross_attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
decoder_hidden_states (tuple(tuple(torch.FloatTensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using contrastive search.
( sequences: LongTensor = Nonescores: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneattentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonehidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
sequences (torch.LongTensor
of shape (batch_size, 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
.
scores (tuple(torch.FloatTensor)
optional, returned when output_scores=True
is passed or when โ config.output_scores=True
) โ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of torch.FloatTensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size, config.vocab_size)
.
attentions (tuple(tuple(torch.FloatTensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
hidden_states (tuple(tuple(torch.FloatTensor))
, optional, returned when output_hidden_states=True
is โ
passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor
of shape (batch_size, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using contrastive search.
( sequences: Tensor = Nonescores: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Noneencoder_attentions: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Noneencoder_hidden_states: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Nonedecoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonecross_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonedecoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = None )
Parameters
sequences (tf.Tensor
of shape (batch_size, 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
.
scores (tuple(tf.Tensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of tf.Tensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size, config.vocab_size)
.
encoder_attentions (tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple of tf.Tensor
(one for each layer of the decoder) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
encoder_hidden_states (tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple of tf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
decoder_attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
cross_attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
decoder_hidden_states (tuple(tuple(tf.Tensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, generated_length, hidden_size)
.
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)
( sequences: Tensor = Nonescores: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Noneattentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonehidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = None )
Parameters
sequences (tf.Tensor
of shape (batch_size, 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
.
scores (tuple(tf.Tensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of tf.Tensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size, config.vocab_size)
.
attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
hidden_states (tuple(tuple(tf.Tensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using greedy search.
( sequences: Tensor = Nonescores: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Noneencoder_attentions: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Noneencoder_hidden_states: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Nonedecoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonecross_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonedecoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = None )
Parameters
sequences (tf.Tensor
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
.
scores (tuple(tf.Tensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of tf.Tensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size*num_return_sequences, config.vocab_size)
.
encoder_attentions (tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple of tf.Tensor
(one for each layer of the decoder) of shape (batch_size*num_return_sequences, num_heads, sequence_length, sequence_length)
.
encoder_hidden_states (tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple of tf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape (batch_size*num_return_sequences, sequence_length, hidden_size)
.
decoder_attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size*num_return_sequences, num_heads, generated_length, sequence_length)
.
cross_attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
decoder_hidden_states (tuple(tuple(tf.Tensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size*num_return_sequences, generated_length, hidden_size)
.
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)
( sequences: Tensor = Nonescores: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Noneattentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonehidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = None )
Parameters
sequences (tf.Tensor
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
.
scores (tuple(tf.Tensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of tf.Tensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size*num_return_sequences, config.vocab_size)
.
attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (num_return_sequences*batch_size, num_heads, generated_length, sequence_length)
.
hidden_states (tuple(tuple(tf.Tensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (num_return_sequences*batch_size, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using sampling.
( sequences: Tensor = Nonesequences_scores: typing.Optional[tensorflow.python.framework.ops.Tensor] = Nonescores: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Nonebeam_indices: typing.Optional[tensorflow.python.framework.ops.Tensor] = Noneencoder_attentions: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Noneencoder_hidden_states: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Nonedecoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonecross_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonedecoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = None )
Parameters
sequences (tf.Tensor
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
.
sequences_scores (tf.Tensor
of shape (batch_size*num_return_sequences)
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Final beam scores of the generated sequences
.
scores (tuple(tf.Tensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this beam. Tuple of
tf.Tensorwith up to
max_new_tokenselements (one element for each generated token), with each tensor of shape
(batch_size*num_beams, config.vocab_size)`.
beam_indices (tf.Tensor
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Beam indices of generated token id at each generation step. tf.Tensor
of shape (batch_size*num_return_sequences, sequence_length)
.
encoder_attentions (tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple of tf.Tensor
(one for each layer of the decoder) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
encoder_hidden_states (tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple of tf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape (batch_size*num_beams*num_return_sequences, sequence_length, hidden_size)
.
decoder_attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size*num_beams*num_return_sequences, num_heads, generated_length, sequence_length)
.
cross_attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
decoder_hidden_states (tuple(tuple(tf.Tensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size*num_beams*num_return_sequences, generated_length, hidden_size)
.
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)
( sequences: Tensor = Nonesequences_scores: typing.Optional[tensorflow.python.framework.ops.Tensor] = Nonescores: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Nonebeam_indices: typing.Optional[tensorflow.python.framework.ops.Tensor] = Noneattentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonehidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = None )
Parameters
sequences (tf.Tensor
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
.
sequences_scores (tf.Tensor
of shape (batch_size*num_return_sequences)
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Final beam scores of the generated sequences
.
scores (tuple(tf.Tensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this beam. Tuple of tf.Tensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size*num_beams*num_return_sequences, config.vocab_size)
.
beam_indices (tf.Tensor
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Beam indices of generated token id at each generation step. tf.Tensor
of shape (batch_size*num_return_sequences, sequence_length)
.
attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size*num_beams, num_heads, generated_length, sequence_length)
.
hidden_states (tuple(tuple(tf.Tensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size*num_beams*num_return_sequences, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using beam search.
( sequences: Tensor = Nonesequences_scores: typing.Optional[tensorflow.python.framework.ops.Tensor] = Nonescores: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Nonebeam_indices: typing.Optional[tensorflow.python.framework.ops.Tensor] = Noneencoder_attentions: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Noneencoder_hidden_states: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Nonedecoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonecross_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonedecoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = None )
Parameters
sequences (tf.Tensor
of shape (batch_size*num_beams, 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
.
sequences_scores (tf.Tensor
of shape (batch_size * num_return_sequence)
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Final beam scores of the generated sequences
.
scores (tuple(tf.Tensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this beam. Tuple of tf.Tensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size*num_beams, config.vocab_size)
.
beam_indices (tf.Tensor
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Beam indices of generated token id at each generation step. tf.Tensor
of shape (batch_size*num_return_sequences, sequence_length)
.
encoder_attentions (tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple of tf.Tensor
(one for each layer of the decoder) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
encoder_hidden_states (tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple of tf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape (batch_size*num_beams, sequence_length, hidden_size)
.
decoder_attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size*num_beams, num_heads, generated_length, sequence_length)
.
cross_attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
decoder_hidden_states (tuple(tuple(tf.Tensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size*num_beams, generated_length, hidden_size)
.
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)
( sequences: Tensor = Nonesequences_scores: typing.Optional[tensorflow.python.framework.ops.Tensor] = Nonescores: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Nonebeam_indices: typing.Optional[tensorflow.python.framework.ops.Tensor] = Noneattentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonehidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = None )
Parameters
sequences (tf.Tensor
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
.
sequences_scores (tf.Tensor
of shape (batch_size * num_return_sequence)
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Final beam scores of the generated sequences
.
scores (tuple(tf.Tensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this beam. Tuple of tf.Tensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size*num_beams*num_return_sequences, config.vocab_size)
.
beam_indices (tf.Tensor
, optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Beam indices of generated token id at each generation step. tf.Tensor
of shape (batch_size*num_return_sequences, sequence_length)
.
attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size*num_beams, num_heads, generated_length, sequence_length)
.
hidden_states (tuple(tuple(tf.Tensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size*num_beams, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using beam sample.
( sequences: Tensor = Nonescores: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Noneencoder_attentions: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Noneencoder_hidden_states: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Nonedecoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonecross_attentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonedecoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = None )
Parameters
sequences (tf.Tensor
of shape (batch_size, 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
.
scores (tuple(tf.Tensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of tf.Tensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size, config.vocab_size)
.
encoder_attentions (tuple(tf.Tensor)
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple of tf.Tensor
(one for each layer of the decoder) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
encoder_hidden_states (tuple(tf.Tensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple of tf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
decoder_attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
cross_attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
decoder_hidden_states (tuple(tuple(tf.Tensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, generated_length, hidden_size)
.
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)
( sequences: Tensor = Nonescores: typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = Noneattentions: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = Nonehidden_states: typing.Optional[typing.Tuple[typing.Tuple[tensorflow.python.framework.ops.Tensor]]] = None )
Parameters
sequences (tf.Tensor
of shape (batch_size, 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
.
scores (tuple(tf.Tensor)
optional, returned when output_scores=True
is passed or when config.output_scores=True
) โ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of tf.Tensor
with up to max_new_tokens
elements (one element for each generated token), with each tensor of shape (batch_size, config.vocab_size)
.
attentions (tuple(tuple(tf.Tensor))
, optional, returned when output_attentions=True
is passed or config.output_attentions=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, num_heads, generated_length, sequence_length)
.
hidden_states (tuple(tuple(tf.Tensor))
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) โ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of tf.Tensor
of shape (batch_size, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using contrastive search.
( sequences: Array = None )
Parameters
sequences (jnp.ndarray
of shape (batch_size, max_length)
) โ The generated sequences.
Flax Base class for outputs of decoder-only generation models using sampling.
replace
( **updates )
โReturns a new object replacing the specified fields with new values.
( sequences: Array = None )
Parameters
sequences (jnp.ndarray
of shape (batch_size, max_length)
) โ The generated sequences.
Flax Base class for outputs of decoder-only generation models using greedy search.
replace
( **updates )
โReturns a new object replacing the specified fields with new values.
( sequences: Array = Nonescores: Array = None )
Parameters
sequences (jnp.ndarray
of shape (batch_size, max_length)
) โ The generated sequences.
scores (jnp.ndarray
of shape (batch_size,)
) โ The scores (log probabilities) of the generated sequences.
Flax Base class for outputs of decoder-only generation models using greedy search.
replace
( **updates )
โReturns a new object replacing the specified fields with new values.
( input_start_len: intsemantic_vocab_size: intcodebook_size: int )
Parameters
input_start_len (int
) โ The length of the initial input sequence.
semantic_vocab_size (int
) โ Vocabulary size of the semantic part, i.e number of tokens associated to the semantic vocabulary.
codebook_size (int
) โ Number of tokens associated to the codebook.
__call__
( input_ids: LongTensorscores: FloatTensor )
( guidance_scale )
Parameters
guidance_scale (float) โ The guidance scale for classifier free guidance (CFG). CFG is enabled by setting guidance_scale > 1
. Higher guidance scale encourages the model to generate samples that are more closely linked to the input prompt, usually at the expense of poorer quality.
Logits processor 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
.
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( encoder_ngram_size: intencoder_input_ids: LongTensor )
Parameters
encoder_ngram_size (int
) โ All ngrams of size ngram_size
can only occur within the encoder input ids.
encoder_input_ids (int
) โ The encoder_input_ids that should not be repeated within the decoder ids.
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( penalty: floatencoder_input_ids: LongTensor )
Parameters
hallucination_penalty (float
) โ The parameter for hallucination penalty. 1.0 means no penalty.
encoder_input_ids (torch.LongTensor
) โ The encoder_input_ids that should be repeated within the decoder ids.
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( epsilon: floatfilter_value: float = -infmin_tokens_to_keep: int = 1 )
Parameters
epsilon (float
) โ If set to > 0, only the most tokens with probabilities epsilon
or higher are kept for generation.
filter_value (float
, optional, defaults to -float("Inf")
) โ All filtered values will be set to this float value.
min_tokens_to_keep (int
, optional, defaults to 1) โ Minimum number of tokens that cannot be filtered.
Examples:
Copied
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( epsilon: floatfilter_value: float = -infmin_tokens_to_keep: int = 1 )
Parameters
epsilon (float
) โ A float value in the range (0, 1). Hyperparameter used to calculate the dynamic cutoff value, eta
. The suggested values from the paper ranges from 3e-4 to 4e-3 depending on the size of the model.
filter_value (float
, optional, defaults to -float("Inf")
) โ All values that are found to be below the dynamic cutoff value, eta
, are set to this float value. This parameter is useful when logits need to be modified for very low probability tokens that should be excluded from generation entirely.
min_tokens_to_keep (int
, optional, defaults to 1) โ Specifies the minimum number of tokens that must be kept for generation, regardless of their probabilities. For example, if min_tokens_to_keep
is set to 1, at least one token will always be kept for generation, even if all tokens have probabilities below the cutoff eta
.
Examples:
Copied
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( exponential_decay_length_penalty: typing.Tuple[int, float]eos_token_id: typing.Union[int, typing.List[int]]input_ids_seq_length: int )
Parameters
exponential_decay_length_penalty (tuple(int, float)
) โ This tuple shall consist of: (start_index, decay_factor)
where start_index
indicates where penalty starts and decay_factor
represents the factor of exponential decay
eos_token_id (Union[int, List[int]]
) โ The id of the end-of-sequence token. Optionally, use a list to set multiple end-of-sequence tokens.
input_ids_seq_length (int
) โ The length of the input sequence.
Examples:
Copied
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( bos_token_id: int )
Parameters
bos_token_id (int
) โ The id of the token to force as the first generated token.
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( max_length: inteos_token_id: typing.Union[int, typing.List[int]] )
Parameters
max_length (int
) โ The maximum length of the sequence to be generated.
eos_token_id (Union[int, List[int]]
) โ The id of the token to force as the last generated token when max_length
is reached. Optionally, use a list to set multiple end-of-sequence tokens.
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( 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 inf
so that they are sampled at their corresponding index.
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( diversity_penalty: floatnum_beams: intnum_beam_groups: int )
Parameters
diversity_penalty (float
) โ This value is subtracted from a beamโs score if it generates a token same as any beam from other group at a particular time. Note that diversity_penalty
is only effective if group beam search is enabled. The penalty applied to a beamโs score when it generates a token that has already been chosen by another beam within the same group during the same time step. A higher diversity_penalty
will enforce greater diversity among the beams, making it less likely for multiple beams to choose the same token. Conversely, a lower penalty will allow beams to more freely choose similar tokens. Adjusting this value can help strike a balance between diversity and natural likelihood.
num_beams (int
) โ Number of beams used for group beam search. Beam search is a method used that maintains beams (or โmultiple hypothesesโ) at each step, expanding each one and keeping the top-scoring sequences. A higher num_beams
will explore more potential sequences. This can increase chances of finding a high-quality output but also increases computational cost.
Diverse beam search can be particularly useful in scenarios where a variety of different outputs is desired, rather than multiple similar sequences. It allows the model to explore different generation paths and provides a broader coverage of possible outputs.
This logits processor can be resource-intensive, especially when using large models or long sequences.
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.
How It Works:
Grouping Beams: Beams are divided into groups. Each group selects tokens independently of the others.
Penalizing Repeated Tokens: If a beam in a group selects a token already chosen by another group in the same step, a penalty is applied to that tokenโs score.
Promoting Diversity: This penalty discourages beams within a group from selecting the same tokens as beams in other groups.
Benefits:
Diverse Outputs: Produces a variety of different sequences.
Exploration: Allows the model to explore different paths.
Examples:
Copied
__call__
( input_ids: LongTensorscores: FloatTensorcurrent_tokens: LongTensorbeam_group_idx: int ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
current_tokens (torch.LongTensor
of shape (batch_size)
) โ Indices of input sequence tokens in the vocabulary, corresponding to the tokens selected by the other beam groups in the current generation step.
beam_group_idx (int
) โ The index of the beam group currently being processed.
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( )
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( )
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
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__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( iterable = () )
__call__
( input_ids: LongTensorscores: FloatTensor**kwargs ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
kwargs (Dict[str, Any]
, optional) โ Additional kwargs that are specific to a logits processor.
Returns
torch.FloatTensor
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__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( min_length: inteos_token_id: typing.Union[int, typing.List[int]] )
Parameters
min_length (int
) โ The minimum length below which the score of eos_token_id
is set to -float("Inf")
.
eos_token_id (Union[int, List[int]]
) โ The id of the end-of-sequence token. Optionally, use a list to set multiple end-of-sequence tokens.
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( prompt_length_to_skip: intmin_new_tokens: inteos_token_id: typing.Union[int, typing.List[int]] )
Parameters
prompt_length_to_skip (int
) โ The input tokens length. Not a valid argument when used with generate
as it will automatically assign the input length.
min_new_tokens (int
) โ The minimum new tokens length below which the score of eos_token_id
is set to -float("Inf")
.
eos_token_id (Union[int, List[int]]
) โ The id of the end-of-sequence token. Optionally, use a list to set multiple end-of-sequence tokens.
Examples:
Copied
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( bad_words_ids: typing.List[typing.List[int]]eos_token_id: typing.Union[int, typing.List[int]] )
Parameters
bad_words_ids (List[List[int]]
) โ List of list of token ids that are not allowed to be generated.
eos_token_id (Union[int, List[int]]
) โ The id of the end-of-sequence token. Optionally, use a list to set multiple end-of-sequence tokens.
Examples:
Copied
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( ngram_size: int )
Parameters
ngram_size (int
) โ All ngrams of size ngram_size
can only occur once.
Examples:
Copied
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( prefix_allowed_tokens_fn: typing.Callable[[int, torch.Tensor], typing.List[int]]num_beams: int )
Parameters
prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], List[int]]
) โ This function constraints the beam search to allowed tokens only at each step. This function takes 2 arguments inputs_ids
and the batch ID batch_id
. It has to return a list with the allowed tokens for the next generation step conditioned on the previously generated tokens inputs_ids
and the batch ID batch_id
.
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( penalty: float )
Parameters
Examples:
Copied
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( sequence_bias: typing.Dict[typing.Tuple[int], float] )
Parameters
sequence_bias (Dict[Tuple[int], float]
) โ Dictionary that maps a sequence of tokens to its bias term. Positive biases increase the odds of the sequence being selected, while negative biases do the opposite. If a sequence has a length of 1, its bias will always be applied. Otherwise, the bias will only be applied if the sequence in question is about to be completed (in the token selection step after this processor is applied).
Examples:
Copied
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( begin_suppress_tokensbegin_index )
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( 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__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( temperature: float )
Parameters
temperature (float
) โ Strictly positive float value used to modulate the logits distribution. A value smaller than 1
decreases randomness (and vice versa), with 0
being equivalent to shifting all probability mass to the most likely token.
Make sure that do_sample=True
is included in the generate
arguments otherwise the temperature value wonโt have any effect.
Examples:
Copied
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( top_k: intfilter_value: float = -infmin_tokens_to_keep: int = 1 )
Parameters
top_k (int
) โ The number of highest probability vocabulary tokens to keep for top-k-filtering.
filter_value (float
, optional, defaults to -float("Inf")
) โ All filtered values will be set to this float value.
min_tokens_to_keep (int
, optional, defaults to 1) โ Minimum number of tokens that cannot be filtered.
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( top_p: floatfilter_value: float = -infmin_tokens_to_keep: int = 1 )
Parameters
top_p (float
) โ If set to < 1, only the smallest set of most probable tokens with probabilities that add up to top_p
or higher are kept for generation.
filter_value (float
, optional, defaults to -float("Inf")
) โ All filtered values will be set to this float value.
min_tokens_to_keep (int
, optional, defaults to 1) โ Minimum number of tokens that cannot be filtered.
Examples:
Copied
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( mass: float = 0.9filter_value: float = -infmin_tokens_to_keep: int = 1 )
Parameters
mass (float
) โ Value of typical_p between 0 and 1 inclusive, defaults to 0.9.
filter_value (float
, optional, defaults to -float("Inf")
) โ All filtered values will be set to this float value.
min_tokens_to_keep (int
, optional, defaults to 1) โ Minimum number of tokens that cannot be filtered.
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( guidance_scale: floatmodelunconditional_ids: typing.Optional[torch.LongTensor] = Noneunconditional_attention_mask: typing.Optional[torch.LongTensor] = Noneuse_cache: typing.Optional[bool] = True )
Parameters
guidance_scale (float
) โ The guidance scale for classifier free guidance (CFG). CFG is enabled by setting guidance_scale != 1
. Higher guidance scale encourages the model to generate samples that are more closely linked to the input prompt, usually at the expense of poorer quality. A value smaller than 1 has the opposite effect, while making the negative prompt provided with negative_prompt_ids (if any) act as a positive prompt.
unconditional_ids (torch.LongTensor
of shape (batch_size, sequence_length)
, optional) โ Indices of input sequence tokens in the vocabulary for the unconditional branch. If unset, will default to the last token of the prompt.
unconditional_attention_mask (torch.LongTensor
of shape (batch_size, sequence_length)
, optional) โ Attention mask for unconditional_ids.
model (PreTrainedModel
) โ The model computing the unconditional scores. Supposedly the same as the one computing the conditional scores. Both models must use the same tokenizer.
smooth_factor (float
, optional) โ The interpolation weight for CFG Rescale. 1 means no rescaling, 0 reduces to the conditional scores without CFG. Turn it lower if the output degenerates.
use_cache (bool
, optional) โ Whether to cache key/values during the negative prompt forward pass.
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.
Examples:
Copied
__call__
( input_idsscores )
( generate_config )
Parameters
generate_config (GenerateConfig
) โ The generate config used to generate the output. The following parameters are required: eos_token_id (int
, optional, defaults to 50257): The id of the end-of-sequence token. no_timestamps_token_id (int
, optional, defaults to 50363): The id of the "<|notimestamps|>"
token. max_initial_timestamp_index (int
, optional, defaults to 1): Used to set the maximum value of the initial timestamp. This is used to prevent the model from predicting timestamps that are too far in the future.
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.
__call__
( input_ids: LongTensorscores: FloatTensor ) โ torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
( bos_token_id: int )
Parameters
bos_token_id (int
) โ The id of the token to force as the first generated token.
__call__
( input_ids: Tensorscores: Tensorcur_len: int )
( max_length: inteos_token_id: int )
Parameters
max_length (int
) โ The maximum length of the sequence to be generated.
eos_token_id (int
) โ The id of the token to force as the last generated token when max_length
is reached.
__call__
( input_ids: Tensorscores: Tensorcur_len: int )
( 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__
( input_ids: Tensorscores: Tensorcur_len: int )
( )
Abstract base class for all logit processors that can be applied during generation.
__call__
( input_ids: Tensorscores: Tensorcur_len: int ) โ tf.Tensor
of shape (batch_size, config.vocab_size)
Parameters
input_ids (tf.Tensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
scores (tf.Tensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search.
cur_len (int
) โ The current length of valid input sequence tokens. In the TF implementation, the input_idsโ sequence length is the maximum length generate can produce, and we need to know which of its tokens are valid.
kwargs (Dict[str, Any]
, optional) โ Additional logits processor specific kwargs.
Returns
tf.Tensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
TF method for processing logits.
( iterable = () )
__call__
( input_ids: Tensorscores: Tensorcur_len: int**kwargs ) โ tf.Tensor
of shape (batch_size, config.vocab_size)
Parameters
input_ids (tf.Tensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
scores (tf.Tensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search.
cur_len (int
) โ The current length of valid input sequence tokens. In the TF implementation, the input_idsโ sequence length is the maximum length generate can produce, and we need to know which of its tokens are valid.
kwargs (Dict[str, Any]
, optional) โ Additional logits processor specific kwargs.
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__
( input_ids: Tensorscores: Tensorcur_len: int ) โ tf.Tensor
of shape (batch_size, config.vocab_size)
Parameters
input_ids (tf.Tensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
scores (tf.Tensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search.
cur_len (int
) โ The current length of valid input sequence tokens. In the TF implementation, the input_idsโ sequence length is the maximum length generate can produce, and we need to know which of its tokens are valid.
kwargs (Dict[str, Any]
, optional) โ Additional logits processor specific kwargs.
Returns
tf.Tensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
TF method for warping logits.
( min_length: inteos_token_id: int )
Parameters
min_length (int
) โ The minimum length below which the score of eos_token_id
is set to -float("Inf")
.
eos_token_id (int
) โ The id of the end-of-sequence token.
__call__
( input_ids: Tensorscores: Tensorcur_len: int )
( bad_words_ids: typing.List[typing.List[int]]eos_token_id: int )
Parameters
eos_token_id (int
) โ The id of the end-of-sequence token.
__call__
( input_ids: Tensorscores: Tensorcur_len: int )
( ngram_size: int )
Parameters
ngram_size (int
) โ All ngrams of size ngram_size
can only occur once.
__call__
( input_ids: Tensorscores: Tensorcur_len: int )
( penalty: float )
Parameters
__call__
( input_ids: Tensorscores: Tensorcur_len: int )
( begin_suppress_tokensbegin_index )
__call__
( input_ids: Tensorscores: Tensorcur_len: int )
( 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__
( input_ids: Tensorscores: Tensorcur_len: int )
( temperature: float )
Parameters
temperature (float
) โ The value used to module the logits distribution.
__call__
( input_ids: Tensorscores: Tensorcur_len: int )
( top_k: intfilter_value: float = -infmin_tokens_to_keep: int = 1 )
Parameters
top_k (int
) โ The number of highest probability vocabulary tokens to keep for top-k-filtering.
filter_value (float
, optional, defaults to -float("Inf")
) โ All filtered values will be set to this float value.
min_tokens_to_keep (int
, optional, defaults to 1) โ Minimum number of tokens that cannot be filtered.
__call__
( input_ids: Tensorscores: Tensorcur_len: int )
( top_p: floatfilter_value: float = -infmin_tokens_to_keep: int = 1 )
Parameters
top_p (float
) โ If set to < 1, only the smallest set of most probable tokens with probabilities that add up to top_p
or higher are kept for generation.
filter_value (float
, optional, defaults to -float("Inf")
) โ All filtered values will be set to this float value.
min_tokens_to_keep (int
, optional, defaults to 1) โ Minimum number of tokens that cannot be filtered.
__call__
( input_ids: Tensorscores: Tensorcur_len: int )
( bos_token_id: int )
Parameters
bos_token_id (int
) โ The id of the token to force as the first generated token.
__call__
( input_ids: Arrayscores: Arraycur_len: int )
( max_length: inteos_token_id: int )
Parameters
max_length (int
) โ The maximum length of the sequence to be generated.
eos_token_id (int
) โ The id of the token to force as the last generated token when max_length
is reached.
__call__
( input_ids: Arrayscores: Arraycur_len: int )
( force_token_map )
Parameters
force_token_map (list
) โ Map giving token ids and indices where they will be forced to be sampled.
__call__
( input_ids: Arrayscores: Arraycur_len: int )
( )
Abstract base class for all logit processors that can be applied during generation.
__call__
( input_ids: Arrayscores: Array ) โ jnp.ndarray
of shape (batch_size, config.vocab_size)
Parameters
input_ids (jnp.ndarray
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
scores (jnp.ndarray
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
kwargs (Dict[str, Any]
, optional) โ Additional logits processor specific kwargs.
Returns
jnp.ndarray
of shape (batch_size, config.vocab_size)
The processed prediction scores.
Flax method for processing logits.
( iterable = () )
__call__
( input_ids: Arrayscores: Arraycur_len: int**kwargs ) โ jnp.ndarray
of shape (batch_size, config.vocab_size)
Parameters
input_ids (jnp.ndarray
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
scores (jnp.ndarray
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
kwargs (Dict[str, Any]
, optional) โ Additional logits processor specific kwargs.
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__
( input_ids: Arrayscores: Array ) โ jnp.ndarray
of shape (batch_size, config.vocab_size)
Parameters
input_ids (jnp.ndarray
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
scores (jnp.ndarray
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search
kwargs (Dict[str, Any]
, optional) โ Additional logits processor specific kwargs.
Returns
jnp.ndarray
of shape (batch_size, config.vocab_size)
The processed prediction scores.
Flax method for warping logits.
( min_length: inteos_token_id: int )
Parameters
min_length (int
) โ The minimum length below which the score of eos_token_id
is set to -float("Inf")
.
eos_token_id (int
) โ The id of the end-of-sequence token.
__call__
( input_ids: Arrayscores: Arraycur_len: int )
( begin_suppress_tokensbegin_index )
Parameters
begin_suppress_tokens (List[int]
) โ Tokens to not sample.
begin_index (int
) โ Index where the tokens are suppressed.
__call__
( input_idsscorescur_len: int )
( suppress_tokens: list )
Parameters
suppress_tokens (list
) โ Tokens to not sample.
__call__
( input_ids: Arrayscores: Arraycur_len: int )
( temperature: float )
Parameters
temperature (float
) โ The value used to module the logits distribution.
__call__
( input_ids: Arrayscores: Arraycur_len: int )
( top_k: intfilter_value: float = -infmin_tokens_to_keep: int = 1 )
Parameters
top_k (int
) โ The number of highest probability vocabulary tokens to keep for top-k-filtering.
filter_value (float
, optional, defaults to -float("Inf")
) โ All filtered values will be set to this float value.
min_tokens_to_keep (int
, optional, defaults to 1) โ Minimum number of tokens that cannot be filtered.
__call__
( input_ids: Arrayscores: Arraycur_len: int )
( top_p: floatfilter_value: float = -infmin_tokens_to_keep: int = 1 )
Parameters
top_p (float
) โ If set to < 1, only the smallest set of most probable tokens with probabilities that add up to top_p
or higher are kept for generation.
filter_value (float
, optional, defaults to -float("Inf")
) โ All filtered values will be set to this float value.
min_tokens_to_keep (int
, optional, defaults to 1) โ Minimum number of tokens that cannot be filtered.
__call__
( input_ids: Arrayscores: Arraycur_len: int )
( generate_configmodel_configdecoder_input_length )
Parameters
generate_config (GenerateConfig
) โ The generate config used to generate the output. The following parameters are required: eos_token_id (int
, optional, defaults to 50257): The id of the end-of-sequence token. no_timestamps_token_id (int
, optional, defaults to 50363): The id of the "<|notimestamps|>"
token. max_initial_timestamp_index (int
, optional, defaults to 1): Used to set the maximum value of the initial timestamp. This is used to prevent the model from predicting timestamps that are too far in the future.
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.
__call__
( input_idsscorescur_len )
( )
Abstract base class for all stopping criteria that can be applied during generation.
__call__
( input_ids: LongTensorscores: FloatTensor**kwargs )
Parameters
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax.
kwargs (Dict[str, Any]
, optional) โ Additional stopping criteria specific kwargs.
( iterable = () )
__call__
( input_ids: LongTensorscores: FloatTensor**kwargs )
Parameters
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax.
kwargs (Dict[str, Any]
, optional) โ Additional stopping criteria specific kwargs.
( max_length: intmax_position_embeddings: typing.Optional[int] = None )
Parameters
max_length (int
) โ The maximum length that the output sequence can have in number of tokens.
max_position_embeddings (int
, optional
) โ The maximum model length, as defined by the modelโs config.max_position_embeddings
attribute.
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__
( input_ids: LongTensorscores: FloatTensor**kwargs )
Parameters
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax.
kwargs (Dict[str, Any]
, optional) โ Additional stopping criteria specific kwargs.
( max_time: floatinitial_timestamp: typing.Optional[float] = None )
Parameters
max_time (float
) โ The maximum allowed time in seconds for the generation.
initial_time (float
, optional, defaults to time.time()
) โ The start of the generation allowed time.
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 an initial_time
.
__call__
( input_ids: LongTensorscores: FloatTensor**kwargs )
Parameters
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
scores (torch.FloatTensor
of shape (batch_size, config.vocab_size)
) โ Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax.
kwargs (Dict[str, Any]
, optional) โ Additional stopping criteria specific kwargs.
( )
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
Copied
will always terminate (halt).
advance
( ) โ token_ids(torch.tensor
)
Returns
token_ids(torch.tensor
)
Must be a tensor of a list of indexable tokens, not some integer.
When called, returns the token that would take this constraint one step closer to being fulfilled.
copy
( stateful = False ) โ constraint(Constraint
)
Returns
constraint(Constraint
)
The same constraint as the one being called from.
Creates a new instance of this constraint.
does_advance
( token_id: int )
Reads in a token and returns whether it creates progress.
remaining
( )
Returns the number of remaining steps of advance()
in order to complete this constraint.
reset
( )
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.
test
( )
Tests whether this constraint has been properly defined.
update
( token_id: int ) โ stepped(bool
)
Returns
stepped(bool
)
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)
( token_ids: typing.List[int] )
Parameters
token_ids (List[int]
) โ The id of the token that must be generated by the output.
( nested_token_ids: typing.List[typing.List[int]] )
Parameters
nested_token_ids (List[List[int]]
) โ a list of words, where each word is a list of ids. This constraint
is fulfilled by generating just one from the list of words. โ
( constraints: typing.List[transformers.generation.beam_constraints.Constraint] )
Parameters
A class for beam scorers to track its progress through a list of constraints.
advance
( )
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
( token_ids: typing.Optional[typing.List[int]] )
token_ids: the tokens generated thus far to reset the state of the progress through constraints.
( )
process
( input_ids: LongTensornext_scores: FloatTensornext_tokens: LongTensornext_indices: LongTensor**kwargs ) โ UserDict
Parameters
input_ids (torch.LongTensor
of shape (batch_size * num_beams, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
next_scores (torch.FloatTensor
of shape (batch_size, 2 * num_beams)
) โ Current scores of the top 2 * num_beams
non-finished beam hypotheses.
next_tokens (torch.LongTensor
of shape (batch_size, 2 * num_beams)
) โ input_ids
of the tokens corresponding to the top 2 * num_beams
non-finished beam hypotheses.
next_indices (torch.LongTensor
of shape (batch_size, 2 * num_beams)
) โ Beam indices indicating to which beam hypothesis the next_tokens
correspond.
pad_token_id (int
, optional) โ The id of the padding token.
eos_token_id (Union[int, List[int]]
, optional) โ The id of the end-of-sequence token. Optionally, use a list to set multiple end-of-sequence tokens.
beam_indices (torch.LongTensor
, optional) โ Beam indices indicating to which beam hypothesis each token correspond.
Returns
UserDict
A dictionary composed of the fields as defined above:
next_beam_scores (torch.FloatTensor
of shape (batch_size * num_beams)
) โ Updated scores of all non-finished beams.
next_beam_tokens (torch.FloatTensor
of shape (batch_size * num_beams)
) โ Next tokens to be added to the non-finished beam_hypotheses.
next_beam_indices (torch.FloatTensor
of shape (batch_size * num_beams)
) โ Beam indices indicating to which beam the next tokens shall be added.
finalize
( input_ids: LongTensornext_scores: FloatTensornext_tokens: LongTensornext_indices: LongTensormax_length: int**kwargs ) โ torch.LongTensor
of shape (batch_size * num_return_sequences, sequence_length)
Parameters
input_ids (torch.LongTensor
of shape (batch_size * num_beams, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
final_beam_scores (torch.FloatTensor
of shape (batch_size * num_beams)
) โ The final scores of all non-finished beams.
final_beam_tokens (torch.FloatTensor
of shape (batch_size * num_beams)
) โ The last tokens to be added to the non-finished beam_hypotheses.
final_beam_indices (torch.FloatTensor
of shape (batch_size * num_beams)
) โ The beam indices indicating to which beam the final_beam_tokens
shall be added.
pad_token_id (int
, optional) โ The id of the padding token.
eos_token_id (Union[int, List[int]]
, optional) โ The id of the end-of-sequence token. Optionally, use a list to set multiple end-of-sequence tokens.
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
.
( batch_size: intnum_beams: intdevice: devicelength_penalty: typing.Optional[float] = 1.0do_early_stopping: typing.Union[str, bool, NoneType] = Falsenum_beam_hyps_to_keep: typing.Optional[int] = 1num_beam_groups: typing.Optional[int] = 1max_length: typing.Optional[int] = None )
Parameters
batch_size (int
) โ Batch Size of input_ids
for which standard beam search decoding is run in parallel.
num_beams (int
) โ Number of beams for beam search.
device (torch.device
) โ Defines the device type (e.g., "cpu"
or "cuda"
) on which this instance of BeamSearchScorer
will be allocated.
length_penalty (float
, optional, defaults to 1.0) โ Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), length_penalty
> 0.0 promotes longer sequences, while length_penalty
< 0.0 encourages shorter sequences.
do_early_stopping (bool
or str
, optional, defaults to False
) โ Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values: True
, where the generation stops as soon as there are num_beams
complete candidates; False
, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates; "never"
, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).
num_beam_hyps_to_keep (int
, optional, defaults to 1) โ The number of beam hypotheses that shall be returned upon calling ~transformer.BeamSearchScorer.finalize
.
max_length (int
, optional) โ The maximum length of the sequence to be generated.
process
( input_ids: LongTensornext_scores: FloatTensornext_tokens: LongTensornext_indices: LongTensorpad_token_id: typing.Optional[int] = Noneeos_token_id: typing.Union[int, typing.List[int], NoneType] = Nonebeam_indices: typing.Optional[torch.LongTensor] = Nonegroup_index: typing.Optional[int] = 0 )
finalize
( input_ids: LongTensorfinal_beam_scores: FloatTensorfinal_beam_tokens: LongTensorfinal_beam_indices: LongTensormax_length: intpad_token_id: typing.Optional[int] = Noneeos_token_id: typing.Union[int, typing.List[int], NoneType] = Nonebeam_indices: typing.Optional[torch.LongTensor] = None )
( batch_size: intnum_beams: intconstraints: typing.List[transformers.generation.beam_constraints.Constraint]device: devicelength_penalty: typing.Optional[float] = 1.0do_early_stopping: typing.Union[str, bool, NoneType] = Falsenum_beam_hyps_to_keep: typing.Optional[int] = 1num_beam_groups: typing.Optional[int] = 1max_length: typing.Optional[int] = None )
Parameters
batch_size (int
) โ Batch Size of input_ids
for which standard beam search decoding is run in parallel.
num_beams (int
) โ Number of beams for beam search.
device (torch.device
) โ Defines the device type (e.g., "cpu"
or "cuda"
) on which this instance of BeamSearchScorer
will be allocated.
length_penalty (float
, optional, defaults to 1.0) โ Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), length_penalty
> 0.0 promotes longer sequences, while length_penalty
< 0.0 encourages shorter sequences.
do_early_stopping (bool
or str
, optional, defaults to False
) โ Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values: True
, where the generation stops as soon as there are num_beams
complete candidates; False
, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates; "never"
, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).
num_beam_hyps_to_keep (int
, optional, defaults to 1) โ The number of beam hypotheses that shall be returned upon calling ~transformer.BeamSearchScorer.finalize
.
max_length (int
, optional) โ The maximum length of the sequence to be generated.
process
( input_ids: LongTensornext_scores: FloatTensornext_tokens: LongTensornext_indices: LongTensorscores_for_all_vocab: FloatTensorpad_token_id: typing.Optional[int] = Noneeos_token_id: typing.Union[int, typing.List[int], NoneType] = Nonebeam_indices: typing.Optional[torch.LongTensor] = None ) โ UserDict
Parameters
input_ids (torch.LongTensor
of shape (batch_size * num_beams, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
next_scores (torch.FloatTensor
of shape (batch_size, 2 * num_beams)
) โ Current scores of the top 2 * num_beams
non-finished beam hypotheses.
next_tokens (torch.LongTensor
of shape (batch_size, 2 * num_beams)
) โ input_ids
of the tokens corresponding to the top 2 * num_beams
non-finished beam hypotheses.
next_indices (torch.LongTensor
of shape (batch_size, 2 * num_beams)
) โ Beam indices indicating to which beam hypothesis the next_tokens
correspond.
scores_for_all_vocab (torch.FloatTensor
of shape (batch_size * num_beams, sequence_length)
) โ The scores of all tokens in the vocabulary for each of the beam hypotheses.
pad_token_id (int
, optional) โ The id of the padding token.
eos_token_id (Union[int, List[int]]
, optional) โ The id of the end-of-sequence token. Optionally, use a list to set multiple end-of-sequence tokens.
beam_indices (torch.LongTensor
, optional) โ Beam indices indicating to which beam hypothesis each token correspond.
Returns
UserDict
A dictionary composed of the fields as defined above:
next_beam_scores (torch.FloatTensor
of shape (batch_size * num_beams)
) โ Updated scores of all non-finished beams.
next_beam_tokens (torch.FloatTensor
of shape (batch_size * num_beams)
) โ Next tokens to be added to the non-finished beam_hypotheses.
next_beam_indices (torch.FloatTensor
of shape (batch_size * num_beams)
) โ Beam indices indicating to which beam the next tokens shall be added.
finalize
( input_ids: LongTensorfinal_beam_scores: FloatTensorfinal_beam_tokens: LongTensorfinal_beam_indices: LongTensormax_length: intpad_token_id: typing.Optional[int] = Noneeos_token_id: typing.Union[int, typing.List[int], NoneType] = Nonebeam_indices: typing.Optional[torch.LongTensor] = None )
transformers.top_k_top_p_filtering
( logits: FloatTensortop_k: int = 0top_p: float = 1.0filter_value: float = -infmin_tokens_to_keep: int = 1 )
Parameters
top_k (int
, optional, defaults to 0) โ If > 0, only keep the top k tokens with highest probability (top-k filtering)
min_tokens_to_keep (int
, optional, defaults to 1) โ Minimumber of tokens we keep per batch example in the output.
Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
transformers.tf_top_k_top_p_filtering
( logitstop_k = 0top_p = 1.0filter_value = -infmin_tokens_to_keep = 1 )
Parameters
top_k (int
, optional, defaults to 0) โ If > 0, only keep the top k tokens with highest probability (top-k filtering)
min_tokens_to_keep (int
, optional, defaults to 1) โ Minimumber of tokens we keep per batch example in the output.
Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
( tokenizer: AutoTokenizerskip_prompt: bool = False**decode_kwargs )
Parameters
tokenizer (AutoTokenizer
) โ The tokenized used to decode the tokens.
skip_prompt (bool
, optional, defaults to False
) โ Whether to skip the prompt to .generate()
or not. Useful e.g. for chatbots.
decode_kwargs (dict
, optional) โ Additional keyword arguments to pass to the tokenizerโs decode
method.
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:
Copied
end
( )
Flushes any remaining cache and prints a newline to stdout.
on_finalized_text
( text: strstream_end: bool = False )
Prints the new text to stdout. If the stream is ending, also prints a newline.
put
( value )
Receives tokens, decodes them, and prints them to stdout as soon as they form entire words.
( tokenizer: AutoTokenizerskip_prompt: bool = Falsetimeout: typing.Optional[float] = None**decode_kwargs )
Parameters
tokenizer (AutoTokenizer
) โ The tokenized used to decode the tokens.
skip_prompt (bool
, optional, defaults to False
) โ Whether to skip the prompt to .generate()
or not. Useful e.g. for chatbots.
timeout (float
, optional) โ The timeout for the text queue. If None
, the queue will block indefinitely. Useful to handle exceptions in .generate()
, when it is called in a separate thread.
decode_kwargs (dict
, optional) โ Additional keyword arguments to pass to the tokenizerโs decode
method.
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 acessing 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:
Copied
on_finalized_text
( text: strstream_end: bool = False )
Put the new text in the queue. If the stream is ending, also put a stop signal in the queue.
A can be used to modify the prediction scores of a language model head for generation.
enforcing alternated generation between the two codebooks of Bark
โs fine submodel.
See for more information.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
that enforces no repetition of encoder input ids n-grams for the decoder ids. See .
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
enforcing an exponential penalty on tokens that are not in the original input.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
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 for more information.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
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 for more information. Note: do_sample
must be set to True
for this LogitsWarper
to work.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
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.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
that enforces the specified token as the first generated token.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
that enforces the specified token as the last generated token when max_length
is reached.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
num_beam_groups (int
) โ Number of groups to divide num_beams
into in order to ensure diversity among different groups of beams. Each group of beams will operate independently, selecting tokens without considering the choices of other groups. This division promotes diversity by ensuring that beams within different groups explore different paths. For instance, if num_beams
is 6 and num_beam_groups
is 2, there will be 2 groups each containing 3 beams. The choice of num_beam_groups
should be made considering the desired level of output diversity and the total number of beams. See for more details.
that enforces diverse beam search.
Note that this logits processor is only effective for . See for more details.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
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.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
and 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.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
This class can be used to create a list of or to subsequently process a scores
input tensor. This class inherits from list and adds a specific call method to apply each or to the inputs.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
enforcing a min-length by setting EOS probability to 0.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
enforcing a min-length of new tokens by setting EOS (End-Of-Sequence) token probability to 0. Note that for decoder-only models, such as Llama2, min_length
will compute the length of prompt + newly generated tokens
whereas for other models it will behave as min_new_tokens
, that is, taking only into account the newly generated ones.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
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 set add_prefix_space=True
when initializing the tokenizer, and use tokenizer(bad_words, add_special_tokens=False).input_ids
. The add_prefix_space
argument is only supported for some slow tokenizers, as fast tokenizersโ prefixing behaviours come from pre tokenizers
. Read more .
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
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 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. .
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.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
that enforces constrained generation and is useful for prefix-conditioned constrained generation. See for more information.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
repetition_penalty (float
) โ The parameter for repetition penalty. 1.0 means no penalty. See for more details.
that prevents the repetition of previous tokens through an exponential penalty. This technique shares some similarities with coverage mechanisms and other aimed at reducing repetition. During the text generation process, the probability distribution for the next token is determined using a formula that incorporates token scores based on their occurrence in the generated sequence. Tokens with higher scores are more likely to be selected. The formula can be seen in the original . According to the paper a penalty of around 1.2 yields a good balance between truthful generation and lack of repetition.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
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).
In order to get the token ids of the sequences that you want to bias, make sure to set add_prefix_space=True
when initializing the tokenizer, and use tokenizer(bad_words, add_special_tokens=False).input_ids
. The add_prefix_space
argument is only supported for some slow tokenizers, as fast tokenizersโ prefixing behaviours come from pre tokenizers
. Read more .
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
supresses a list of tokens as soon as the generate
function starts generating using begin_index
tokens. This should ensure that the tokens defined by begin_suppress_tokens
at not sampled at the begining of the generation.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
for temperature (exponential scaling output probability distribution), which effectively means that it can control the randomness of the predicted tokens.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
that performs top-k, i.e. restricting to the k highest probability elements.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
that performs typical decoding. See for more information.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
See for more information.
See for more information.
input_ids (torch.LongTensor
of shape (batch_size, sequence_length)
) โ Indices of input sequence tokens in the vocabulary.
that enforces the specified token as the first generated token.
that enforces the specified token as the last generated token when max_length
is reached.
Indices can be obtained using . See and for details.
This class can be used to create a list of to subsequently process a scores
input tensor. This class inherits from list and adds a specific call method to apply each to the inputs.
Indices can be obtained using . See and for details.
Indices can be obtained using . See and for details.
enforcing a min-length by setting EOS probability to 0.
bad_words_ids (List[List[int]]
) โ List of list of token ids that are not allowed to be generated. In order to get the tokens of the words that should not appear in the generated text, make sure to set add_prefix_space=True
when initializing the tokenizer, and use tokenizer(bad_words, add_special_tokens=False).input_ids
. The add_prefix_space
argument is only supported for some slow tokenizers, as fast tokenizersโ prefixing behaviours come from pre tokenizers
. Read more .
that enforces that specified sequences will never be sampled.
that enforces no repetition of n-grams. See .
repetition_penalty (float
) โ The parameter for repetition penalty. 1.0 means no penalty. See for more details.
enforcing an exponential penalty on repeated sequences.
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 begining of the generation.
for temperature (exponential scaling output probability distribution).
that performs top-k, i.e. restricting to the k highest probability elements.
that performs top-p, i.e. restricting to top tokens summing to <= prob_cut_off.
that enforces the specified token as the first generated token.
that enforces the specified token as the last generated token when max_length
is reached.
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.
Indices can be obtained using . See and for details.
This class can be used to create a list of or to subsequently process a scores
input tensor. This class inherits from list and adds a specific call method to apply each or to the inputs.
Indices can be obtained using . See and for details.
Indices can be obtained using . See and for details.
enforcing a min-length by setting EOS probability to 0.
supressing 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 sampled at the begining of the generation.
suppressing a list of tokens at each decoding step. The processor will set their log probs to be -inf
so they are not sampled.
for temperature (exponential scaling output probability distribution).
that performs top-k, i.e. restricting to the k highest probability elements.
that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.
A can be used to change when to stop generation (other than EOS token). Please note that this is exclusivelly available to our PyTorch implementations.
Indices can be obtained using . See and for details.
Indices can be obtained using . See and for details.
Indices can be obtained using . See and for details.
Indices can be obtained using . See and for details.
A can be used to force the generation to include specific tokens or sequences in the output. Please note that this is exclusivelly available to our PyTorch implementations.
enforcing that an ordered sequence of tokens is included in the output.
A special that is fulfilled by fulfilling just one of several constraints.
constraints (List[Constraint]
) โ A list of objects that must be fulfilled by the beam scorer.
Abstract base class for all beam scorers that are used for and .
Indices can be obtained using any class inheriting from . See and for details.
group_index (int
, optional) โ The index of the group of beams. Used with .
Indices can be obtained using any class inheriting from . See and for details.
num_beam_groups (int
) โ Number of groups to divide num_beams
into in order to ensure diversity among different groups of beams. See for more details.
implementing standard beam search decoding.
Adapted in part from .
Reference for the diverse beam search algorithm and implementation
constraints (List[Constraint]
) โ A list of positive constraints represented as Constraint
objects that must be fulfilled in the generation output. For more information, the documentation of should be read.
num_beam_groups (int
) โ Number of groups to divide num_beams
into in order to ensure diversity among different groups of beams. See for more details.
implementing constrained beam search decoding.
Indices can be obtained using any class inheriting from . See and for details.
top_p (float
, optional, defaults to 1.0) โ If < 1.0, only keep the top tokens with cumulative probability >= top_p (nucleus filtering). Nucleus filtering is described in Holtzman et al. ()
From:
top_p (float
, optional, defaults to 1.0) โ If < 1.0, only keep the top tokens with cumulative probability >= top_p (nucleus filtering). Nucleus filtering is described in Holtzman et al. ()
From: