TFRagSequenceForGeneration

 post processing steps while
the latter silently ignores them. A TF RAG-sequence model implementation. It performs RAG-sequence specific marginalization in the forward pass. RAG is a sequence-to-sequence model which encapsulates two core components: a question encoder and a generator.
During a forward pass, we encode the input with the question encoder and pass it to the retriever to extract
relevant context documents. The documents are then prepended to the input. Such contextualized inputs is passed to
the generator. The question encoder can be any autoencoding model, preferably TFDPRQuestionEncoder, and the generator can be
any seq2seq model, preferably TFBartForConditionalGeneration. The model can be initialized with a RagRetriever for end-to-end generation or used in combination with the
outputs of a retriever in multiple steps---see examples for more details. The model is compatible any
autoencoding model as the question_encoder and any seq2seq model with languag


TFRagSequenceForGeneration

e model head as the generator.
It has been tested with TFDPRQuestionEncoder as the question_encoder and TFBartForConditionalGeneration
as the generator. This model inherits from TFPreTrainedModel. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.) This model is also a Tensorflow tf.keras.Model
subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to
general usage and behavior. The model is in a developing state as it is now fully supports in eager-mode only, and may not be exported in
SavedModel format.  call  < source > ( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None decoder_input_ids: np.ndarray | tf.Tensor | None = None decoder_attention_mask: np.ndarray | tf.Tensor | None = None encoder_outputs: np.ndarray | tf.Tensor | None = None


TFRagSequenceForGeneration

past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None doc_scores: np.ndarray | tf.Tensor | None = None context_input_ids: np.ndarray | tf.Tensor | None = None context_attention_mask: np.ndarray | tf.Tensor | None = None use_cache: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None output_retrieved: Optional[bool] = None n_docs: Optional[int] = None exclude_bos_score: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None reduce_loss: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False **kwargs  ) → transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput or tuple(tf.Tensor)  Parameters   input_ids (tf.Tensor of shape (batch_size, sequence_length)) —
Indices of input sequence tokens in the vocabulary. RagConfig, used to initialize the model, specifies
which generator to use, it also specifies a compatible generator tokenizer. Use that tokenize


TFRagSequenceForGeneration

r class to
obtain the indices.   attention_mask (tf.Tensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?   encoder_outputs (tuple(tuple(tf.Tensor), optional) —
Tuple consists of (generator_enc_last_hidden_state, optional: generator_enc_hidden_states,
optional: generator_enc_attentions). generator_enc_last_hidden_state of shape (batch_size, n_docs * sequence_length, hidden_size) is a sequence of hidden-states at the output of the last layer of the
generator’s encoder.
Used by the (TFRagModel) model during decoding.   decoder_input_ids (tf.Tensor of shape (batch_size, target_sequence_length), optional) —
Provide for generation tasks. None by default, construct as per instructions for the generator model
you’re using with your RAG instance.   decoder_attention_mask (torch.BoolTensor of


TFRagSequenceForGeneration

shape (batch_size, target_sequence_length), optional) —
Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also
be used by default.   past_key_values (tuple(tuple(tf.Tensor))) —
Tuple consists of two elements: encoder_outputs of the RAG model (see encoder_outputs) and
past_key_values of the underlying generator. Can be used to speed up decoding. past_key_values are used
in the (RagTokenForGeneration) model during decoding.   doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) —
Score between each retrieved document embeddings (see retrieved_doc_embeds) and
question_encoder_last_hidden_state. If the model has is not initialized with a retriever doc_scores
has to be provided to the forward pass. doc_scores can be computed via
question_encoder_last_hidden_state and retrieved_doc_embeds, see examples for more information.   context_input_ids (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length),


TFRagSequenceForGeneration

 optional, returned when output_retrieved=True) —
Input IDs post-processed from the retrieved documents and the question encoder input_ids by the
retriever.
If the model has is not initialized with a retriever `context_input_ids has to be provided to the
forward pass. context_input_ids are returned by __call__(). context_attention_mask
(tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when
output_retrieved=True): Attention mask post-processed from the retrieved documents and the question
encoder input_ids by the retriever.
If the model has is not initialized with a retriever context_attention_mask has to be provided to the
forward pass. context_attention_mask are returned by __call__().   use_cache (bool, optional, defaults to True) —
If set to True, past_key_values key value states are returned and can be used to speed up decoding (see
past_key_values).   output_attentions (bool, optional) —
Whether or not to return the a


TFRagSequenceForGeneration

ttentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   output_retrieved(bool, optional) —
Whether or not to return the retrieved_doc_embeds, retrieved_doc_ids, context_input_ids and
context_attention_mask. See returned tensors for more detail.   return_dict (bool, optional) —
Whether or not to return a TFRetrievAugLMOutput instead of a plain tuple.   n_docs (int, optional, defaults to `config.n_docs“) —
Number of documents to retrieve and/or number of documents for which to generate an answer.   exclude_bos_score (bool, optional) —
Only relevant if labels is passed. If True, the score of the BOS token is disregarded when computing
the loss.   labels (tf.Tensor or np.ndarray of shape (batch_size, sequence_length), optional) —
Labels for computing the cross entropy classi


TFRagSequenceForGeneration

fication loss according to Rag-Sequence model formulation See
https://arxiv.org/pdf/2005.11401.pdf Section 2.1 for details about Rag-Sequence formulation. Indices should
be in [0, ..., config.vocab_size - 1].   reduce_loss (bool, optional) —
Only relevant if labels is passed. If True, the NLL loss is reduced using the tf.Tensor.sum
operation.   kwargs (Dict[str, any], optional, defaults to {}) —
Legacy dictionary, which is required so that model can use generate() function.   Returns
transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput or tuple(tf.Tensor)

A transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput or a tuple of tf.Tensor (if
return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the
configuration (RagConfig) and inputs.
loss (tf.Tensor of shape (1,), optional, returned when labels is provided) — Language modeling loss.
logits (tf.Tensor of shape (batch_size, sequence_length, con


TFRagSequenceForGeneration

fig.vocab_size)) — Prediction scores of the language modeling head. The score is possibly marginalized over all documents for
each vocabulary token.
past_key_values (List[tf.Tensor], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of tf.Tensor of length config.n_layers, with each tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)).
Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used
(see past_key_values input) to speed up sequential decoding.
doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and
question_encoder_last_hidden_state.
retrieved_doc_embeds (tf.Tensor of shape (batch_size, config.n_docs, hidden_size), optional, returned when output_retrieved=True) — Embedded documents retrieved by the retriever. Is used with question_encoder_last_hidden_state to com


TFRagSequenceForGeneration

pute
the doc_scores.
retrieved_doc_ids (tf.Tensor (int32) of shape (batch_size, config.n_docs), optional, returned when output_retrieved=True) — The indexes of the embedded documents retrieved by the retriever.
context_input_ids (tf.Tensor(int32) of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.
context_attention_mask (tf.Tensor (int32) of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the
retriever.
question_encoder_last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden states at the output of the last layer of the question encoder pooled output of the
model.
question_enc_hidden_st


TFRagSequenceForGeneration

ates (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 and one for the output of each layer) of shape
(batch_size, sequence_length, hidden_size).
Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.
question_enc_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights of the question encoder, after the attention softmax, used to compute the weighted
average in the self-attention heads.
generator_enc_last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the generator encoder of the model.
generator_en


TFRagSequenceForGeneration

c_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 and one for the output of each layer) of shape
(batch_size, sequence_length, hidden_size).
Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.
generator_enc_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted
average in the self-attention heads.
generator_dec_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 embedd


TFRagSequenceForGeneration

ings and one for the output of each layer) of shape
(batch_size, sequence_length, hidden_size).
Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.
generator_dec_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted
average in the self-attention heads.
  The TFRagSequenceForGeneration forward method, overrides the __call__ special method. Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.  Example:   Copied >>> from transformers import Aut


TFRagSequenceForGeneration

