Utilities for Generation
This page lists all the utility functions used by generate(), greedy_search(), sample(), beam_search(), beam_sample(), group_beam_search(), and constrained_beam_search().
Most of those are only useful if you are studying the code of the generate methods in the library.
Generate Outputs
The output of generate() is an instance of a subclass of ModelOutput. This output is a data structure containing all the information returned by generate(), but that can also be used as tuple or dictionary.
Here’s an example:
from transformers import GPT2Tokenizer, GPT2LMHeadModel
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")
inputs = tokenizer("Hello, my dog is cute and ", return_tensors="pt")
generation_output = model.generate(**inputs, return_dict_in_generate=True, output_scores=True)
The generation_output
object is a GreedySearchDecoderOnlyOutput, as we can
see in the documentation of that class below, it means it has the following attributes:
sequences
: the generated sequences of tokensscores
(optional): the prediction scores of the language modelling head, for each generation stephidden_states
(optional): the hidden states of the model, for each generation stepattentions
(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
generation_output[:2]
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.
GreedySearchOutput
class transformers.generation_utils.GreedySearchDecoderOnlyOutput
< source >( sequences: LongTensor = None scores: typing.Optional[typing.Tuple[torch.FloatTensor]] = None attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
-
sequences (
torch.LongTensor
of shape(batch_size, sequence_length)
) — The generated sequences. The second dimension (sequence_length) is either equal tomax_length
or shorter if all batches finished early due to theeos_token_id
. -
scores (
tuple(torch.FloatTensor)
optional, returned whenoutput_scores=True
is passed or whenconfig.output_scores=True
) — Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple oftorch.FloatTensor
with up tomax_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 whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size, num_heads, generated_length, sequence_length)
. - hidden_states (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using greedy search.
class transformers.generation_utils.GreedySearchEncoderDecoderOutput
< source >( sequences: LongTensor = None scores: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None cross_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None decoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
-
sequences (
torch.LongTensor
of shape(batch_size, sequence_length)
) — The generated sequences. The second dimension (sequence_length) is either equal tomax_length
or shorter if all batches finished early due to theeos_token_id
. -
scores (
tuple(torch.FloatTensor)
optional, returned whenoutput_scores=True
is passed or whenconfig.output_scores=True
) — Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple oftorch.FloatTensor
with up tomax_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 whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.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 whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size, num_heads, generated_length, sequence_length)
. -
cross_attentions (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size, num_heads, generated_length, sequence_length)
. - decoder_hidden_states (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.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)
class transformers.generation_flax_utils.FlaxGreedySearchOutput
< source >( sequences: ndarray = None )
Flax Base class for outputs of decoder-only generation models using greedy search.
“Returns a new object replacing the specified fields with new values.
SampleOutput
class transformers.generation_utils.SampleDecoderOnlyOutput
< source >( sequences: LongTensor = None scores: typing.Optional[typing.Tuple[torch.FloatTensor]] = None attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
-
sequences (
torch.LongTensor
of shape(batch_size*num_return_sequences, sequence_length)
) — The generated sequences. The second dimension (sequence_length) is either equal tomax_length
or shorter if all batches finished early due to theeos_token_id
. -
scores (
tuple(torch.FloatTensor)
optional, returned whenoutput_scores=True
is passed or whenconfig.output_scores=True
) — Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple oftorch.FloatTensor
with up tomax_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 whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(num_return_sequences*batch_size, num_heads, generated_length, sequence_length)
. - hidden_states (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(num_return_sequences*batch_size, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using sampling.
class transformers.generation_utils.SampleEncoderDecoderOutput
< source >( sequences: LongTensor = None scores: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None cross_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None decoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
-
sequences (
torch.LongTensor
of shape(batch_size*num_return_sequences, sequence_length)
) — The generated sequences. The second dimension (sequence_length) is either equal tomax_length
or shorter if all batches finished early due to theeos_token_id
. -
scores (
tuple(torch.FloatTensor)
optional, returned whenoutput_scores=True
is passed or whenconfig.output_scores=True
) — Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple oftorch.FloatTensor
with up tomax_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 whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.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 whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size*num_return_sequences, num_heads, generated_length, sequence_length)
. -
cross_attentions (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size, num_heads, generated_length, sequence_length)
. - decoder_hidden_states (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.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)
class transformers.generation_flax_utils.FlaxSampleOutput
< source >( sequences: ndarray = None )
Flax Base class for outputs of decoder-only generation models using sampling.
“Returns a new object replacing the specified fields with new values.
BeamSearchOutput
class transformers.generation_utils.BeamSearchDecoderOnlyOutput
< source >( sequences: LongTensor = None sequences_scores: typing.Optional[torch.FloatTensor] = None scores: typing.Optional[typing.Tuple[torch.FloatTensor]] = None beam_indices: typing.Optional[torch.LongTensor] = None attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
-
sequences (
torch.LongTensor
of shape(batch_size*num_return_sequences, sequence_length)
) — The generated sequences. The second dimension (sequence_length) is either equal tomax_length
or shorter if all batches finished early due to theeos_token_id
. -
sequences_scores (
torch.FloatTensor
of shape(batch_size*num_return_sequences)
, optional, returned whenoutput_scores=True
is passed or whenconfig.output_scores=True
) — Final beam scores of the generatedsequences
. -
scores (
tuple(torch.FloatTensor)
optional, returned whenoutput_scores=True
is passed or whenconfig.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 oftorch.FloatTensor
with up tomax_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 (
tuple(tuple(torch.LongTensor))
, optional, returned whenoutput_scores=True
is passed or whenconfig.output_scores=True
) — Beam indices of generated token id at each generation step.torch.LongTensor
of shape(batch_size*num_return_sequences, input_ids.shape[-1])
. -
attentions (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size*num_beams, num_heads, generated_length, sequence_length)
. - hidden_states (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.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.
class transformers.generation_utils.BeamSearchEncoderDecoderOutput
< source >( sequences: LongTensor = None sequences_scores: typing.Optional[torch.FloatTensor] = None scores: typing.Optional[typing.Tuple[torch.FloatTensor]] = None beam_indices: typing.Optional[torch.LongTensor] = None encoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None cross_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None decoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
-
sequences (
torch.LongTensor
of shape(batch_size*num_return_sequences, sequence_length)
) — The generated sequences. The second dimension (sequence_length) is either equal tomax_length
or shorter if all batches finished early due to theeos_token_id
. -
sequences_scores (
torch.FloatTensor
of shape(batch_size*num_return_sequences)
, optional, returned whenoutput_scores=True
is passed or whenconfig.output_scores=True
) — Final beam scores of the generatedsequences
. -
scores (
tuple(torch.FloatTensor)
optional, returned whenoutput_scores=True
is passed or whenconfig.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 oftorch.FloatTensor
with up tomax_new_tokens
elements (one element for each generated token), with each tensor of shape(batch_size*num_beams, config.vocab_size)
. -
beam_indices (
tuple(tuple(torch.LongTensor))
, optional, returned whenoutput_scores=True
is passed or whenconfig.output_scores=True
) — Beam indices of generated token id at each generation step.torch.LongTensor
of shape(batch_size*num_return_sequences, max_length-1)
. -
attentions (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — -
encoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.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 whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size*num_beams*num_return_sequences, num_heads, generated_length, sequence_length)
. -
cross_attentions (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size, num_heads, generated_length, sequence_length)
. - decoder_hidden_states (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.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)
BeamSampleOutput
class transformers.generation_utils.BeamSampleDecoderOnlyOutput
< source >( sequences: LongTensor = None sequences_scores: typing.Optional[torch.FloatTensor] = None scores: typing.Optional[typing.Tuple[torch.FloatTensor]] = None beam_indices: typing.Optional[torch.LongTensor] = None attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
-
sequences (
torch.LongTensor
of shape(batch_size*num_return_sequences, sequence_length)
) — The generated sequences. The second dimension (sequence_length) is either equal tomax_length
or shorter if all batches finished early due to theeos_token_id
. -
sequences_scores (
torch.FloatTensor
of shape(batch_size * num_return_sequence)
, optional, returned whenoutput_scores=True
is passed or whenconfig.output_scores=True
) — Final beam scores of the generatedsequences
. -
scores (
tuple(torch.FloatTensor)
optional, returned whenoutput_scores=True
is passed or whenconfig.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 oftorch.FloatTensor
with up tomax_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 (
tuple(tuple(torch.LongTensor))
, optional, returned whenoutput_scores=True
is passed or whenconfig.output_scores=True
) — Beam indices of generated token id at each generation step.torch.LongTensor
of shape(batch_size*num_return_sequences, input_ids.shape[-1])
. -
attentions (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size*num_beams, num_heads, generated_length, sequence_length)
. - hidden_states (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size*num_beams, generated_length, hidden_size)
.
Base class for outputs of decoder-only generation models using beam sample.
class transformers.generation_utils.BeamSampleEncoderDecoderOutput
< source >( sequences: LongTensor = None sequences_scores: typing.Optional[torch.FloatTensor] = None scores: typing.Optional[typing.Tuple[torch.FloatTensor]] = None beam_indices: typing.Optional[torch.LongTensor] = None encoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None cross_attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None decoder_hidden_states: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )
Parameters
-
sequences (
torch.LongTensor
of shape(batch_size*num_beams, sequence_length)
) — The generated sequences. The second dimension (sequence_length) is either equal tomax_length
or shorter if all batches finished early due to theeos_token_id
. -
sequences_scores (
torch.FloatTensor
of shape(batch_size * num_return_sequence)
, optional, returned whenoutput_scores=True
is passed or whenconfig.output_scores=True
) — Final beam scores of the generatedsequences
. -
scores (
tuple(torch.FloatTensor)
optional, returned whenoutput_scores=True
is passed or whenconfig.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 oftorch.FloatTensor
with up tomax_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 whenoutput_scores=True
is passed or whenconfig.output_scores=True
) — Beam indices of generated token id at each generation step.torch.LongTensor
of shape(batch_size*num_return_sequences, max_length-1)
. -
encoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.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 whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size*num_beams, num_heads, generated_length, sequence_length)
. -
cross_attentions (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_attentions=True
is passed orconfig.output_attentions=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.FloatTensor
of shape(batch_size, num_heads, generated_length, sequence_length)
. - decoder_hidden_states (
tuple(tuple(torch.FloatTensor))
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) oftorch.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)
LogitsProcessor
A LogitsProcessor can be used to modify the prediction scores of a language model head for generation.
Abstract base class for all logit processors that can be applied during generation.
__call__
< source >(
input_ids: LongTensor
scores: FloatTensor
)
→
torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
-
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using BertTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — Additional logits processor specific kwargs.
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
Torch method for processing logits.
This class can be used to create a list of LogitsProcessor or LogitsWarper to subsequently process a
scores
input tensor. This class inherits from list and adds a specific call method to apply each
LogitsProcessor or LogitsWarper to the inputs.
__call__
< source >(
input_ids: LongTensor
scores: FloatTensor
**kwargs
)
→
torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
-
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using BertTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — Additional logits processor specific kwargs.
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__
< source >(
input_ids: LongTensor
scores: FloatTensor
)
→
torch.FloatTensor
of shape (batch_size, config.vocab_size)
Parameters
-
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using BertTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — Additional logits processor specific kwargs.
Returns
torch.FloatTensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
Torch method for warping logits.
class transformers.MinLengthLogitsProcessor
< source >( min_length: int eos_token_id: int )
LogitsProcessor enforcing a min-length by setting EOS probability to 0.
class transformers.TemperatureLogitsWarper
< source >( temperature: float )
LogitsWarper for temperature (exponential scaling output probability distribution).
class transformers.RepetitionPenaltyLogitsProcessor
< source >( penalty: float )
Parameters
-
repetition_penalty (
float
) — The parameter for repetition penalty. 1.0 means no penalty. See this paper for more details.
LogitsProcessor enforcing an exponential penalty on repeated sequences.
class transformers.TopPLogitsWarper
< source >( top_p: float filter_value: float = -inf min_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 totop_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.
LogitsWarper that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.
class transformers.TopKLogitsWarper
< source >( top_k: int filter_value: float = -inf min_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.
LogitsWarper that performs top-k, i.e. restricting to the k highest probability elements.
class transformers.TypicalLogitsWarper
< source >( mass: float = 0.9 filter_value: float = -inf min_tokens_to_keep: int = 1 )
Parameters
LogitsWarper that performs typical decoding. See Typical Decoding for Natural Language Generation for more information.
class transformers.NoRepeatNGramLogitsProcessor
< source >( ngram_size: int )
LogitsProcessor that enforces no repetition of n-grams. See Fairseq.
class transformers.NoBadWordsLogitsProcessor
< source >( bad_words_ids: typing.List[typing.List[int]] eos_token_id: int )
Parameters
-
bad_words_ids (
List[List[int]]
) — List of list of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, usetokenizer(bad_words, add_prefix_space=True, add_special_tokens=False).input_ids
. -
eos_token_id (
int
) — The id of the end-of-sequence token.
LogitsProcessor that enforces that specified sequences will never be sampled.
class transformers.PrefixConstrainedLogitsProcessor
< source >( prefix_allowed_tokens_fn: typing.Callable[[int, torch.Tensor], typing.List[int]] num_beams: int )
LogitsProcessor that enforces constrained generation and is useful for prefix-conditioned constrained generation. See Autoregressive Entity Retrieval for more information.
class transformers.HammingDiversityLogitsProcessor
< source >( diversity_penalty: float num_beams: int num_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 thatdiversity_penalty
is only effective ifgroup beam search
is enabled. -
num_beams (
int
) — Number of beams used for group beam search. See this paper for more details. -
num_beam_groups (
int
) — Number of groups to dividenum_beams
into in order to ensure diversity among different groups of beams. See this paper for more details.
LogitsProcessor that enforces diverse beam search. Note that this logits processor is only effective for PreTrainedModel.group_beam_search(). See Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models for more details.
__call__
< source >( input_ids: LongTensor scores: FloatTensor current_tokens: LongTensor beam_group_idx: int )
class transformers.ForcedBOSTokenLogitsProcessor
< source >( bos_token_id: int )
LogitsProcessor that enforces the specified token as the first generated token.
class transformers.ForcedEOSTokenLogitsProcessor
< source >( max_length: int eos_token_id: int )
LogitsProcessor that enforces the specified token as the last generated token when max_length
is reached.
LogitsProcessor that removes all nan
and inf
values to avoid the generation method to fail. Note that using
the logits processor should only be used if necessary since it can slow down the generation method. max_length
is
reached.
Abstract base class for all logit processors that can be applied during generation.
__call__
< source >(
input_ids: Tensor
scores: Tensor
cur_len: int
)
→
tf.Tensor
of shape (batch_size, config.vocab_size)
Parameters
-
input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using PreTrainedTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — Additional logits processor specific kwargs.
Returns
tf.Tensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
TF method for processing logits.
This class can be used to create a list of TFLogitsProcessor to subsequently process a scores
input tensor.
This class inherits from list and adds a specific call method to apply each TFLogitsProcessor to the
inputs.
__call__
< source >(
input_ids: Tensor
scores: Tensor
cur_len: int
**kwargs
)
→
tf.Tensor
of shape (batch_size, config.vocab_size)
Parameters
-
input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using PreTrainedTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — 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__
< source >(
input_ids: Tensor
scores: Tensor
cur_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.Indices can be obtained using PreTrainedTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — Additional logits processor specific kwargs.
Returns
tf.Tensor
of shape (batch_size, config.vocab_size)
The processed prediction scores.
TF method for warping logits.
class transformers.TFTemperatureLogitsWarper
< source >( temperature: float )
TFLogitsWarper for temperature (exponential scaling output probability distribution).
class transformers.TFTopPLogitsWarper
< source >( top_p: float filter_value: float = -inf min_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 totop_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.
TFLogitsWarper that performs top-p, i.e. restricting to top tokens summing to <= prob_cut_off.
class transformers.TFTopKLogitsWarper
< source >( top_k: int filter_value: float = -inf min_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.
TFLogitsWarper that performs top-k, i.e. restricting to the k highest probability elements.
class transformers.TFMinLengthLogitsProcessor
< source >( min_length: int eos_token_id: int )
TFLogitsProcessor enforcing a min-length by setting EOS probability to 0.
class transformers.TFNoBadWordsLogitsProcessor
< source >( bad_words_ids: typing.List[typing.List[int]] eos_token_id: int )
Parameters
TFLogitsProcessor that enforces that specified sequences will never be sampled.
class transformers.TFNoRepeatNGramLogitsProcessor
< source >( ngram_size: int )
TFLogitsProcessor that enforces no repetition of n-grams. See Fairseq.
class transformers.TFRepetitionPenaltyLogitsProcessor
< source >( penalty: float )
Parameters
-
repetition_penalty (
float
) — The parameter for repetition penalty. 1.0 means no penalty. See this paper for more details.
TFLogitsProcessor enforcing an exponential penalty on repeated sequences.
class transformers.TFForcedBOSTokenLogitsProcessor
< source >( bos_token_id: int )
TFLogitsProcessor that enforces the specified token as the first generated token.
class transformers.TFForcedEOSTokenLogitsProcessor
< source >( max_length: int eos_token_id: int )
TFLogitsProcessor that enforces the specified token as the last generated token when max_length
is reached.
Abstract base class for all logit processors that can be applied during generation.
__call__
< source >(
input_ids: ndarray
scores: ndarray
)
→
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.Indices can be obtained using PreTrainedTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — Additional logits processor specific kwargs.
Returns
jnp.ndarray
of shape (batch_size, config.vocab_size)
The processed prediction scores.
Flax method for processing logits.
This class can be used to create a list of FlaxLogitsProcessor or FlaxLogitsWarper to subsequently process
a scores
input tensor. This class inherits from list and adds a specific call method to apply each
FlaxLogitsProcessor or FlaxLogitsWarper to the inputs.
__call__
< source >(
input_ids: ndarray
scores: ndarray
cur_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.Indices can be obtained using PreTrainedTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — 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__
< source >(
input_ids: ndarray
scores: ndarray
)
→
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.Indices can be obtained using PreTrainedTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — Additional logits processor specific kwargs.
Returns
jnp.ndarray
of shape (batch_size, config.vocab_size)
The processed prediction scores.
Flax method for warping logits.
class transformers.FlaxTemperatureLogitsWarper
< source >( temperature: float )
FlaxLogitsWarper for temperature (exponential scaling output probability distribution).
class transformers.FlaxTopPLogitsWarper
< source >( top_p: float filter_value: float = -inf min_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 totop_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.
FlaxLogitsWarper that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.
class transformers.FlaxTopKLogitsWarper
< source >( top_k: int filter_value: float = -inf min_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.
FlaxLogitsWarper that performs top-k, i.e. restricting to the k highest probability elements.
class transformers.FlaxForcedBOSTokenLogitsProcessor
< source >( bos_token_id: int )
FlaxLogitsProcessor that enforces the specified token as the first generated token.
class transformers.FlaxForcedEOSTokenLogitsProcessor
< source >( max_length: int eos_token_id: int )
FlaxLogitsProcessor that enforces the specified token as the last generated token when max_length
is reached.
class transformers.FlaxMinLengthLogitsProcessor
< source >( min_length: int eos_token_id: int )
FlaxLogitsProcessor enforcing a min-length by setting EOS probability to 0.
StoppingCriteria
A StoppingCriteria can be used to change when to stop generation (other than EOS token).
Abstract base class for all stopping criteria that can be applied during generation.
__call__
< source >( input_ids: LongTensor scores: FloatTensor **kwargs )
Parameters
-
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using BertTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — Additional stopping criteria specific kwargs.
__call__
< source >( input_ids: LongTensor scores: FloatTensor **kwargs )
Parameters
-
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using BertTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — Additional stopping criteria specific kwargs.
class transformers.MaxLengthCriteria
< source >( max_length: int )
This class can be used to stop generation whenever the full generated number of tokens exceeds max_length
. Keep
in mind for decoder-only type of transformers, this will include the initial prompted tokens.
__call__
< source >( input_ids: LongTensor scores: FloatTensor **kwargs )
Parameters
-
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using BertTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — Additional stopping criteria specific kwargs.
class transformers.MaxTimeCriteria
< source >( max_time: float initial_timestamp: typing.Optional[float] = None )
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__
< source >( input_ids: LongTensor scores: FloatTensor **kwargs )
Parameters
-
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using BertTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 — Additional stopping criteria specific kwargs.
Constraints
A Constraint can be used to force the generation to include specific tokens or sequences in the output.
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
will always terminate (halt).
advance
< source >(
)
→
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
< source >(
stateful = False
)
→
constraint(Constraint
)
Returns
constraint(Constraint
)
The same constraint as the one being called from.
Creates a new instance of this constraint.
Reads in a token and returns whether it creates progress.
Returns the number of remaining steps of advance()
in order to complete this constraint.
Resets the state of this constraint to its initialization. We would call this in cases where the fulfillment of a constraint is abrupted by an unwanted token.
Tests whether this constraint has been properly defined.
update
< source >(
token_id: int
)
→
stepped(bool
)
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)
class transformers.PhrasalConstraint
< source >( token_ids: typing.List[int] )
Constraint enforcing that an ordered sequence of tokens is included in the output.
class transformers.DisjunctiveConstraint
< source >( nested_token_ids: typing.List[typing.List[int]] )
A special Constraint that is fulfilled by fulfilling just one of several constraints.
class transformers.ConstraintListState
< source >( constraints: typing.List[transformers.generation_beam_constraints.Constraint] )
Parameters
-
constraints (
List[Constraint]
) — A list of Constraint objects that must be fulfilled by the beam scorer.
A class for beam scorers to track its progress through a list of constraints.
The list of tokens to generate such that we can make progress. By “list” we don’t mean the list of token that will fully fulfill a constraint.
Given constraints c_i = {t_ij | j == # of tokens}
, If we’re not in the middle of progressing through a
specific constraint c_i
, we return:
[t_k1 for k in indices of unfulfilled constraints]
If we are in the middle of a constraint, then we return:
[t_ij]
, where i
is the index of the inprogress constraint, j
is the next step for the constraint.
Though we don’t care which constraint is fulfilled first, if we are in the progress of fulfilling a constraint, that’s the only one we’ll return.
token_ids: the tokens generated thus far to reset the state of the progress through constraints.
BeamSearch
Abstract base class for all beam scorers that are used for beam_search() and beam_sample().
process
< source >(
input_ids: LongTensor
next_scores: FloatTensor
next_tokens: LongTensor
next_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.Indices can be obtained using any class inheriting from PreTrainedTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
next_scores (
torch.FloatTensor
of shape(batch_size, 2 * num_beams)
) — Current scores of the top2 * 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 top2 * num_beams
non-finished beam hypotheses. -
next_indices (
torch.LongTensor
of shape(batch_size, 2 * num_beams)
) — Beam indices indicating to which beam hypothesis thenext_tokens
correspond. -
pad_token_id (
int
, optional) — The id of the padding token. -
eos_token_id (
int
, optional) — The id of the end-of-sequence token.
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
< source >(
input_ids: LongTensor
next_scores: FloatTensor
next_tokens: LongTensor
next_indices: LongTensor
max_length: int
**kwargs
)
→
torch.LongTensor
of shape (batch_size * num_return_sequences, sequence_length)
Parameters
-
input_ids (
torch.LongTensor
of shape(batch_size * num_beams, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using any class inheriting from PreTrainedTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
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 thefinal_beam_tokens
shall be added. -
pad_token_id (
int
, optional) — The id of the padding token. -
eos_token_id (
int
, optional) — The id of the end-of-sequence token.
Returns
torch.LongTensor
of shape (batch_size * num_return_sequences, sequence_length)
The generated sequences.
The second dimension (sequence_length) is either equal to max_length
or shorter if all batches finished early
due to the eos_token_id
.
class transformers.BeamSearchScorer
< source >( batch_size: int num_beams: int device: device length_penalty: typing.Optional[float] = 1.0 do_early_stopping: typing.Optional[bool] = False num_beam_hyps_to_keep: typing.Optional[int] = 1 num_beam_groups: typing.Optional[int] = 1 **kwargs )
Parameters
-
batch_size (
int
) — Batch Size ofinput_ids
for which standard beam search decoding is run in parallel. -
max_length (
int
) — The maximum length of the sequence to be generated. -
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 ofBeamSearchScorer
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, whilelength_penalty
< 0.0 encourages shorter sequences. -
do_early_stopping (
bool
, optional, defaults toFalse
) — Whether to stop the beam search when at leastnum_beams
sentences are finished per batch or not. -
num_beam_hyps_to_keep (
int
, optional, defaults to 1) — The number of beam hypotheses that shall be returned upon calling~transformer.BeamSearchScorer.finalize
. -
num_beam_groups (
int
) — Number of groups to dividenum_beams
into in order to ensure diversity among different groups of beams. See this paper for more details.
BeamScorer implementing standard beam search decoding.
Adapted in part from Facebook’s XLM beam search code.
Reference for the diverse beam search algorithm and implementation Ashwin Kalyan’s DBS implementation
process
< source >( input_ids: LongTensor next_scores: FloatTensor next_tokens: LongTensor next_indices: LongTensor pad_token_id: typing.Optional[int] = None eos_token_id: typing.Optional[int] = None beam_indices: typing.Optional[torch.LongTensor] = None )
finalize
< source >( input_ids: LongTensor final_beam_scores: FloatTensor final_beam_tokens: LongTensor final_beam_indices: LongTensor max_length: int pad_token_id: typing.Optional[int] = None eos_token_id: typing.Optional[int] = None beam_indices: typing.Optional[torch.LongTensor] = None )
class transformers.ConstrainedBeamSearchScorer
< source >( batch_size: int num_beams: int constraints: typing.List[transformers.generation_beam_constraints.Constraint] device: device length_penalty: typing.Optional[float] = 1.0 do_early_stopping: typing.Optional[bool] = False num_beam_hyps_to_keep: typing.Optional[int] = 1 num_beam_groups: typing.Optional[int] = 1 **kwargs )
Parameters
-
batch_size (
int
) — Batch Size ofinput_ids
for which standard beam search decoding is run in parallel. -
max_length (
int
) — The maximum length of the sequence to be generated. -
num_beams (
int
) — Number of beams for beam search. -
constraints (
List[Constraint]
) — A list of positive constraints represented asConstraint
objects that must be fulfilled in the generation output. For more information, the documentation of Constraint should be read. -
device (
torch.device
) — Defines the device type (e.g.,"cpu"
or"cuda"
) on which this instance ofBeamSearchScorer
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, whilelength_penalty
< 0.0 encourages shorter sequences. -
do_early_stopping (
bool
, optional, defaults toFalse
) — Whether to stop the beam search when at leastnum_beams
sentences are finished per batch or not. -
num_beam_hyps_to_keep (
int
, optional, defaults to 1) — The number of beam hypotheses that shall be returned upon calling~transformer.BeamSearchScorer.finalize
. -
num_beam_groups (
int
) — Number of groups to dividenum_beams
into in order to ensure diversity among different groups of beams. See this paper for more details.
BeamScorer implementing constrained beam search decoding.
process
< source >(
input_ids: LongTensor
next_scores: FloatTensor
next_tokens: LongTensor
next_indices: LongTensor
scores_for_all_vocab: FloatTensor
pad_token_id: typing.Optional[int] = None
eos_token_id: typing.Optional[int] = None
)
→
UserDict
Parameters
-
input_ids (
torch.LongTensor
of shape(batch_size * num_beams, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using any class inheriting from PreTrainedTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
-
next_scores (
torch.FloatTensor
of shape(batch_size, 2 * num_beams)
) — Current scores of the top2 * 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 top2 * num_beams
non-finished beam hypotheses. -
next_indices (
torch.LongTensor
of shape(batch_size, 2 * num_beams)
) — Beam indices indicating to which beam hypothesis thenext_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 (
int
, optional) — The id of the end-of-sequence token.
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
< source >( input_ids: LongTensor final_beam_scores: FloatTensor final_beam_tokens: LongTensor final_beam_indices: LongTensor max_length: int pad_token_id: typing.Optional[int] = None eos_token_id: typing.Optional[int] = None )
Utilities
transformers.top_k_top_p_filtering
< source >( logits: FloatTensor top_k: int = 0 top_p: float = 1.0 filter_value: float = -inf min_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) -
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. (http://arxiv.org/abs/1904.09751) -
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
From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
transformers.tf_top_k_top_p_filtering
< source >( logits top_k = 0 top_p = 1.0 filter_value = -inf min_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) -
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. (http://arxiv.org/abs/1904.09751) -
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
From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317