oTokenizer, RagRetriever, TFRagSequenceForGeneration
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-sequence-nq")
>>> retriever = RagRetriever.from_pretrained(
...     "facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True
... )
>>> # initialize with RagRetriever to do everything in one forward call
>>> model = TFRagSequenceForGeneration.from_pretrained(
...     "facebook/rag-sequence-nq", retriever=retriever, from_pt=True
... )
>>> input_dict = tokenizer.prepare_seq2seq_batch(
...     "How many people live in Paris?", "In Paris, there are 10 million people.", return_tensors="tf"
... )
>>> outputs = model(input_dict, output_retrieved=True)
>>> # or use retriever separately
>>> # 1. Encode
>>> input_ids = input_dict["input_ids"]
>>> question_hidden_states = model.question_encoder(input_ids)[0]
>>> # 2. Retrieve
>>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.numpy(), return_tensors="tf")
>>> doc_scores = tf.squeeze(
...


TFRagSequenceForGeneration

   tf.matmul(
...         tf.expand_dims(question_hidden_states, axis=1), docs_dict["retrieved_doc_embeds"], transpose_b=True
...     ),
...     axis=1,
... )
>>> # 3. Forward to generator
>>> outputs = model(
...     inputs=None,
...     context_input_ids=docs_dict["context_input_ids"],
...     context_attention_mask=docs_dict["context_attention_mask"],
...     doc_scores=doc_scores,
...     decoder_input_ids=input_dict["labels"],
... )
>>> # or directly generate
>>> generated = model.generate(
...     context_input_ids=docs_dict["context_input_ids"],
...     context_attention_mask=docs_dict["context_attention_mask"],
...     doc_scores=doc_scores,
... )
>>> generated_string = tokenizer.batch_decode(generated, skip_special_tokens=True)  generate  < source > ( input_ids: TFModelInputType | None = None attention_mask: tf.Tensor | None = None context_input_ids = None context_attention_mask = None doc_scores = None do_deduplication = None num_return_sequences = None num_b


TFRagSequenceForGeneration

eams = None n_docs = None **model_kwargs  ) → tf.Tensor of shape (batch_size * num_return_sequences, sequence_length)  Parameters   input_ids (tf.Tensor of shape (batch_size, sequence_length), optional) —
The sequence used as a prompt for the generation. If input_ids is not passed, then
context_input_ids has to be provided.   attention_mask (tf.Tensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]: - 1 for
tokens that are not masked, - 0 for tokens that are masked. What are attention
masks?   context_input_ids (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) —
Input IDs post-processed from the retrieved documents and the question encoder input_ids by the
retriever.   context_attention_mask (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_re


TFRagSequenceForGeneration

trieved=True) —
Attention mask post-processed from the retrieved documents and the question encoder input_ids by the
retriever. If the model has is not initialized with a retriever or input_ids is not given,
context_input_ids and context_attention_mask have to be provided to the forward pass. They are
returned by __call__().   doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) —
Score between each retrieved document embeddings (see retrieved_doc_embeds) and
question_encoder_last_hidden_state. If the model has is not initialized with a retriever or
input_ids is not given, doc_scores has to be provided to the forward pass. doc_scores are
returned by __call__().   do_deduplication (bool, optional) —
Whether or not to deduplicate the generations from different context documents for a given input. Has
to be set to False if used while training with distributed backend.   num_return_sequences(int, optional, defaults to 1) —
The number of independently computed return


TFRagSequenceForGeneration

ed sequences for each element in the batch. Note that this
is not the value we pass to the generator’s [generate()](/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate) function,
where we set num_return_sequences to num_beams.   num_beams (int, optional, defaults to 1) —
Number of beams for beam search. 1 means no beam search.   n_docs (int, optional, defaults to config.n_docs) —
Number of documents to retrieve and/or number of documents for which to generate an answer.   kwargs (Dict[str, Any], optional) —
Additional kwargs will be passed to generate()   Returns
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.
  Implements RAG sequence “thorough” decoding. Read the generate()` documentation
for more information on how to set other generate inp


TFRagTokenForGeneration

class transformers.TFRagTokenForGeneration  < source > ( *args **kwargs  )   Parameters   config (RagConfig) —
Model configuration class with all the parameters of the model. Initializing with a config file does not
load the weights associated with the model, only the configuration. Check out the
from_pretrained() method to load the model weights.   question_encoder (TFPreTrainedModel) —
An encoder model compatible with the faiss index encapsulated by the retriever.   generator (TFPreTrainedModel) —
A seq2seq model used as the generator in the RAG architecture.   retriever (RagRetriever) —
A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.    The TFRagTokenForGeneration forward method, overrides the __call__ special method. Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing


TFRagTokenForGeneration

steps while
the latter silently ignores them. A TF RAG-token model implementation. It performs RAG-token specific marginalization in the forward pass. RAG is a sequence-to-sequence model which encapsulates two core components: a question encoder and a generator.
During a forward pass, we encode the input with the question encoder and pass it to the retriever to extract
relevant context documents. The documents are then prepended to the input. Such contextualized inputs is passed to
the generator. The question encoder can be any autoencoding model, preferably TFDPRQuestionEncoder, and the generator can be
any seq2seq model, preferably TFBartForConditionalGeneration. The model can be initialized with a RagRetriever for end-to-end generation or used in combination with the
outputs of a retriever in multiple steps---see examples for more details. The model is compatible any
autoencoding model as the question_encoder and any seq2seq model with language model head as the generator.
It


TFRagTokenForGeneration

has been tested with TFDPRQuestionEncoder as the question_encoder and TFBartForConditionalGeneration
as the generator. This model inherits from TFPreTrainedModel. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.) This model is also a Tensorflow tf.keras.Model
subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to
general usage and behavior. The model is in a developing state as it is now fully supports in eager-mode only, and may not be exported in
SavedModel format.  call  < source > ( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None decoder_input_ids: np.ndarray | tf.Tensor | None = None decoder_attention_mask: np.ndarray | tf.Tensor | None = None encoder_outputs: np.ndarray | tf.Tensor | None = None past_key_values: Tuple[Tuple[Union[np.ndarray


TFRagTokenForGeneration

, tf.Tensor]]] | None = None doc_scores: np.ndarray | tf.Tensor | None = None context_input_ids: np.ndarray | tf.Tensor | None = None context_attention_mask: np.ndarray | tf.Tensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None output_retrieved: bool | None = None n_docs: int | None = None do_marginalize: bool | None = None labels: np.ndarray | tf.Tensor | None = None reduce_loss: bool | None = None return_dict: bool | None = None training: bool = False **kwargs  ) → transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput or tuple(tf.Tensor)  Parameters   input_ids (tf.Tensor of shape (batch_size, sequence_length)) —
Indices of input sequence tokens in the vocabulary. RagConfig, used to initialize the model, specifies
which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to
obtain the indices.   attention_mask (tf.Tensor of shape (batch_size, seque


TFRagTokenForGeneration

nce_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?   encoder_outputs (tuple(tuple(tf.Tensor), optional) —
Tuple consists of (generator_enc_last_hidden_state, optional: generator_enc_hidden_states,
optional: generator_enc_attentions). generator_enc_last_hidden_state of shape (batch_size, n_docs * sequence_length, hidden_size) is a sequence of hidden-states at the output of the last layer of the
generator’s encoder.
Used by the (TFRagModel) model during decoding.   decoder_input_ids (tf.Tensor of shape (batch_size, target_sequence_length), optional) —
Provide for generation tasks. None by default, construct as per instructions for the generator model
you’re using with your RAG instance.   decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), optional) —
Default behavior: generate a tensor that


TFRagTokenForGeneration

ignores pad tokens in decoder_input_ids. Causal mask will also
be used by default.   past_key_values (tuple(tuple(tf.Tensor))) —
Tuple consists of two elements: encoder_outputs of the RAG model (see encoder_outputs) and
past_key_values of the underlying generator. Can be used to speed up decoding. past_key_values are used
in the (RagTokenForGeneration) model during decoding.   doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) —
Score between each retrieved document embeddings (see retrieved_doc_embeds) and
question_encoder_last_hidden_state. If the model has is not initialized with a retriever doc_scores
has to be provided to the forward pass. doc_scores can be computed via
question_encoder_last_hidden_state and retrieved_doc_embeds, see examples for more information.   context_input_ids (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) —
Input IDs post-processed from the retrieved documents and


TFRagTokenForGeneration

the question encoder input_ids by the
retriever.
If the model has is not initialized with a retriever `context_input_ids has to be provided to the
forward pass. context_input_ids are returned by __call__(). context_attention_mask
(tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when
output_retrieved=True): Attention mask post-processed from the retrieved documents and the question
encoder input_ids by the retriever.
If the model has is not initialized with a retriever context_attention_mask has to be provided to the
forward pass. context_attention_mask are returned by __call__().   use_cache (bool, optional, defaults to True) —
If set to True, past_key_values key value states are returned and can be used to speed up decoding (see
past_key_values).   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_state


TFRagTokenForGeneration

s (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   output_retrieved(bool, optional) —
Whether or not to return the retrieved_doc_embeds, retrieved_doc_ids, context_input_ids and
context_attention_mask. See returned tensors for more detail.   return_dict (bool, optional) —
Whether or not to return a TFRetrievAugLMOutput instead of a plain tuple.   n_docs (int, optional, defaults to `config.n_docs“) —
Number of documents to retrieve and/or number of documents for which to generate an answer.   do_marginalize (bool, optional) —
If True, the logits are marginalized over all documents by making use of
torch.nn.functional.log_softmax.   labels (tf.Tensor or np.ndarray of shape (batch_size, sequence_length), optional) —
Labels for computing the cross entropy classification loss according to Rag-Token model formulation See
https://arxiv.org/pdf/2005.11401.pdf Section 2.1 for details about Rag-Token fo


TFRagTokenForGeneration

rmulation. Indices should be
in [0, ..., config.vocab_size - 1].   reduce_loss (bool, optional) —
Only relevant if labels is passed. If True, the NLL loss is reduced using the tf.Tensor.sum
operation.   kwargs (Dict[str, any], optional, defaults to {}) —
Legacy dictionary, which is required so that model can use generate() function.   Returns
transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput or tuple(tf.Tensor)

A transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput or a tuple of tf.Tensor (if
return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the
configuration (RagConfig) and inputs.
loss (tf.Tensor of shape (1,), optional, returned when labels is provided) — Language modeling loss.
logits (tf.Tensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head. The score is possibly marginalized over all documents for
each vocabulary token.
past_k


TFRagTokenForGeneration

ey_values (List[tf.Tensor], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of tf.Tensor of length config.n_layers, with each tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)).
Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used
(see past_key_values input) to speed up sequential decoding.
doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and
question_encoder_last_hidden_state.
retrieved_doc_embeds (tf.Tensor of shape (batch_size, config.n_docs, hidden_size), optional, returned when output_retrieved=True) — Embedded documents retrieved by the retriever. Is used with question_encoder_last_hidden_state to compute
the doc_scores.
retrieved_doc_ids (tf.Tensor (int32) of shape (batch_size, config.n_docs), optional, returned when output_retrieved=True) — The indexes of the em


TFRagTokenForGeneration

bedded documents retrieved by the retriever.
context_input_ids (tf.Tensor(int32) of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.
context_attention_mask (tf.Tensor (int32) of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the
retriever.
question_encoder_last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden states at the output of the last layer of the question encoder pooled output of the
model.
question_enc_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 emb


TFRagTokenForGeneration

eddings and one for the output of each layer) of shape
(batch_size, sequence_length, hidden_size).
Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.
question_enc_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights of the question encoder, after the attention softmax, used to compute the weighted
average in the self-attention heads.
generator_enc_last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the generator encoder of the model.
generator_enc_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 emb


TFRagTokenForGeneration

eddings and one for the output of each layer) of shape
(batch_size, sequence_length, hidden_size).
Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.
generator_enc_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted
average in the self-attention heads.
generator_dec_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 and one for the output of each layer) of shape
(batch_size, sequence_length, hidden_size).
Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.


TFRagTokenForGeneration

generator_dec_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted
average in the self-attention heads.
  The TFRagTokenForGeneration forward method, overrides the __call__ special method. Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.  Example:   Copied >>> import tensorflow as tf
>>> from transformers import AutoTokenizer, RagRetriever, TFRagTokenForGeneration
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-token-nq")
>>> retriever = RagRetriever.from_pretrained(
...     "facebook/


TFRagTokenForGeneration

rag-token-nq", index_name="exact", use_dummy_dataset=True
... )
>>> # initialize with RagRetriever to do everything in one forward call
>>> model = TFRagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever, from_pt=True)
>>> input_dict = tokenizer.prepare_seq2seq_batch(
...     "How many people live in Paris?", "In Paris, there are 10 million people.", return_tensors="tf"
... )
>>> outputs = model(input_dict, output_retrieved=True)
>>> # or use retriever separately
>>> # 1. Encode
>>> input_ids = input_dict["input_ids"]
>>> question_hidden_states = model.question_encoder(input_ids)[0]
>>> # 2. Retrieve
>>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.numpy(), return_tensors="tf")
>>> doc_scores = tf.squeeze(
...     tf.matmul(
...         tf.expand_dims(question_hidden_states, axis=1), docs_dict["retrieved_doc_embeds"], transpose_b=True
...     ),
...     axis=1,
... )
>>> # 3. Forward to generator
>>> outputs = model(
...     inputs=


TFRagTokenForGeneration

None,
...     context_input_ids=docs_dict["context_input_ids"],
...     context_attention_mask=docs_dict["context_attention_mask"],
...     doc_scores=doc_scores,
...     decoder_input_ids=input_dict["labels"],
... )
>>> # or directly generate
>>> generated = model.generate(
...     context_input_ids=docs_dict["context_input_ids"],
...     context_attention_mask=docs_dict["context_attention_mask"],
...     doc_scores=doc_scores,
... )
>>> generated_string = tokenizer.batch_decode(generated, skip_special_tokens=True)  generate  < source > ( input_ids: TFModelInputType | None = None attention_mask: tf.Tensor | None = None context_input_ids = None context_attention_mask = None doc_scores = None n_docs = None generation_config = None logits_processor = [] **kwargs  ) → tf.Tensor of shape (batch_size * num_return_sequences, sequence_length)  Parameters   input_ids (tf.Tensor of shape (batch_size, sequence_length), optional) —
The sequence used as a prompt for the generation. If input_


TFRagTokenForGeneration

ids is not passed, then
context_input_ids has to be provided.   attention_mask (tf.Tensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?   context_input_ids (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) —
Input IDs post-processed from the retrieved documents and the question encoder input_ids by the
retriever.
If the model has is not initialized with a retriever, context_input_ids has to be provided to the
forward pass. context_input_ids are returned by __call__().   context_attention_mask (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) —
Attention mask post-processed from the retrieved documents and the question encoder input_ids by the
retr


TFRagTokenForGeneration

iever.
If the model has is not initialized with a retriever, context_input_ids has to be provided to the
forward pass. context_input_ids are returned by __call__().   doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) —
Score between each retrieved document embeddings (see retrieved_doc_embeds) and
question_encoder_last_hidden_state.
If the model has is not initialized with a retriever, context_input_ids has to be provided to the
forward pass. context_input_ids are returned by __call__().   n_docs (int, optional, defaults to config.n_docs) —
Number of documents to retrieve and/or number of documents for which to generate an answer.   generation_config (~generation.GenerationConfig, optional) —
The generation configuration to be used as base parametrization for the generation call. **kwargs
passed to generate matching the attributes of generation_config will override them. If
generation_config is not provided, the default will be used, which had the following loading
prio


TFRagTokenForGeneration

rity: 1) from the generation_config.json model file, if it exists; 2) from the model
configuration. Please note that unspecified parameters will inherit GenerationConfig’s
default values, whose documentation should be checked to parameterize generation.   logits_processor (TFLogitsProcessorList, optional) —
Custom logits processors that complement the default logits processors built from arguments and a
model’s config. If a logit processor is passed that is already created with the arguments or a model’s
config an error is thrown.   kwargs (Dict[str, Any], optional) —
Ad hoc parametrization of generate_config and/or additional model-specific kwargs that will be
forwarded to the forward function of the model.   Returns
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.
  Implements TFRAG token decod


Overview

The TrOCR model was proposed in TrOCR: Transformer-based Optical Character Recognition with Pre-trained
Models by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang,
Zhoujun Li, Furu Wei. TrOCR consists of an image Transformer encoder and an autoregressive text Transformer decoder to
perform optical character recognition (OCR).
The abstract from the paper is the following:
Text recognition is a long-standing research problem for document digitalization. Existing approaches for text recognition
are usually built based on CNN for image understanding and RNN for char-level text generation. In addition, another language
model is usually needed to improve the overall accuracy as a post-processing step. In this paper, we propose an end-to-end
text recognition approach with pre-trained image Transformer and text Transformer models, namely TrOCR, which leverages the
Transformer architecture for both image understanding and wordpiece-level text generation. The TrOC


Overview

R model is simple but
effective, and can be pre-trained with large-scale synthetic data and fine-tuned with human-labeled datasets. Experiments
show that the TrOCR model outperforms the current state-of-the-art models on both printed and handwritten text recognition
tasks.
TrOCR architecture. Taken from the original paper.
Please refer to the VisionEncoderDecoder class on how to use this model.
This model was contributed by nielsr. The original code can be found
here.
Tips:
The quickest way to get started with TrOCR is by checking the tutorial
notebooks, which show how to use the model
at inference time as well as fine-tuning on custom data. TrOCR is pre-trained in 2 stages before being fine-tuned on downstream datasets. It achieves state-of-the-art results
on both printed (e.g. the SROIE dataset and handwritten (e.g. the IAM
Handwriting dataset text recognition tasks. For more
information, see the official models. TrOCR is always used within the VisionEncoderDecoder framework


Resources

A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with TrOCR. If you’re interested in submitting a resource to be included here, please feel free to open a Pull Request and we’ll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource.
 Text Classification
A blog post on Accelerating Document AI with TrOCR. A blog post on how to Document AI with TrOCR. A notebook on how to finetune TrOCR on IAM Handwriting Database using Seq2SeqTrainer. A notebook on inference with TrOCR and Gradio demo. A notebook on finetune TrOCR on the IAM Handwriting Database using native PyTorch. A notebook on evaluating TrOCR on the IAM test set.
 Text Generation
Casual language modeling task guide.
⚡ Inference
An interactive-demo on TrOCR handwritten character recognition.


Inference

TrOCR’s VisionEncoderDecoder model accepts images as input and makes use of
generate() to autoregressively generate text given the input image.
The [ViTImageProcessor/DeiTImageProcessor] class is responsible for preprocessing the input image and
[RobertaTokenizer/XLMRobertaTokenizer] decodes the generated target tokens to the target string. The
TrOCRProcessor wraps [ViTImageProcessor/DeiTImageProcessor] and [RobertaTokenizer/XLMRobertaTokenizer]
into a single instance to both extract the input features and decode the predicted token ids.
Step-by-step Optical Character Recognition (OCR)
  Copied >>> from transformers import TrOCRProcessor, VisionEncoderDe


Inference

coderModel
>>> import requests
>>> from PIL import Image
>>> processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
>>> model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
>>> # load image from the IAM dataset
>>> url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
>>> pixel_values = processor(image, return_tensors="pt").pixel_values
>>> generated_ids = model.generate(pixel_values)
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
See the model hub to look for TrOCR checkpoints.


TrOCRConfig

class transformers.TrOCRConfig  < source > ( vocab_size = 50265 d_model = 1024 decoder_layers = 12 decoder_attention_heads = 16 decoder_ffn_dim = 4096 activation_function = 'gelu' max_position_embeddings = 512 dropout = 0.1 attention_dropout = 0.0 activation_dropout = 0.0 decoder_start_token_id = 2 init_std = 0.02 decoder_layerdrop = 0.0 use_cache = True scale_embedding = False use_learned_position_embeddings = True layernorm_embedding = True pad_token_id = 1 bos_token_id = 0 eos_token_id = 2 **kwargs  )   Parameters   vocab_size (int, optional, defaults to 50265) —
Vocabulary size of the TrOCR model. Defines the number of different tokens that can be represented by the
inputs_ids passed when calling TrOCRForCausalLM.   d_model (int, optional, defaults to 1024) —
Dimensionality of the layers and the pooler layer.   decoder_layers (int, optional, defaults to 12) —
Number of decoder layers.   decoder_attention_heads (int, o


TrOCRConfig

ptional, defaults to 16) —
Number of attention heads for each attention layer in the Transformer decoder.   decoder_ffn_dim (int, optional, defaults to 4096) —
Dimensionality of the “intermediate” (often named feed-forward) layer in decoder.   activation_function (str or function, optional, defaults to "gelu") —
The non-linear activation function (function or string) in the pooler. If string, "gelu", "relu",
"silu" and "gelu_new" are supported.   max_position_embeddings (int, optional, defaults to 512) —
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048).   dropout (float, optional, defaults to 0.1) —
The dropout probability for all fully connected layers in the embeddings, and pooler.   attention_dropout (float, optional, defaults to 0.0) —
The dropout ratio for the attention probabilities.   activation_dropout (float, option


TrOCRConfig

al, defaults to 0.0) —
The dropout ratio for activations inside the fully connected layer.   init_std (float, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.   decoder_layerdrop (float, optional, defaults to 0.0) —
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
for more details.   use_cache (bool, optional, defaults to True) —
Whether or not the model should return the last key/values attentions (not used by all models).   scale_embedding (bool, optional, defaults to False) —
Whether or not to scale the word embeddings by sqrt(d_model).   use_learned_position_embeddings (bool, optional, defaults to True) —
Whether or not to use learned position embeddings. If not, sinusoidal position embeddings will be used.   layernorm_embedding (bool, optional, defaults to True) —
Whether or not to u


TrOCRConfig

se a layernorm after the word + position embeddings.    This is the configuration class to store the configuration of a TrOCRForCausalLM. It is used to instantiate an
TrOCR model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the TrOCR
microsoft/trocr-base-handwritten architecture. Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the
documentation from PretrainedConfig for more information.  Example:   Copied >>> from transformers import TrOCRConfig, TrOCRForCausalLM
>>> # Initializing a TrOCR-base style configuration
>>> configuration = TrOCRConfig()
>>> # Initializing a model (with random weights) from the TrOCR-base style configuration
>>> model = TrOCRForCausalLM(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config


TrOCRProcessor

class transformers.TrOCRProcessor  < source > ( image_processor = None tokenizer = None **kwargs  )   Parameters   image_processor ([ViTImageProcessor/DeiTImageProcessor], optional) —
An instance of [ViTImageProcessor/DeiTImageProcessor]. The image processor is a required input.   tokenizer ([RobertaTokenizer/XLMRobertaTokenizer], optional) —
An instance of [RobertaTokenizer/XLMRobertaTokenizer]. The tokenizer is a required input.    Constructs a TrOCR processor which wraps a vision image processor and a TrOCR tokenizer into a single processor. TrOCRProcessor offers all the functionalities of [ViTImageProcessor/DeiTImageProcessor] and
[RobertaTokenizer/XLMRobertaTokenizer]. See the call() and decode() for
more information.  __call__  < source > ( *args **kwargs  )    When used in normal mode, this method forwards all its arguments to AutoImageProcessor’s
__call__() and returns its output. If used in the context
as_target_processor() thi


TrOCRProcessor

s method forwards all its arguments to TrOCRTokenizer’s
~TrOCRTokenizer.__call__. Please refer to the doctsring of the above two methods for more information.  from_pretrained  < source > ( pretrained_model_name_or_path: typing.Union[str, os.PathLike] cache_dir: typing.Union[str, os.PathLike, NoneType] = None force_download: bool = False local_files_only: bool = False token: typing.Union[bool, str, NoneType] = None revision: str = 'main' **kwargs  )   Parameters   pretrained_model_name_or_path (str or os.PathLike) —
This can be either:
a string, the model id of a pretrained feature_extractor hosted inside a model repo on
huggingface.co. Valid model ids can be located at the root-level, like bert-base-uncased, or
namespaced under a user or organization name, like dbmdz/bert-base-german-cased.
a path to a directory containing a feature extractor file saved using the
save_pretrained() method, e.g., ./my_model_directory/.
a path or url to a


TrOCRProcessor

 saved feature extractor JSON file, e.g.,
./my_model_directory/preprocessor_config.json.
**kwargs —
Additional keyword arguments passed along to both
from_pretrained() and
~tokenization_utils_base.PreTrainedTokenizer.from_pretrained.
    Instantiate a processor associated with a pretrained model. This class method is simply calling the feature extractor
from_pretrained(), image processor
ImageProcessingMixin and the tokenizer
~tokenization_utils_base.PreTrainedTokenizer.from_pretrained methods. Please refer to the docstrings of the
methods above for more information.  save_pretrained  < source > ( save_directory push_to_hub: bool = False **kwargs  )   Parameters   save_directory (str or os.PathLike) —
Directory where the feature extractor JSON file and the tokenizer files will be saved (directory will
be created if it does not exist).   push_to_hub (bool, optional, defaults to False) —
Whether or not to push your model to the Hugging Fa


TrOCRProcessor

ce model hub after saving it. You can specify the
repository you want to push to with repo_id (will default to the name of save_directory in your
namespace).   kwargs (Dict[str, Any], optional) —
Additional key word arguments passed along to the push_to_hub() method.    Saves the attributes of this processor (feature extractor, tokenizer…) in the specified directory so that it
can be reloaded using the from_pretrained() method. This class method is simply calling save_pretrained() and
save_pretrained(). Please refer to the docstrings of the
methods above for more information.  batch_decode  < source > ( *args **kwargs  )    This method forwards all its arguments to TrOCRTokenizer’s batch_decode(). Please refer
to the docstring of this method for more information.  decode  < source > ( *args **kwargs  )    This method forwards all its arguments to TrOCRTokenizer’s decode(). Please refer to the
docstring of this method for more informatio


TrOCRForCausalLM

class transformers.TrOCRForCausalLM  < source > ( config  )   Parameters   config (TrOCRConfig) —
Model configuration class with all the parameters of the model. Initializing with a config file does not
load the weights associated with the model, only the configuration. Check out the
from_pretrained() method to load the model weights.    The TrOCR Decoder with a language modeling head. Can be used as the decoder part of EncoderDecoderModel and VisionEncoderDecoder.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.) This model is also a PyTorch torch.nn.Module subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.  forward  < source > ( input_ids: typing.Optional[torch.LongTensor] = Non


TrOCRForCausalLM

e attention_mask: typing.Optional[torch.Tensor] = None encoder_hidden_states: typing.Optional[torch.FloatTensor] = None encoder_attention_mask: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None  ) → transformers.modeling_outputs.CausalLMOutputWithCrossAttentions or tuple(torch.FloatTensor)  Parameters   input_ids (torch.LongTensor of shape (batch_size, sequence_length)) —
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provid


TrOCRForCausalLM

e it.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and
PreTrainedTokenizer.call() for details.
What are input IDs?   attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?   encoder_hidden_states  (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) —
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
if the model is configured as a decoder.   encoder_attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
in the cross-attention if the model is configured as a decoder. Mask values selected


TrOCRForCausalLM

in [0, 1]:   head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) —
Mask to nullify selected heads of the attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   cross_attn_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) —
Mask to nullify selected heads of the cross-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) —
Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of
shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of
shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). The two additional
ten


TrOCRForCausalLM

sors are only required when the model is used as a decoder in a Sequence to Sequence model.
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding.
If past_key_values are used, the user can optionally input only the last decoder_input_ids (those
that don’t have their past key value states given to this model) of shape (batch_size, 1) instead of
all decoder_input_ids of shape (batch_size, sequence_length).   labels (torch.LongTensor of shape (batch_size, sequence_length), optional) —
Labels for computing the masked language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored
(masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size].   use_cache (bool, optional) —
If set t


TrOCRForCausalLM

o True, past_key_values key value states are returned and can be used to speed up decoding
(see past_key_values).
1 for tokens that are not masked,
0 for tokens that are masked.
   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under
returned tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors
for more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   Returns
transformers.modeling_outputs.CausalLMOutputWithCrossAttentions or tuple(torch.FloatTensor)

A transformers.modeling_outputs.CausalLMOutputWithCrossAttentions or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (TrOCRConfig) and in


TrOCRForCausalLM

puts.
loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Language modeling loss (for next-token prediction).
logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
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, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) o


TrOCRForCausalLM

f shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Cross attentions weights after the attention softmax, used to compute the weighted average in the
cross-attention heads.
past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of torch.FloatTensor tuples of length config.n_layers, with each tuple containing the cached key,
value states of the self-attention and the cross-attention layers if model is used in encoder-decoder
setting. Only relevant if config.is_decoder = True.
C


TrOCRForCausalLM

ontains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
past_key_values input) to speed up sequential decoding.
   Example:   Copied >>> from transformers import (
...     TrOCRConfig,
...     TrOCRProcessor,
...     TrOCRForCausalLM,
...     ViTConfig,
...     ViTModel,
...     VisionEncoderDecoderModel,
... )
>>> import requests
>>> from PIL import Image
>>> # TrOCR is a decoder model and should be used within a VisionEncoderDecoderModel
>>> # init vision2text model with random weights
>>> encoder = ViTModel(ViTConfig())
>>> decoder = TrOCRForCausalLM(TrOCRConfig())
>>> model = VisionEncoderDecoderModel(encoder=encoder, decoder=decoder)
>>> # If you want to start from the pretrained model, load the checkpoint with `VisionEncoderDecoderModel`
>>> processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
>>> model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-b


TrOCRForCausalLM

ase-handwritten")
>>> # load image from the IAM dataset
>>> url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
>>> pixel_values = processor(image, return_tensors="pt").pixel_values
>>> text = "industry, ' Mr. Brown commented icily. ' Let us have a"
>>> # training
>>> model.config.decoder_start_token_id = processor.tokenizer.cls_token_id
>>> model.config.pad_token_id = processor.tokenizer.pad_token_id
>>> model.config.vocab_size = model.config.decoder.vocab_size
>>> labels = processor.tokenizer(text, return_tensors="pt").input_ids
>>> outputs = model(pixel_values, labels=labels)
>>> loss = outputs.loss
>>> round(loss.item(), 2)
5.30
>>> # inference
>>> generated_ids = model.generate(pixel_values)
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> generated_text
'industry, " Mr. Brown commented icily. " Let us have a


Overview

The SpeechT5 model was proposed in SpeechT5: Unified-Modal Encoder-Decoder Pre-Training for Spoken Language Processing by Junyi Ao, Rui Wang, Long Zhou, Chengyi Wang, Shuo Ren, Yu Wu, Shujie Liu, Tom Ko, Qing Li, Yu Zhang, Zhihua Wei, Yao Qian, Jinyu Li, Furu Wei.
The abstract from the paper is the following:
Motivated by the success of T5 (Text-To-Text Transfer Transformer) in pre-trained natural language processing models, we propose a unified-modal SpeechT5 framework that explores the encoder-decoder pre-training for self-supervised speech/text representation learning. The SpeechT5 framework consists of a shared encoder-decoder network and six modal-specific (speech/text) pre/post-nets. After preprocessing the input speech/text through the pre-nets, the shared encoder-decoder network models the sequence-to-sequence transformation, and then the post-n


Overview

ets generate the output in the speech/text modality based on the output of the decoder. Leveraging large-scale unlabeled speech and text data, we pre-train SpeechT5 to learn a unified-modal representation, hoping to improve the modeling capability for both speech and text. To align the textual and speech information into this unified semantic space, we propose a cross-modal vector quantization approach that randomly mixes up speech/text states with latent units as the interface between encoder and decoder. Extensive evaluations show the superiority of the proposed SpeechT5 framework on a wide variety of spoken language processing tasks, including automatic speech recognition, speech synthesis, speech translation, voice conversion, speech enhancement, and speaker identification.
This model was contributed by Matthijs. The original code can be found here.


SpeechT5Config

class transformers.SpeechT5Config  < source > ( vocab_size = 81 hidden_size = 768 encoder_layers = 12 encoder_attention_heads = 12 encoder_ffn_dim = 3072 encoder_layerdrop = 0.1 decoder_layers = 6 decoder_ffn_dim = 3072 decoder_attention_heads = 12 decoder_layerdrop = 0.1 hidden_act = 'gelu' positional_dropout = 0.1 hidden_dropout = 0.1 attention_dropout = 0.1 activation_dropout = 0.1 initializer_range = 0.02 layer_norm_eps = 1e-05 scale_embedding = False feat_extract_norm = 'group' feat_proj_dropout = 0.0 feat_extract_activation = 'gelu' conv_dim = (512, 512, 512, 512, 512, 512, 512) conv_stride = (5, 2, 2, 2, 2, 2, 2) conv_kernel = (10, 3, 3, 3, 3, 2, 2) conv_bias = False num_conv_pos_embeddings = 128 num_conv_pos_embedding_groups = 16 apply_spec_augment = True mask_time_prob = 0.05 mask_time_length = 10 mask_time_min_masks = 2 mask_feature_prob = 0.0 mask_feature_length = 10 mask_feature_min_masks = 0 pad_token_id = 1 bos_token_id = 0 eos_token_id = 2 d


SpeechT5Config

ecoder_start_token_id = 2 num_mel_bins = 80 speech_decoder_prenet_layers = 2 speech_decoder_prenet_units = 256 speech_decoder_prenet_dropout = 0.5 speaker_embedding_dim = 512 speech_decoder_postnet_layers = 5 speech_decoder_postnet_units = 256 speech_decoder_postnet_kernel = 5 speech_decoder_postnet_dropout = 0.5 reduction_factor = 2 max_speech_positions = 4000 max_text_positions = 450 encoder_max_relative_position = 160 use_guided_attention_loss = True guided_attention_loss_num_heads = 2 guided_attention_loss_sigma = 0.4 guided_attention_loss_scale = 10.0 use_cache = True is_encoder_decoder = True **kwargs  )   Parameters   vocab_size (int, optional, defaults to 81) —
Vocabulary size of the SpeechT5 model. Defines the number of different tokens that can be represented by
the inputs_ids passed to the forward method of SpeechT5Model.   hidden_size (int, optional, defaults to 768) —
Dimensionality of the encoder layers and the pooler layer.   encoder_layers


SpeechT5Config

(int, optional, defaults to 12) —
Number of hidden layers in the Transformer encoder.   encoder_attention_heads (int, optional, defaults to 12) —
Number of attention heads for each attention layer in the Transformer encoder.   encoder_ffn_dim (int, optional, defaults to 3072) —
Dimensionality of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder.   encoder_layerdrop (float, optional, defaults to 0.1) —
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
for more details.   decoder_layers (int, optional, defaults to 6) —
Number of hidden layers in the Transformer decoder.   decoder_attention_heads (int, optional, defaults to 12) —
Number of attention heads for each attention layer in the Transformer decoder.   decoder_ffn_dim (int, optional, defaults to 3072) —
Dimensionality of the “intermediate” (often named feed-forward) layer in the Transformer decoder.   decoder_layerdrop (flo


SpeechT5Config

at, optional, defaults to 0.1) —
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
for more details.   hidden_act (str or function, optional, defaults to "gelu") —
The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu",
"relu", "selu" and "gelu_new" are supported.   positional_dropout (float, optional, defaults to 0.1) —
The dropout probability for the text position encoding layers.   hidden_dropout (float, optional, defaults to 0.1) —
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.   attention_dropout (float, optional, defaults to 0.1) —
The dropout ratio for the attention probabilities.   activation_dropout (float, optional, defaults to 0.1) —
The dropout ratio for activations inside the fully connected layer.   initializer_range (float, optional, defaults to 0.02) —
The standard deviation of the truncated_


SpeechT5Config

normal_initializer for initializing all weight matrices.   layer_norm_eps (float, optional, defaults to 1e-5) —
The epsilon used by the layer normalization layers.   scale_embedding (bool, optional, defaults to False) —
Scale embeddings by diving by sqrt(d_model).   feat_extract_norm (str, optional, defaults to "group") —
The norm to be applied to 1D convolutional layers in the speech encoder pre-net. One of "group" for group
normalization of only the first 1D convolutional layer or "layer" for layer normalization of all 1D
convolutional layers.   feat_proj_dropout (float, optional, defaults to 0.0) —
The dropout probability for output of the speech encoder pre-net.   feat_extract_activation (str, optional, defaults to “gelu”) -- The non-linear activation function (function or string) in the 1D convolutional layers of the feature extractor. If string, “gelu”, “relu”, “selu”and“gelu_new”` are supported.   conv_dim (Tuple[int] or List[int], optional, default


SpeechT5Config

s to (512, 512, 512, 512, 512, 512, 512)) —
A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
speech encoder pre-net. The length of conv_dim defines the number of 1D convolutional layers.   conv_stride (Tuple[int] or List[int], optional, defaults to (5, 2, 2, 2, 2, 2, 2)) —
A tuple of integers defining the stride of each 1D convolutional layer in the speech encoder pre-net. The
length of conv_stride defines the number of convolutional layers and has to match the length of
conv_dim.   conv_kernel (Tuple[int] or List[int], optional, defaults to (10, 3, 3, 3, 3, 3, 3)) —
A tuple of integers defining the kernel size of each 1D convolutional layer in the speech encoder pre-net.
The length of conv_kernel defines the number of convolutional layers and has to match the length of
conv_dim.   conv_bias (bool, optional, defaults to False) —
Whether the 1D convolutional layers have a bias.   num_conv_pos_embeddi


SpeechT5Config

ngs (int, optional, defaults to 128) —
Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
embeddings layer.   num_conv_pos_embedding_groups (int, optional, defaults to 16) —
Number of groups of 1D convolutional positional embeddings layer.   apply_spec_augment (bool, optional, defaults to True) —
Whether to apply SpecAugment data augmentation to the outputs of the speech encoder pre-net. For
reference see SpecAugment: A Simple Data Augmentation Method for Automatic Speech
Recognition.   mask_time_prob (float, optional, defaults to 0.05) —
Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
procecure generates ”mask_time_problen(time_axis)/mask_time_length” independent masks over the axis. If
reasoning from the propability of each feature vector to be chosen as the start of the vector span to be
masked, mask_time_prob should be `prob_vector_startmask_tim


SpeechT5Config

e_length. Note that overlap may decrease the actual percentage of masked vectors. This is only relevant if apply_spec_augment is True`.   mask_time_length (int, optional, defaults to 10) —
Length of vector span along the time axis.   mask_time_min_masks (int, optional, defaults to 2), —
The minimum number of masks of length mask_feature_length generated along the time axis, each time step,
irrespectively of mask_feature_prob. Only relevant if ”mask_time_prob*len(time_axis)/mask_time_length <
mask_time_min_masks”   mask_feature_prob (float, optional, defaults to 0.0) —
Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
masking procecure generates ”mask_feature_problen(feature_axis)/mask_time_length” independent masks over
the axis. If reasoning from the propability of each feature vector to be chosen as the start of the vector
span to be masked, mask_feature_prob should be `prob_vector_startmask_feature_leng


SpeechT5Config

th. Note that overlap may decrease the actual percentage of masked vectors. This is only relevant if apply_spec_augment is
True`.   mask_feature_length (int, optional, defaults to 10) —
Length of vector span along the feature axis.   mask_feature_min_masks (int, optional, defaults to 0), —
The minimum number of masks of length mask_feature_length generated along the feature axis, each time
step, irrespectively of mask_feature_prob. Only relevant if
”mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks”   num_mel_bins (int, optional, defaults to 80) —
Number of mel features used per input features. Used by the speech decoder pre-net. Should correspond to
the value used in the SpeechT5Processor class.   speech_decoder_prenet_layers (int, optional, defaults to 2) —
Number of layers in the speech decoder pre-net.   speech_decoder_prenet_units (int, optional, defaults to 256) —
Dimensionality of the layers in the speech decoder pre-n


SpeechT5Config

et.   speech_decoder_prenet_dropout (float, optional, defaults to 0.5) —
The dropout probability for the speech decoder pre-net layers.   speaker_embedding_dim (int, optional, defaults to 512) —
Dimensionality of the XVector embedding vectors.   speech_decoder_postnet_layers (int, optional, defaults to 5) —
Number of layers in the speech decoder post-net.   speech_decoder_postnet_units (int, optional, defaults to 256) —
Dimensionality of the layers in the speech decoder post-net.   speech_decoder_postnet_kernel (int, optional, defaults to 5) —
Number of convolutional filter channels in the speech decoder post-net.   speech_decoder_postnet_dropout (float, optional, defaults to 0.5) —
The dropout probability for the speech decoder post-net layers.   reduction_factor (int, optional, defaults to 2) —
Spectrogram length reduction factor for the speech decoder inputs.   max_speech_positions (int, optional, defaults to 4000) —
The maximum sequence length of speec


SpeechT5Config

h features that this model might ever be used with.   max_text_positions (int, optional, defaults to 450) —
The maximum sequence length of text features that this model might ever be used with.   encoder_max_relative_position (int, optional, defaults to 160) —
Maximum distance for relative position embedding in the encoder.   use_guided_attention_loss (bool, optional, defaults to True) —
Whether to apply guided attention loss while training the TTS model.   guided_attention_loss_num_heads (int, optional, defaults to 2) —
Number of attention heads the guided attention loss will be applied to. Use -1 to apply this loss to all
attention heads.   guided_attention_loss_sigma (float, optional, defaults to 0.4) —
Standard deviation for guided attention loss.   guided_attention_loss_scale (float, optional, defaults to 10.0) —
Scaling coefficient for guided attention loss (also known as lambda).   use_cache (bool, optional, defaults to True) —
Whether or not the mo


SpeechT5Config

del should return the last key/values attentions (not used by all models).    This is the configuration class to store the configuration of a SpeechT5Model. It is used to instantiate a
SpeechT5 model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the SpeechT5
microsoft/speecht5_asr architecture. Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the
documentation from PretrainedConfig for more information.  Example:   Copied >>> from transformers import SpeechT5Model, SpeechT5Config
>>> # Initializing a "microsoft/speecht5_asr" style configuration
>>> configuration = SpeechT5Config()
>>> # Initializing a model (with random weights) from the "microsoft/speecht5_asr" style configuration
>>> model = SpeechT5Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model


class transformers.SpeechT5HifiGanConfig  < source > ( model_in_dim = 80 sampling_rate = 16000 upsample_initial_channel = 512 upsample_rates = [4, 4, 4, 4] upsample_kernel_sizes = [8, 8, 8, 8] resblock_kernel_sizes = [3, 7, 11] resblock_dilation_sizes = [[1, 3, 5], [1, 3, 5], [1, 3, 5]] initializer_range = 0.01 leaky_relu_slope = 0.1 normalize_before = True **kwargs  )   Parameters   model_in_dim (int, optional, defaults to 80) —
The number of frequency bins in the input log-mel spectrogram.   sampling_rate (int, optional, defaults to 16000) —
The sampling rate at which the output audio will be generated, expressed in hertz (Hz).   upsample_initial_channel (int, optional, defaults to 512) —
The number of input channels into the upsampling network.   upsample_rates (Tuple[int] or List[int], optional, def


aults to [4, 4, 4, 4]) —
A tuple of integers defining the stride of each 1D convolutional layer in the upsampling network. The
length of upsample_rates defines the number of convolutional layers and has to match the length of
upsample_kernel_sizes.   upsample_kernel_sizes (Tuple[int] or List[int], optional, defaults to [8, 8, 8, 8]) —
A tuple of integers defining the kernel size of each 1D convolutional layer in the upsampling network. The
length of upsample_kernel_sizes defines the number of convolutional layers and has to match the length of
upsample_rates.   resblock_kernel_sizes (Tuple[int] or List[int], optional, defaults to [3, 7, 11]) —
A tuple of integers defining the kernel sizes of the 1D convolutional layers in the multi-receptive field
fusion (MRF) module.   resblock_dilation_sizes (Tuple[Tu


ple[int]] or List[List[int]], optional, defaults to [[1, 3, 5], [1, 3, 5], [1, 3, 5]]) —
A nested tuple of integers defining the dilation rates of the dilated 1D convolutional layers in the
multi-receptive field fusion (MRF) module.   initializer_range (float, optional, defaults to 0.01) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.   leaky_relu_slope (float, optional, defaults to 0.1) —
The angle of the negative slope used by the leaky ReLU activation.   normalize_before (bool, optional, defaults to True) —
Whether or not to normalize the spectrogram before vocoding using the vocoder’s learned mean and variance.    This is the configuration class to store the configuration of a SpeechT5HifiGanModel. It is used to instantiate
a SpeechT5 HiFi-GAN vocod


er model according to the specified arguments, defining the model architecture.
Instantiating a configuration with the defaults will yield a similar configuration to that of the SpeechT5
microsoft/speecht5_hifigan architecture. Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the
documentation from PretrainedConfig for more information.  Example:   Copied >>> from transformers import SpeechT5HifiGan, SpeechT5HifiGanConfig
>>> # Initializing a "microsoft/speecht5_hifigan" style configuration
>>> configuration = SpeechT5HifiGanConfig()
>>> # Initializing a model (with random weights) from the "microsoft/speecht5_hifigan" style configuration
>>> model = SpeechT5HifiGan(configuration)
>>> # Accessing the model configuration
>>> configuration = model.conf


SpeechT5Tokenizer

class transformers.SpeechT5Tokenizer  < source > ( vocab_file bos_token = '<s>' eos_token = '</s>' unk_token = '<unk>' pad_token = '<pad>' normalize = False sp_model_kwargs: typing.Union[typing.Dict[str, typing.Any], NoneType] = None **kwargs  )   Parameters   vocab_file (str) —
SentencePiece file (generally has a .spm extension) that
contains the vocabulary necessary to instantiate a tokenizer.   bos_token (str, optional, defaults to "<s>") —
The begin of sequence token.   eos_token (str, optional, defaults to "</s>") —
The end of sequence token.   unk_token (str, optional, defaults to "<unk>") —
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead.   pad_token (str, optional, defaults to "<pad>") —
The token used for padding, for example when batching sequences of different lengths.   normalize (bool, optional, defaults to False) —
Whether to convert numeric quantities in the text to their spelt-out english counter


SpeechT5Tokenizer

parts.   sp_model_kwargs (dict, optional) —
Will be passed to the SentencePieceProcessor.__init__() method. The Python wrapper for
SentencePiece can be used, among other things,
to set:
enable_sampling: Enable subword regularization.
nbest_size: Sampling parameters for unigram. Invalid for BPE-Dropout.
nbest_size = {0,1}: No sampling is performed.
nbest_size > 1: samples from the nbest_size results.
nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
using forward-filtering-and-backward-sampling algorithm.
alpha: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
BPE-dropout.
   sp_model (SentencePieceProcessor) —
The SentencePiece processor that is used for every conversion (string, tokens and IDs).    Construct a SpeechT5 tokenizer. Based on SentencePiece. This tokenizer inherits from PreTrainedTokenizer which contains most of the main methods. Users should refer to
this superclass for more informa


SpeechT5Tokenizer

tion regarding those methods.  __call__  < source > ( text: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None text_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None add_special_tokens: bool = True padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False truncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = None max_length: typing.Optional[int] = None stride: int = 0 is_split_into_words: bool = False pad_to_multiple_of: typing.Optional[int] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_token_type_ids: typing.Optional[bool] = None return_attention_mask: typing.Optional[bool] = None return_overflowing_tokens: bool


SpeechT5Tokenizer

= False return_special_tokens_mask: bool = False return_offsets_mapping: bool = False return_length: bool = False verbose: bool = True **kwargs  ) → BatchEncoding  Parameters   text (str, List[str], List[List[str]], optional) —
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
is_split_into_words=True (to lift the ambiguity with a batch of sequences).   text_pair (str, List[str], List[List[str]], optional) —
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
is_split_into_words=True (to lift the ambiguity with a batch of sequences).   text_target (str, List[str], List[List[str]], optional) —
The sequence or batch of sequences to be encoded as target texts. Each sequence can be a string o


SpeechT5Tokenizer

r a
list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized),
you must set is_split_into_words=True (to lift the ambiguity with a batch of sequences).   text_pair_target (str, List[str], List[List[str]], optional) —
The sequence or batch of sequences to be encoded as target texts. Each sequence can be a string or a
list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized),
you must set is_split_into_words=True (to lift the ambiguity with a batch of sequences).   add_special_tokens (bool, optional, defaults to True) —
Whether or not to add special tokens when encoding the sequences. This will use the underlying
PretrainedTokenizerBase.build_inputs_with_special_tokens function, which defines which tokens are
automatically added to the input ids. This is usefull if you want to add bos or eos tokens
automatically.   padding (bool, str or PaddingStrategy, optional, defaults to False) —
Activates and


SpeechT5Tokenizer

controls padding. Accepts the following values:
True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single
sequence if provided).
'max_length': Pad to a maximum length specified with the argument max_length or to the maximum
acceptable input length for the model if that argument is not provided.
False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different
lengths).
   truncation (bool, str or TruncationStrategy, optional, defaults to False) —
Activates and controls truncation. Accepts the following values:
True or 'longest_first': Truncate to a maximum length specified with the argument max_length or
to the maximum acceptable input length for the model if that argument is not provided. This will
truncate token by token, removing a token from the longest sequence in the pair if a pair of
sequences (or a batch of pairs) is provided.
'only_first': Truncate to a maximum length specified with the argument max_length or t


SpeechT5Tokenizer

o the
maximum acceptable input length for the model if that argument is not provided. This will only
truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
'only_second': Truncate to a maximum length specified with the argument max_length or to the
maximum acceptable input length for the model if that argument is not provided. This will only
truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths
greater than the model maximum admissible input size).
   max_length (int, optional) —
Controls the maximum length to use by one of the truncation/padding parameters.
If left unset or set to None, this will use the predefined model maximum length if a maximum length
is required by one of the truncation/padding parameters. If the model has no specific maximum input
length (like XLNet) truncation/padding to a maximum


SpeechT5Tokenizer

length will be deactivated.   stride (int, optional, defaults to 0) —
If set to a number along with max_length, the overflowing tokens returned when
return_overflowing_tokens=True will contain some tokens from the end of the truncated sequence
returned to provide some overlap between truncated and overflowing sequences. The value of this
argument defines the number of overlapping tokens.   is_split_into_words (bool, optional, defaults to False) —
Whether or not the input is already pre-tokenized (e.g., split into words). If set to True, the
tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)
which it will tokenize. This is useful for NER or token classification.   pad_to_multiple_of (int, optional) —
If set will pad the sequence to a multiple of the provided value. Requires padding to be activated.
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
>= 7.5 (Volta).   return_tensors (st


SpeechT5Tokenizer

r or TensorType, optional) —
If set, will return tensors instead of list of python integers. Acceptable values are:
'tf': Return TensorFlow tf.constant objects.
'pt': Return PyTorch torch.Tensor objects.
'np': Return Numpy np.ndarray objects.
   return_token_type_ids (bool, optional) —
Whether to return token type IDs. If left to the default, will return the token type IDs according to
the specific tokenizer’s default, defined by the return_outputs attribute.
What are token type IDs?   return_attention_mask (bool, optional) —
Whether to return the attention mask. If left to the default, will return the attention mask according
to the specific tokenizer’s default, defined by the return_outputs attribute.
What are attention masks?   return_overflowing_tokens (bool, optional, defaults to False) —
Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch
of pairs) is provided with truncation_strategy = longest_first or True, an error is raised i


SpeechT5Tokenizer

nstead
of returning overflowing tokens.   return_special_tokens_mask (bool, optional, defaults to False) —
Whether or not to return special tokens mask information.   return_offsets_mapping (bool, optional, defaults to False) —
Whether or not to return (char_start, char_end) for each token.
This is only available on fast tokenizers inheriting from PreTrainedTokenizerFast, if using
Python’s tokenizer, this method will raise NotImplementedError.   return_length  (bool, optional, defaults to False) —
Whether or not to return the lengths of the encoded inputs.   verbose (bool, optional, defaults to True) —
Whether or not to print more information and warnings.
**kwargs — passed to the self.tokenize() method   Returns
BatchEncoding

A BatchEncoding with the following fields:
input_ids — List of token ids to be fed to a model.
What are input IDs?
token_type_ids — List of token type ids to be fed to a model (when return_token_type_ids=True or
if “token_type_ids” is in self.model_input_nam


SpeechT5Tokenizer

es).
What are token type IDs?
attention_mask — List of indices specifying which tokens should be attended to by the model (when
return_attention_mask=True or if “attention_mask” is in self.model_input_names).
What are attention masks?
overflowing_tokens — List of overflowing tokens sequences (when a max_length is specified and
return_overflowing_tokens=True).
num_truncated_tokens — Number of tokens truncated (when a max_length is specified and
return_overflowing_tokens=True).
special_tokens_mask — List of 0s and 1s, with 1 specifying added special tokens and 0 specifying
regular sequence tokens (when add_special_tokens=True and return_special_tokens_mask=True).
length — The length of the inputs (when return_length=True)
  Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
sequences.  save_vocabulary  < source > ( save_directory: str filename_prefix: typing.Optional[str] = None  )     decode  < source > ( token_ids: typing.Union[in


SpeechT5Tokenizer

t, typing.List[int], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')] skip_special_tokens: bool = False clean_up_tokenization_spaces: bool = None **kwargs  ) → str  Parameters   token_ids (Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]) —
List of tokenized input ids. Can be obtained using the __call__ method.   skip_special_tokens (bool, optional, defaults to False) —
Whether or not to remove special tokens in the decoding.   clean_up_tokenization_spaces (bool, optional) —
Whether or not to clean up the tokenization spaces. If None, will default to
self.clean_up_tokenization_spaces.   kwargs (additional keyword arguments, optional) —
Will be passed to the underlying model specific decode method.   Returns
str

The decoded sentence.
  Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
tokens and clean up tokenization spaces. Similar to doing self.convert_tokens_to_string(self.convert_ids


SpeechT5Tokenizer

_to_tokens(token_ids)).  batch_decode  < source > ( sequences: typing.Union[typing.List[int], typing.List[typing.List[int]], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')] skip_special_tokens: bool = False clean_up_tokenization_spaces: bool = None **kwargs  ) → List[str]  Parameters   sequences (Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]) —
List of tokenized input ids. Can be obtained using the __call__ method.   skip_special_tokens (bool, optional, defaults to False) —
Whether or not to remove special tokens in the decoding.   clean_up_tokenization_spaces (bool, optional) —
Whether or not to clean up the tokenization spaces. If None, will default to
self.clean_up_tokenization_spaces.   kwargs (additional keyword arguments, optional) —
Will be passed to the underlying model specific decode method.   Returns
List[str]

The list of decoded sentences.
  Convert a list of lists of token ids into a list of strings by calling de


class transformers.SpeechT5FeatureExtractor  < source > ( feature_size: int = 1 sampling_rate: int = 16000 padding_value: float = 0.0 do_normalize: bool = False num_mel_bins: int = 80 hop_length: int = 16 win_length: int = 64 win_function: str = 'hann_window' frame_signal_scale: float = 1.0 fmin: float = 80 fmax: float = 7600 mel_floor: float = 1e-10 reduction_factor: int = 2 return_attention_mask: bool = True **kwargs  )   Parameters   feature_size (int, optional, defaults to 1) —
The feature dimension of the extracted features.   sampling_rate (int, optional, defaults to 16000) —
The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).   padding_value (float, optional, defaults to 0.0) —
The value that is used to fill the padding values.   do_normalize (bool, optional, defaults to False) —
Whether or not to zero-mean unit-variance normalize the input. Normalizing can help to significantly
improve the performance for some models.   num_mel_


bins (int, optional, defaults to 80) —
The number of mel-frequency bins in the extracted spectrogram features.   hop_length (int, optional, defaults to 16) —
Number of ms between windows. Otherwise referred to as “shift” in many papers.   win_length (int, optional, defaults to 64) —
Number of ms per window.   win_function (str, optional, defaults to "hann_window") —
Name for the window function used for windowing, must be accessible via torch.{win_function}   frame_signal_scale (float, optional, defaults to 1.0) —
Constant multiplied in creating the frames before applying DFT. This argument is deprecated.   fmin (float, optional, defaults to 80) —
Minimum mel frequency in Hz.   fmax (float, optional, defaults to 7600) —
Maximum mel frequency in Hz.   mel_floor (float, optional, defaults to 1e-10) —
Minimum value of mel frequency banks.   reduction_factor (int, optional, defaults to 2) —
Spectrogram length reduction factor. This argument is deprecated.   return_attention_mas


k (bool, optional, defaults to True) —
Whether or not call() should return attention_mask.    Constructs a SpeechT5 feature extractor. This class can pre-process a raw speech signal by (optionally) normalizing to zero-mean unit-variance, for use by
the SpeechT5 speech encoder prenet. This class can also extract log-mel filter bank features from raw speech, for use by the SpeechT5 speech decoder
prenet. This feature extractor inherits from SequenceFeatureExtractor which contains
most of the main methods. Users should refer to this superclass for more information regarding those methods.  __call__  < source > ( audio: typing.Union[numpy.ndarray, typing.List[float], typing.List[numpy.ndarray], typing.List[typing.List[float]], NoneType] = None audio_target: typing.Union[numpy.ndarray, typing.List[float], typing.List[numpy.ndarray], typing.List[typing.List[float]], NoneType] = None padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False max_length: t


yping.Optional[int] = None truncation: bool = False pad_to_multiple_of: typing.Optional[int] = None return_attention_mask: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None sampling_rate: typing.Optional[int] = None **kwargs  )   Parameters   audio (np.ndarray, List[float], List[np.ndarray], List[List[float]], optional) —
The sequence or batch of sequences to be processed. Each sequence can be a numpy array, a list of float
values, a list of numpy arrays or a list of list of float values. This outputs waveform features. Must
be mono channel audio, not stereo, i.e. single float per timestep.   audio_target (np.ndarray, List[float], List[np.ndarray], List[List[float]], optional) —
The sequence or batch of sequences to be processed as targets. Each sequence can be a numpy array, a
list of float values, a list of numpy arrays or a list of list of float values. This outputs log-mel
spectrogram features.   paddi


ng (bool, str or PaddingStrategy, optional, defaults to False) —
Select a strategy to pad the returned sequences (according to the model’s padding side and padding
index) among:
True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single
sequence if provided).
'max_length': Pad to a maximum length specified with the argument max_length or to the maximum
acceptable input length for the model if that argument is not provided.
False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different
lengths).
   max_length (int, optional) —
Maximum length of the returned list and optionally padding length (see above).   truncation (bool) —
Activates truncation to cut input sequences longer than max_length to max_length.   pad_to_multiple_of (int, optional) —
If set will pad the sequence to a multiple of the provided value.
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capabili


ty
>= 7.5 (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.   return_attention_mask (bool, optional) —
Whether to return the attention mask. If left to the default, will return the attention mask according
to the specific feature_extractor’s default.
What are attention masks?   return_tensors (str or TensorType, optional) —
If set, will return tensors instead of list of python integers. Acceptable values are:
'tf': Return TensorFlow tf.constant objects.
'pt': Return PyTorch torch.Tensor objects.
'np': Return Numpy np.ndarray objects.
   sampling_rate (int, optional) —
The sampling rate at which the audio or audio_target input was sampled. It is strongly recommended
to pass sampling_rate at the forward call to prevent silent errors.    Main method to featurize and prepare for the model one or several sequence(s). Pass in a value for audio to extract waveform features. Pass in a value for audio_target to extract log-mel
spectrogram features.


SpeechT5Processor

class transformers.SpeechT5Processor  < source > ( feature_extractor tokenizer  )   Parameters   feature_extractor (SpeechT5FeatureExtractor) —
An instance of SpeechT5FeatureExtractor. The feature extractor is a required input.   tokenizer (SpeechT5Tokenizer) —
An instance of SpeechT5Tokenizer. The tokenizer is a required input.    Constructs a SpeechT5 processor which wraps a feature extractor and a tokenizer into a single processor. SpeechT5Processor offers all the functionalities of SpeechT5FeatureExtractor and SpeechT5Tokenizer. See
the docstring of call() and decode() for more information.  __call__  < source > ( *args **kwargs  )    Processes audio and text input, as well as audio and text targets. You can process audio by using the argument audio, or process audio targets by using the argument
audio_target. This forwards the arguments to SpeechT5FeatureExtractor’s
call(). You can pr


SpeechT5Processor

ocess text by using the argument text, or process text labels by using the argument text_target.
This forwards the arguments to SpeechT5Tokenizer’s call(). Valid input combinations are: text only audio only text_target only audio_target only text and audio_target audio and audio_target text and text_target audio and text_target Please refer to the docstring of the above two methods for more information.  pad  < source > ( *args **kwargs  )    Collates the audio and text inputs, as well as their targets, into a padded batch. Audio inputs are padded by SpeechT5FeatureExtractor’s pad(). Text inputs are padded
by SpeechT5Tokenizer’s pad(). Valid input combinations are: input_ids only input_values only labels only, either log-mel spectrograms or text tokens input_ids and log-mel spectrogram labels input_values and text labels Please refer to the docstring of the above two methods for more infor


SpeechT5Processor

mation.  from_pretrained  < source > ( pretrained_model_name_or_path: typing.Union[str, os.PathLike] cache_dir: typing.Union[str, os.PathLike, NoneType] = None force_download: bool = False local_files_only: bool = False token: typing.Union[bool, str, NoneType] = None revision: str = 'main' **kwargs  )   Parameters   pretrained_model_name_or_path (str or os.PathLike) —
This can be either:
a string, the model id of a pretrained feature_extractor hosted inside a model repo on
huggingface.co. Valid model ids can be located at the root-level, like bert-base-uncased, or
namespaced under a user or organization name, like dbmdz/bert-base-german-cased.
a path to a directory containing a feature extractor file saved using the
save_pretrained() method, e.g., ./my_model_directory/.
a path or url to a saved feature extractor JSON file, e.g.,
./my_model_directory/preprocessor_config.json.
**kwargs —
Add


SpeechT5Processor

itional keyword arguments passed along to both
from_pretrained() and
~tokenization_utils_base.PreTrainedTokenizer.from_pretrained.
    Instantiate a processor associated with a pretrained model. This class method is simply calling the feature extractor
from_pretrained(), image processor
ImageProcessingMixin and the tokenizer
~tokenization_utils_base.PreTrainedTokenizer.from_pretrained methods. Please refer to the docstrings of the
methods above for more information.  save_pretrained  < source > ( save_directory push_to_hub: bool = False **kwargs  )   Parameters   save_directory (str or os.PathLike) —
Directory where the feature extractor JSON file and the tokenizer files will be saved (directory will
be created if it does not exist).   push_to_hub (bool, optional, defaults to False) —
Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
repos


SpeechT5Processor

itory you want to push to with repo_id (will default to the name of save_directory in your
namespace).   kwargs (Dict[str, Any], optional) —
Additional key word arguments passed along to the push_to_hub() method.    Saves the attributes of this processor (feature extractor, tokenizer…) in the specified directory so that it
can be reloaded using the from_pretrained() method. This class method is simply calling save_pretrained() and
save_pretrained(). Please refer to the docstrings of the
methods above for more information.  batch_decode  < source > ( *args **kwargs  )    This method forwards all its arguments to SpeechT5Tokenizer’s batch_decode(). Please refer
to the docstring of this method for more information.  decode  < source > ( *args **kwargs  )    This method forwards all its arguments to SpeechT5Tokenizer’s decode(). Please refer to
the docstring of this method for more information