---
local: speech2text
sections:
- local: overview
  title: Overview
- local: inference
  title: Inference
- local: transformers.Speech2TextConfig
  title: Speech2TextConfig
- local: transformers.Speech2TextTokenizer
  title: Speech2TextTokenizer
- local: transformers.Speech2TextFeatureExtractor
  title: Speech2TextFeatureExtractor
- local: transformers.Speech2TextProcessor
  title: Speech2TextProcessor
- local: transformers.Speech2TextModel
  title: Speech2TextModel
- local: transformers.Speech2TextForConditionalGeneration
  title: Speech2TextForConditionalGeneration
- local: transformers.TFSpeech2TextModel
  title: TFSpeech2TextModel
- local: transformers.TFSpeech2TextForConditionalGeneration
  title: TFSpeech2TextForConditionalGeneration
title: Speech2Text
---
<script>
import Tip from "./Tip.svelte";
import Youtube from "./Youtube.svelte";
import Docstring from "./Docstring.svelte";
import CodeBlock from "./CodeBlock.svelte";
import CodeBlockFw from "./CodeBlockFw.svelte";
import DocNotebookDropdown from "./DocNotebookDropdown.svelte";
import IconCopyLink from "./IconCopyLink.svelte";
export let fw: "pt" | "tf"
</script>
<!--Copyright 2021 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
-->

<h1 id="speech2text">Speech2Text</h1>

<h2 id="overview">Overview</h2>

The Speech2Text model was proposed in [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino. It's a
transformer-based seq2seq (encoder-decoder) model designed for end-to-end Automatic Speech Recognition (ASR) and Speech
Translation (ST). It uses a convolutional downsampler to reduce the length of speech inputs by 3/4th before they are
fed into the encoder. The model is trained with standard autoregressive cross-entropy loss and generates the
transcripts/translations autoregressively. Speech2Text has been fine-tuned on several datasets for ASR and ST:
[LibriSpeech](http://www.openslr.org/12), [CoVoST 2](https://github.com/facebookresearch/covost), [MuST-C](https://ict.fbk.eu/must-c/).

This model was contributed by [valhalla](https://huggingface.co/valhalla). The original code can be found [here](https://github.com/pytorch/fairseq/tree/master/examples/speech_to_text).


<h2 id="inference">Inference</h2>

Speech2Text is a speech model that accepts a float tensor of log-mel filter-bank features extracted from the speech
signal. It's a transformer-based seq2seq model, so the transcripts/translations are generated autoregressively. The
`generate()` method can be used for inference.

The [Speech2TextFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextFeatureExtractor) class is responsible for extracting the log-mel filter-bank
features. The [Speech2TextProcessor](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextProcessor) wraps [Speech2TextFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextFeatureExtractor) and
[Speech2TextTokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextTokenizer) into a single instance to both extract the input features and decode the
predicted token ids.

The feature extractor depends on `torchaudio` and the tokenizer depends on `sentencepiece` so be sure to
install those packages before running the examples. You could either install those as extra speech dependencies with
`pip install transformers"[speech, sentencepiece]"` or install the packages seperately with `pip install torchaudio sentencepiece`. Also `torchaudio` requires the development version of the [libsndfile](http://www.mega-nerd.com/libsndfile/) package which can be installed via a system package manager. On Ubuntu it can
be installed as follows: `apt install libsndfile1-dev`


- ASR and Speech Translation

```python
>>> import torch
>>> from transformers import Speech2TextProcessor, Speech2TextForConditionalGeneration
>>> from datasets import load_dataset
>>> import soundfile as sf

>>> model = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-librispeech-asr")
>>> processor = Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr")


>>> def map_to_array(batch):
...     speech, _ = sf.read(batch["file"])
...     batch["speech"] = speech
...     return batch


>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.map(map_to_array)

>>> inputs = processor(ds["speech"][0], sampling_rate=16_000, return_tensors="pt")
>>> generated_ids = model.generate(input_ids=inputs["input_features"], attention_mask=inputs["attention_mask"])

>>> transcription = processor.batch_decode(generated_ids)
```

- Multilingual speech translation

  For multilingual speech translation models, `eos_token_id` is used as the `decoder_start_token_id` and
  the target language id is forced as the first generated token. To force the target language id as the first
  generated token, pass the `forced_bos_token_id` parameter to the `generate()` method. The following
  example shows how to transate English speech to French text using the *facebook/s2t-medium-mustc-multilingual-st*
  checkpoint.

```python
>>> import torch
>>> from transformers import Speech2TextProcessor, Speech2TextForConditionalGeneration
>>> from datasets import load_dataset
>>> import soundfile as sf

>>> model = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-medium-mustc-multilingual-st")
>>> processor = Speech2TextProcessor.from_pretrained("facebook/s2t-medium-mustc-multilingual-st")


>>> def map_to_array(batch):
...     speech, _ = sf.read(batch["file"])
...     batch["speech"] = speech
...     return batch


>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.map(map_to_array)

>>> inputs = processor(ds["speech"][0], sampling_rate=16_000, return_tensors="pt")
>>> generated_ids = model.generate(
...     input_ids=inputs["input_features"],
...     attention_mask=inputs["attention_mask"],
...     forced_bos_token_id=processor.tokenizer.lang_code_to_id["fr"],
... )

>>> translation = processor.batch_decode(generated_ids)
```

See the [model hub](https://huggingface.co/models?filter=speech_to_text) to look for Speech2Text checkpoints.


<h2 id="transformers.Speech2TextConfig">Speech2TextConfig</h2>

<div class="docstring">

<docstring><name>class transformers.Speech2TextConfig</name><anchor>transformers.Speech2TextConfig</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/configuration_speech_to_text.py#L29</source><parameters>[{"name": "vocab_size", "val": " = 10000"}, {"name": "encoder_layers", "val": " = 12"}, {"name": "encoder_ffn_dim", "val": " = 2048"}, {"name": "encoder_attention_heads", "val": " = 4"}, {"name": "decoder_layers", "val": " = 6"}, {"name": "decoder_ffn_dim", "val": " = 2048"}, {"name": "decoder_attention_heads", "val": " = 4"}, {"name": "encoder_layerdrop", "val": " = 0.0"}, {"name": "decoder_layerdrop", "val": " = 0.0"}, {"name": "use_cache", "val": " = True"}, {"name": "is_encoder_decoder", "val": " = True"}, {"name": "activation_function", "val": " = 'relu'"}, {"name": "d_model", "val": " = 256"}, {"name": "dropout", "val": " = 0.1"}, {"name": "attention_dropout", "val": " = 0.0"}, {"name": "activation_dropout", "val": " = 0.0"}, {"name": "init_std", "val": " = 0.02"}, {"name": "decoder_start_token_id", "val": " = 2"}, {"name": "classifier_dropout", "val": " = 0.0"}, {"name": "scale_embedding", "val": " = True"}, {"name": "pad_token_id", "val": " = 1"}, {"name": "bos_token_id", "val": " = 0"}, {"name": "eos_token_id", "val": " = 2"}, {"name": "max_source_positions", "val": " = 6000"}, {"name": "max_target_positions", "val": " = 1024"}, {"name": "num_conv_layers", "val": " = 2"}, {"name": "conv_kernel_sizes", "val": " = (5, 5)"}, {"name": "conv_channels", "val": " = 1024"}, {"name": "input_feat_per_channel", "val": " = 80"}, {"name": "input_channels", "val": " = 1"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **vocab_size** (`int`, *optional*, defaults to 50265) --
  Vocabulary size of the Speech2Text model. Defines the number of different tokens that can be represented by
  the `inputs_ids` passed when calling [Speech2TextModel](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextModel)
- **d_model** (`int`, *optional*, defaults to 1024) --
  Dimensionality of the layers and the pooler layer.
- **encoder_layers** (`int`, *optional*, defaults to 12) --
  Number of encoder layers.
- **decoder_layers** (`int`, *optional*, defaults to 12) --
  Number of decoder layers.
- **encoder_attention_heads** (`int`, *optional*, defaults to 16) --
  Number of attention heads for each attention layer in the Transformer encoder.
- **decoder_attention_heads** (`int`, *optional*, 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.
- **encoder_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 encoder and pooler. If string, `"gelu"`,
  `"relu"`, `"silu"` and `"gelu_new"` are supported.
- **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.0) --
  The dropout ratio for the attention probabilities.
- **activation_dropout** (`float`, *optional*, defaults to 0.0) --
  The dropout ratio for activations inside the fully connected layer.
- **classifier_dropout** (`float`, *optional*, defaults to 0.0) --
  The dropout ratio for classifier.
- **init_std** (`float`, *optional*, defaults to 0.02) --
  The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  encoder_layerdrop -- (`float`, *optional*, defaults to 0.0):
  The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
  for more details.
  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).
- **max_source_positions** (`int`, *optional*, defaults to 6000) --
  The maximum sequence length of log-mel filter-bank features that this model might ever be used with.
- **max_target_positions** (`int`, *optional*, defaults to 1024) --
  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).
- **num_conv_layers** (`int`, *optional*, defaults to 2) --
  Number of 1D convolutional layers in the conv module.
- **conv_kernel_sizes** (`Tuple[int]`, *optional*, defaults to `(5, 5)`) --
  A tuple of integers defining the kernel size of each 1D convolutional layer in the conv module. The length
  of `conv_kernel_sizes` has to match `num_conv_layers`.
- **conv_channels** (`int`, *optional*, defaults to 1024) --
  An integer defining the number of output channels of each convolution layers except the final one in the
  conv module.
- **input_feat_per_channel** (`int`, *optional*, defaults to 80) --
  An integer specifying the size of feature vector. This is also the dimensions of log-mel filter-bank
  features.
- **input_channels** (`int`, *optional*, defaults to 1) --
  An integer specifying number of input channels of the input feature vector.</paramsdesc><paramgroups>0</paramgroups></docstring>

This is the configuration class to store the configuration of a [Speech2TextModel](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextModel). It is used to instantiate an
Speech2Text 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 Speech2Text
[facebook/s2t-small-librispeech-asr](https://huggingface.co/facebook/s2t-small-librispeech-asr) architecture.

Configuration objects inherit from [PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the
documentation from [PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig) for more information.




Example:

```python
>>> from transformers import Speech2TextModel, Speech2TextConfig

>>> # Initializing a Speech2Text s2t_transformer_s style configuration
>>> configuration = Speech2TextConfig()

>>> # Initializing a model from the s2t_transformer_s style configuration
>>> model = Speech2TextModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

</div>

<h2 id="transformers.Speech2TextTokenizer">Speech2TextTokenizer</h2>

<div class="docstring">

<docstring><name>class transformers.Speech2TextTokenizer</name><anchor>transformers.Speech2TextTokenizer</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/tokenization_speech_to_text.py#L55</source><parameters>[{"name": "vocab_file", "val": ""}, {"name": "spm_file", "val": ""}, {"name": "bos_token", "val": " = '<s>'"}, {"name": "eos_token", "val": " = '</s>'"}, {"name": "pad_token", "val": " = '<pad>'"}, {"name": "unk_token", "val": " = '<unk>'"}, {"name": "do_upper_case", "val": " = False"}, {"name": "do_lower_case", "val": " = False"}, {"name": "tgt_lang", "val": " = None"}, {"name": "lang_codes", "val": " = None"}, {"name": "sp_model_kwargs", "val": ": typing.Union[typing.Dict[str, typing.Any], NoneType] = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **vocab_file** (`str`) --
  File containing the vocabulary.
- **spm_file** (`str`) --
  Path to the [SentencePiece](https://github.com/google/sentencepiece) model file
- **bos_token** (`str`, *optional*, defaults to `"<s>"`) --
  The beginning of sentence token.
- **eos_token** (`str`, *optional*, defaults to `"</s>"`) --
  The end of sentence token.
- **unk_token** (`str`, *optional*, defaults to `"&amp;lt;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 `"&amp;lt;pad>"`) --
  The token used for padding, for example when batching sequences of different lengths.
- **do_upper_case** (`bool`, *optional*, defaults to `False`) --
  Whether or not to uppercase the output when decoding.
- **do_lower_case** (`bool`, *optional*, defaults to `False`) --
  Whether or not to lowercase the input when tokenizing.
- **tgt_lang** (`str`, *optional*) --
  A string representing the target language.
- **sp_model_kwargs** (`dict`, *optional*) --
  Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  SentencePiece](https://github.com/google/sentencepiece/tree/master/python) 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 = &amp;lcub;0,1}`: No sampling is performed.
    - `nbest_size > 1`: samples from the nbest_size results.
    - `nbest_size &amp;lt; 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.

**kwargs --
Additional keyword arguments passed along to [PreTrainedTokenizer](/docs/transformers/pr_15592/en/main_classes/tokenizer#transformers.PreTrainedTokenizer)</paramsdesc><paramgroups>0</paramgroups></docstring>

Construct an Speech2Text tokenizer.

This tokenizer inherits from [PreTrainedTokenizer](/docs/transformers/pr_15592/en/main_classes/tokenizer#transformers.PreTrainedTokenizer) which contains some of the main methods. Users should refer to
the superclass for more information regarding such methods.





<div class="docstring">
<docstring><name>build\_inputs\_with\_special\_tokens</name><anchor>transformers.Speech2TextTokenizer.build_inputs_with_special_tokens</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/tokenization_speech_to_text.py#L195</source><parameters>[{"name": "token_ids_0", "val": ""}, {"name": "token_ids_1", "val": " = None"}]</parameters></docstring>
Build model inputs from a sequence by appending eos_token_id.

</div>
<div class="docstring">
<docstring><name>get\_special\_tokens\_mask</name><anchor>transformers.Speech2TextTokenizer.get_special_tokens_mask</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/tokenization_speech_to_text.py#L202</source><parameters>[{"name": "token_ids_0", "val": ": typing.List[int]"}, {"name": "token_ids_1", "val": ": typing.Optional[typing.List[int]] = None"}, {"name": "already_has_special_tokens", "val": ": bool = False"}]</parameters><paramsdesc>- **token_ids_0** (`List[int]`) --
  List of IDs.
- **token_ids_1** (`List[int]`, *optional*) --
  Optional second list of IDs for sequence pairs.
- **already_has_special_tokens** (`bool`, *optional*, defaults to `False`) --
  Whether or not the token list is already formatted with special tokens for the model.</paramsdesc><paramgroups>0</paramgroups><rettype>`List[int]`</rettype><retdesc>A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.</retdesc></docstring>

Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer `prepare_for_model` method.








</div>
<div class="docstring">
<docstring><name>create\_token\_type\_ids\_from\_sequences</name><anchor>transformers.PreTrainedTokenizerBase.create_token_type_ids_from_sequences</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/tokenization_utils_base.py#L2864</source><parameters>[{"name": "token_ids_0", "val": ": typing.List[int]"}, {"name": "token_ids_1", "val": ": typing.Optional[typing.List[int]] = None"}]</parameters><paramsdesc>- **token_ids_0** (`List[int]`) -- The first tokenized sequence.
- **token_ids_1** (`List[int]`, *optional*) -- The second tokenized sequence.</paramsdesc><paramgroups>0</paramgroups><rettype>`List[int]`</rettype><retdesc>The token type ids.</retdesc></docstring>

Create the token type IDs corresponding to the sequences passed. [What are token type
IDs?](../glossary#token-type-ids)

Should be overridden in a subclass if the model has a special way of building those.








</div>
<div class="docstring"></div></div>

<h2 id="transformers.Speech2TextFeatureExtractor">Speech2TextFeatureExtractor</h2>

<div class="docstring">

<docstring><name>class transformers.Speech2TextFeatureExtractor</name><anchor>transformers.Speech2TextFeatureExtractor</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/feature_extraction_speech_to_text.py#L34</source><parameters>[{"name": "feature_size", "val": " = 80"}, {"name": "sampling_rate", "val": " = 16000"}, {"name": "num_mel_bins", "val": " = 80"}, {"name": "padding_value", "val": " = 0.0"}, {"name": "do_ceptral_normalize", "val": " = True"}, {"name": "normalize_means", "val": " = True"}, {"name": "normalize_vars", "val": " = True"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **feature_size** (`int`, defaults to 80) --
  The feature dimension of the extracted features.
- **sampling_rate** (`int`, defaults to 16000) --
  The sampling rate at which the audio files should be digitalized expressed in Hertz per second (Hz).
- **num_mel_bins** (`int`, defaults to 80) --
  Number of Mel-frequency bins.
- **padding_value** (`float`, defaults to 0.0) --
  The value that is used to fill the padding vectors.
- **do_ceptral_normalize** (`bool`, *optional*, defaults to `True`) --
  Whether or not to apply utterance-level cepstral mean and variance normalization to extracted features.
- **normalize_means** (`bool`, *optional*, defaults to `True`) --
  Whether or not to zero-mean normalize the extracted features.
- **normalize_vars** (`bool`, *optional*, defaults to `True`) --
  Whether or not to unit-variance normalize the extracted features.</paramsdesc><paramgroups>0</paramgroups></docstring>

Constructs a Speech2Text feature extractor.

This feature extractor inherits from [Speech2TextFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextFeatureExtractor) which contains most of the main methods. Users
should refer to this superclass for more information regarding those methods.

This class extracts mel-filter bank features from raw speech using TorchAudio and applies utterance-level cepstral
mean and variance normalization to the extracted features.





<div class="docstring">
<docstring><name>\_\_call\_\_</name><anchor>transformers.Speech2TextFeatureExtractor.__call__</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/feature_extraction_speech_to_text.py#L127</source><parameters>[{"name": "raw_speech", "val": ": typing.Union[numpy.ndarray, typing.List[float], typing.List[numpy.ndarray], typing.List[typing.List[float]]]"}, {"name": "padding", "val": ": typing.Union[bool, str, transformers.file_utils.PaddingStrategy] = False"}, {"name": "max_length", "val": ": typing.Optional[int] = None"}, {"name": "truncation", "val": ": bool = False"}, {"name": "pad_to_multiple_of", "val": ": typing.Optional[int] = None"}, {"name": "return_tensors", "val": ": typing.Union[str, transformers.file_utils.TensorType, NoneType] = None"}, {"name": "sampling_rate", "val": ": typing.Optional[int] = None"}, {"name": "return_attention_mask", "val": ": typing.Optional[bool] = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **raw_speech** (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`) --
  The sequence or batch of sequences to be padded. 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.
- **padding** (`bool`, `str` or [PaddingStrategy](/docs/transformers/pr_15592/en/internal/file_utils#transformers.file_utils.PaddingStrategy), *optional*, defaults to `True`) --
  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 capability
  >= 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?](../glossary#attention-mask)

  <Tip>

  For Speech2TextTransoformer models, `attention_mask` should alwys be passed for batched inference, to
  avoid subtle bugs.

  </Tip>

- **return_tensors** (`str` or [TensorType](/docs/transformers/pr_15592/en/internal/file_utils#transformers.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 `raw_speech` input was sampled. It is strongly recommended to pass
  `sampling_rate` at the forward call to prevent silent errors.
- **padding_value** (`float`, defaults to 0.0) --
  The value that is used to fill the padding values / vectors.</paramsdesc><paramgroups>0</paramgroups></docstring>

Main method to featurize and prepare for the model one or several sequence(s). sequences.




</div></div>

<h2 id="transformers.Speech2TextProcessor">Speech2TextProcessor</h2>

<div class="docstring">

<docstring><name>class transformers.Speech2TextProcessor</name><anchor>transformers.Speech2TextProcessor</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/processing_speech_to_text.py#L23</source><parameters>[{"name": "feature_extractor", "val": ""}, {"name": "tokenizer", "val": ""}]</parameters><paramsdesc>- **feature_extractor** (`Speech2TextFeatureExtractor`) --
  An instance of [Speech2TextFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextFeatureExtractor). The feature extractor is a required input.
- **tokenizer** (`Speech2TextTokenizer`) --
  An instance of [Speech2TextTokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextTokenizer). The tokenizer is a required input.</paramsdesc><paramgroups>0</paramgroups></docstring>

Constructs a Speech2Text processor which wraps a Speech2Text feature extractor and a Speech2Text tokenizer into a
single processor.

[Speech2TextProcessor](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextProcessor) offers all the functionalities of [Speech2TextFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextFeatureExtractor) and
[Speech2TextTokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextTokenizer). See the [__call__()](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextProcessor.__call__) and [decode()](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextProcessor.decode) for more
information.





<div class="docstring">
<docstring><name>\_\_call\_\_</name><anchor>transformers.Speech2TextProcessor.__call__</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/processing_speech_to_text.py#L45</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>

When used in normal mode, this method forwards all its arguments to Speech2TextFeatureExtractor's
[__call__()](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextFeatureExtractor.__call__) and returns its output. If used in the context
[as_target_processor()](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextProcessor.as_target_processor) this method forwards all its arguments to Speech2TextTokenizer's
[__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__). Please refer to the doctsring of the above two methods for more
information.


</div>
<div class="docstring">
<docstring><name>from\_pretrained</name><anchor>transformers.ProcessorMixin.from_pretrained</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/processing_utils.py#L157</source><parameters>[{"name": "pretrained_model_name_or_path", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **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()](/docs/transformers/pr_15592/en/main_classes/feature_extractor#transformers.FeatureExtractionMixin.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 --
Additional keyword arguments passed along to both
[from_pretrained()](/docs/transformers/pr_15592/en/main_classes/feature_extractor#transformers.FeatureExtractionMixin.from_pretrained) and
`from_pretrained`.</paramsdesc><paramgroups>0</paramgroups></docstring>

Instantiate a processor associated with a pretrained model.

<Tip>

This class method is simply calling the feature extractor
[from_pretrained()](/docs/transformers/pr_15592/en/main_classes/feature_extractor#transformers.FeatureExtractionMixin.from_pretrained) and the tokenizer
`from_pretrained` methods. Please refer to the docstrings of the
methods above for more information.

</Tip>




</div>
<div class="docstring">
<docstring><name>save\_pretrained</name><anchor>transformers.ProcessorMixin.save_pretrained</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/processing_utils.py#L95</source><parameters>[{"name": "save_directory", "val": ""}, {"name": "push_to_hub", "val": ": bool = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **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 processor to the Hugging Face model hub after saving it.

  <Tip warning=&amp;lcub;true}>

  Using `push_to_hub=True` will synchronize the repository you are pushing to with `save_directory`,
  which requires `save_directory` to be a local clone of the repo you are pushing to if it's an existing
  folder. Pass along `temp_dir=True` to use a temporary directory instead.

  </Tip>

  kwargs --
  Additional key word arguments passed along to the [push_to_hub()](/docs/transformers/pr_15592/en/main_classes/model#transformers.file_utils.PushToHubMixin.push_to_hub) method.</paramsdesc><paramgroups>0</paramgroups></docstring>

Saves the attributes of this processor (feature extractor, tokenizer...) in the specified directory so that it
can be reloaded using the [from_pretrained()](/docs/transformers/pr_15592/en/main_classes/processors#transformers.ProcessorMixin.from_pretrained) method.

<Tip>

This class method is simply calling [save_pretrained()](/docs/transformers/pr_15592/en/main_classes/feature_extractor#transformers.FeatureExtractionMixin.save_pretrained) and
`save_pretrained`. Please refer to the docstrings of the methods
above for more information.

</Tip>




</div>
<div class="docstring">
<docstring><name>batch\_decode</name><anchor>transformers.Speech2TextProcessor.batch_decode</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/processing_speech_to_text.py#L55</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>

This method forwards all its arguments to Speech2TextTokenizer's [batch_decode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.batch_decode). Please
refer to the docstring of this method for more information.


</div>
<div class="docstring">
<docstring><name>decode</name><anchor>transformers.Speech2TextProcessor.decode</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/processing_speech_to_text.py#L62</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>

This method forwards all its arguments to Speech2TextTokenizer's [decode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.decode). Please refer
to the docstring of this method for more information.


</div>
<div class="docstring">
<docstring><name>as\_target\_processor</name><anchor>transformers.Speech2TextProcessor.as_target_processor</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/processing_speech_to_text.py#L69</source><parameters>[]</parameters></docstring>

Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning
Speech2Text.


</div></div>

<h2 id="transformers.Speech2TextModel">Speech2TextModel</h2>

<div class="docstring">

<docstring><name>class transformers.Speech2TextModel</name><anchor>transformers.Speech2TextModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/modeling_speech_to_text.py#L1124</source><parameters>[{"name": "config", "val": ": Speech2TextConfig"}]</parameters><paramsdesc>- **config** ([Speech2TextConfig](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextConfig)) --
  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()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>
The bare Speech2Text Model outputting raw hidden-states without any specific head on top.
This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.Speech2TextModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/modeling_speech_to_text.py#L1146</source><parameters>[{"name": "input_features", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "decoder_input_ids", "val": " = None"}, {"name": "decoder_attention_mask", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "decoder_head_mask", "val": " = None"}, {"name": "cross_attn_head_mask", "val": " = None"}, {"name": "encoder_outputs", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "decoder_inputs_embeds", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **input_features** (`torch.LongTensor` of shape `(batch_size, sequence_length, feature_size)`) --
  Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained
  by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.*
  via the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
  [Speech2TextTokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextTokenizer) should be used for extracting the fbank features, padding and conversion into a
  tensor of type `torch.FloatTensor`. See [__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)
- **attention_mask** (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Mask to avoid performing convolution and 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?](../glossary#attention-mask)
- **decoder_input_ids** (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*) --
  Indices of decoder input sequence tokens in the vocabulary.

  Indices can be obtained using `SpeechToTextTokenizer`. See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are decoder input IDs?](../glossary#decoder-input-ids)

  SpeechToText uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If
  `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
  `past_key_values`).
- **decoder_attention_mask** (`torch.LongTensor` of 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.

  If you want to change padding behavior, you should read `modeling_speech_to_text._prepare_decoder_inputs`
  and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
  information on the default strategy.
- **head_mask** (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*) --
  Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:

  - 1 indicates the head is **not masked**,
  - 0 indicates the head is **masked**.

- **decoder_head_mask** (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*) --
  Mask to nullify selected heads of the attention modules in the decoder. 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**.

- **encoder_outputs** (`tuple(tuple(torch.FloatTensor)`, *optional*) --
  Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
  `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
  hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
- **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)`.

  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)`. decoder_inputs_embeds (`torch.FloatTensor`
  of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
  `decoder_input_ids` you can choose to directly pass an embedded representation. If `past_key_values` is
  used, optionally only the last `decoder_inputs_embeds` have to be input (see `past_key_values`). This is
  useful if you want more control over how to convert `decoder_input_ids` indices into associated vectors
  than the model's internal embedding lookup matrix.

  If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
  of `inputs_embeds`.
- **use_cache** (`bool`, *optional*) --
  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_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](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_outputs.Seq2SeqModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.Seq2SeqModelOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.Seq2SeqModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.Seq2SeqModelOutput) 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 ([Speech2TextConfig](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextConfig)) and inputs.

- **last_hidden_state** (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the decoder of the model.

  If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
  hidden_size)` is output.
- **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)`.

  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.
- **decoder_hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  shape `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
- **decoder_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)`.

  Attentions weights of the decoder, 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)`.

  Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.
- **encoder_last_hidden_state** (`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 of the model.
- **encoder_hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  shape `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
- **encoder_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)`.

  Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
  self-attention heads.</retdesc></docstring>
The [Speech2TextModel](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextModel) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> from transformers import Speech2TextTokenizer, Speech2TextModel
>>> import torch

>>> tokenizer = Speech2TextTokenizer.from_pretrained("facebook/s2t-small-librispeech-asr")
>>> model = Speech2TextModel.from_pretrained("facebook/s2t-small-librispeech-asr")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state
```


</div></div>

<h2 id="transformers.Speech2TextForConditionalGeneration">Speech2TextForConditionalGeneration</h2>

<div class="docstring">

<docstring><name>class transformers.Speech2TextForConditionalGeneration</name><anchor>transformers.Speech2TextForConditionalGeneration</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/modeling_speech_to_text.py#L1237</source><parameters>[{"name": "config", "val": ": Speech2TextConfig"}]</parameters><paramsdesc>- **config** ([Speech2TextConfig](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextConfig)) --
  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()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>
The Speech2Text Model with a language modeling head. Can be used for summarization.
This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.Speech2TextForConditionalGeneration.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/modeling_speech_to_text.py#L1274</source><parameters>[{"name": "input_features", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "decoder_input_ids", "val": " = None"}, {"name": "decoder_attention_mask", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "decoder_head_mask", "val": " = None"}, {"name": "cross_attn_head_mask", "val": " = None"}, {"name": "encoder_outputs", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "decoder_inputs_embeds", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **input_features** (`torch.LongTensor` of shape `(batch_size, sequence_length, feature_size)`) --
  Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained
  by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.*
  via the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
  [Speech2TextTokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextTokenizer) should be used for extracting the fbank features, padding and conversion into a
  tensor of type `torch.FloatTensor`. See [__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)
- **attention_mask** (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Mask to avoid performing convolution and 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?](../glossary#attention-mask)
- **decoder_input_ids** (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*) --
  Indices of decoder input sequence tokens in the vocabulary.

  Indices can be obtained using `SpeechToTextTokenizer`. See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are decoder input IDs?](../glossary#decoder-input-ids)

  SpeechToText uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If
  `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
  `past_key_values`).
- **decoder_attention_mask** (`torch.LongTensor` of 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.

  If you want to change padding behavior, you should read `modeling_speech_to_text._prepare_decoder_inputs`
  and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
  information on the default strategy.
- **head_mask** (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*) --
  Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:

  - 1 indicates the head is **not masked**,
  - 0 indicates the head is **masked**.

- **decoder_head_mask** (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*) --
  Mask to nullify selected heads of the attention modules in the decoder. 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**.

- **encoder_outputs** (`tuple(tuple(torch.FloatTensor)`, *optional*) --
  Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
  `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
  hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
- **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)`.

  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)`. decoder_inputs_embeds (`torch.FloatTensor`
  of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
  `decoder_input_ids` you can choose to directly pass an embedded representation. If `past_key_values` is
  used, optionally only the last `decoder_inputs_embeds` have to be input (see `past_key_values`). This is
  useful if you want more control over how to convert `decoder_input_ids` indices into associated vectors
  than the model's internal embedding lookup matrix.

  If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
  of `inputs_embeds`.
- **use_cache** (`bool`, *optional*) --
  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_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](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.

- **labels** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Labels for computing the 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]`.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_outputs.Seq2SeqLMOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.Seq2SeqLMOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.Seq2SeqLMOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.Seq2SeqLMOutput) 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 ([Speech2TextConfig](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextConfig)) and inputs.

- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) -- Language modeling loss.
- **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).
- **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)`.

  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.
- **decoder_hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  shape `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
- **decoder_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)`.

  Attentions weights of the decoder, 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)`.

  Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.
- **encoder_last_hidden_state** (`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 of the model.
- **encoder_hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  shape `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
- **encoder_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)`.

  Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
  self-attention heads.</retdesc></docstring>
The [Speech2TextForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextForConditionalGeneration) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> import torch
>>> from transformers import Speech2TextProcessor, Speech2TextForConditionalGeneration
>>> from datasets import load_dataset
>>> import soundfile as sf

>>> model = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-librispeech-asr")
>>> processor = Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr")


>>> def map_to_array(batch):
...     speech, _ = sf.read(batch["file"])
...     batch["speech"] = speech
...     return batch


>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.map(map_to_array)

>>> input_features = processor(
...     ds["speech"][0], sampling_rate=16000, return_tensors="pt"
>>> ).input_features  # Batch size 1
>>> generated_ids = model.generate(inputs=input_features)

>>> transcription = processor.batch_decode(generated_ids)
```

</div></div>

<h2 id="transformers.TFSpeech2TextModel">TFSpeech2TextModel</h2>

<div class="docstring">

<docstring><name>class transformers.TFSpeech2TextModel</name><anchor>transformers.TFSpeech2TextModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/modeling_tf_speech_to_text.py#L1288</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([Speech2TextConfig](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextConfig)) --
  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()](/docs/transformers/pr_15592/en/main_classes/model#transformers.TFPreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>
The bare Speech2Text Model outputting raw hidden-states without any specific head on top.
This model inherits from [TFPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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 [tf.keras.Model](https://www.tensorflow.org/api_docs/python/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.

<Tip>

TF 2.0 models accepts two formats as inputs:

- having all inputs as keyword arguments (like PyTorch models), or
- having all inputs as a list, tuple or dict in the first positional arguments.

This second option is useful when using `tf.keras.Model.fit` method which currently requires having all the
tensors in the first argument of the model call function: `model(inputs)`.

If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the
first positional argument :

- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
`model(&amp;lcub;"input_ids": input_ids, "token_type_ids": token_type_ids})`

</Tip>





<div class="docstring">
<docstring><name>call</name><anchor>transformers.TFSpeech2TextModel.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/modeling_tf_speech_to_text.py#L1300</source><parameters>[{"name": "input_features", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "decoder_input_ids", "val": " = None"}, {"name": "decoder_attention_mask", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "decoder_head_mask", "val": " = None"}, {"name": "cross_attn_head_mask", "val": " = None"}, {"name": "encoder_outputs", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "decoder_inputs_embeds", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "training", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **input_features** (`tf.Tensor` of shape `(batch_size, sequence_length, feature_size)`) --
  Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained
  by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.*
  via the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
  [Speech2TextTokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextTokenizer) should be used for extracting the fbank features, padding and conversion into a
  tensor of floats. See [__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)
- **attention_mask** (`tf.Tensor` of shape `(&amp;lcub;0})`, *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?](../glossary#attention-mask)
- **decoder_input_ids** (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*) --
  Indices of decoder input sequence tokens in the vocabulary.

  Indices can be obtained using [Speech2TextTokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are decoder input IDs?](../glossary#decoder-input-ids)

  Bart uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
  is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).

  For translation and summarization training, `decoder_input_ids` should be provided. If no
  `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
  for denoising pre-training following the paper.
- **decoder_attention_mask** (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*) --
  will be made by default and ignore pad tokens. It is not recommended to set this for most use cases.
- **head_mask** (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*) --
  Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:

  - 1 indicates the head is **not masked**,
  - 0 indicates the head is **masked**.

- **decoder_head_mask** (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*) --
  Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:

  - 1 indicates the head is **not masked**,
  - 0 indicates the head is **masked**.

- **cross_attn_head_mask** (`tf.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**.

- **encoder_outputs** (`tf.FloatTensor`, *optional*) --
  hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
  of shape `(batch_size, sequence_length, hidden_size)` is a sequence of
- **past_key_values** (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`) --
  contains precomputed key and value hidden states of the attention blocks. Can be used to speed up 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)`.
- **output_attentions** (`bool`, *optional*) --
  Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
  config will be used instead.
- **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. This argument can be used only in eager mode, in graph mode the value in the config will be
  used instead.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple. This argument can be used
  in eager mode, in graph mode the value will always be set to True.
- **training** (`bool`, *optional*, defaults to `False`) --
  Whether or not to use the model in training mode (some modules like dropout modules have different
  behaviors between training and evaluation).</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_tf_outputs.TFSeq2SeqModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFSeq2SeqModelOutput) or `tuple(tf.Tensor)`</rettype><retdesc>A [transformers.modeling_tf_outputs.TFSeq2SeqModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFSeq2SeqModelOutput) 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 ([Speech2TextConfig](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextConfig)) and inputs.

- **last_hidden_state** (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the decoder of the model.

  If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
  hidden_size)` is output.
- **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 pre-computed 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.
- **decoder_hidden_states** (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
  `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
- **decoder_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 decoder, after the attention softmax, used to compute the weighted average in the
  self-attention heads.
- **cross_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 decoder's cross-attention layer, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.
- **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 encoder of the model.
- **encoder_hidden_states** (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
  `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
- **encoder_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 encoder, after the attention softmax, used to compute the weighted average in the
  self-attention heads.</retdesc></docstring>
The [TFSpeech2TextModel](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.TFSpeech2TextModel) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> from transformers import Speech2TextTokenizer, TFSpeech2TextModel
>>> import tensorflow as tf

>>> tokenizer = Speech2TextTokenizer.from_pretrained("facebook/s2t-small-librispeech-asr")
>>> model = TFSpeech2TextModel.from_pretrained("facebook/s2t-small-librispeech-asr")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> outputs = model(inputs)

>>> last_hidden_states = outputs.last_hidden_state
```


</div></div>

<h2 id="transformers.TFSpeech2TextForConditionalGeneration">TFSpeech2TextForConditionalGeneration</h2>

<div class="docstring">

<docstring><name>class transformers.TFSpeech2TextForConditionalGeneration</name><anchor>transformers.TFSpeech2TextForConditionalGeneration</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/modeling_tf_speech_to_text.py#L1393</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([Speech2TextConfig](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextConfig)) --
  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()](/docs/transformers/pr_15592/en/main_classes/model#transformers.TFPreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>
The Speech2Text Model with a language modeling head. Can be used for summarization.
This model inherits from [TFPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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 [tf.keras.Model](https://www.tensorflow.org/api_docs/python/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.

<Tip>

TF 2.0 models accepts two formats as inputs:

- having all inputs as keyword arguments (like PyTorch models), or
- having all inputs as a list, tuple or dict in the first positional arguments.

This second option is useful when using `tf.keras.Model.fit` method which currently requires having all the
tensors in the first argument of the model call function: `model(inputs)`.

If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the
first positional argument :

- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
`model(&amp;lcub;"input_ids": input_ids, "token_type_ids": token_type_ids})`

</Tip>





<div class="docstring">
<docstring><name>call</name><anchor>transformers.TFSpeech2TextForConditionalGeneration.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text/modeling_tf_speech_to_text.py#L1415</source><parameters>[{"name": "input_features", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "decoder_input_ids", "val": " = None"}, {"name": "decoder_attention_mask", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "decoder_head_mask", "val": " = None"}, {"name": "cross_attn_head_mask", "val": " = None"}, {"name": "encoder_outputs", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "decoder_inputs_embeds", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "training", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **input_features** (`tf.Tensor` of shape `(batch_size, sequence_length, feature_size)`) --
  Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained
  by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.*
  via the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
  [Speech2TextTokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextTokenizer) should be used for extracting the fbank features, padding and conversion into a
  tensor of floats. See [__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)
- **attention_mask** (`tf.Tensor` of shape `(&amp;lcub;0})`, *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?](../glossary#attention-mask)
- **decoder_input_ids** (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*) --
  Indices of decoder input sequence tokens in the vocabulary.

  Indices can be obtained using [Speech2TextTokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are decoder input IDs?](../glossary#decoder-input-ids)

  Bart uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
  is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).

  For translation and summarization training, `decoder_input_ids` should be provided. If no
  `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
  for denoising pre-training following the paper.
- **decoder_attention_mask** (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*) --
  will be made by default and ignore pad tokens. It is not recommended to set this for most use cases.
- **head_mask** (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*) --
  Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:

  - 1 indicates the head is **not masked**,
  - 0 indicates the head is **masked**.

- **decoder_head_mask** (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*) --
  Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:

  - 1 indicates the head is **not masked**,
  - 0 indicates the head is **masked**.

- **cross_attn_head_mask** (`tf.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**.

- **encoder_outputs** (`tf.FloatTensor`, *optional*) --
  hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
  of shape `(batch_size, sequence_length, hidden_size)` is a sequence of
- **past_key_values** (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`) --
  contains precomputed key and value hidden states of the attention blocks. Can be used to speed up 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)`.
- **output_attentions** (`bool`, *optional*) --
  Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
  config will be used instead.
- **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. This argument can be used only in eager mode, in graph mode the value in the config will be
  used instead.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple. This argument can be used
  in eager mode, in graph mode the value will always be set to True.
- **training** (`bool`, *optional*, defaults to `False`) --
  Whether or not to use the model in training mode (some modules like dropout modules have different
  behaviors between training and evaluation).

- **labels** (`tf.Tensor` 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]`.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_tf_outputs.TFSeq2SeqLMOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFSeq2SeqLMOutput) or `tuple(tf.Tensor)`</rettype><retdesc>A [transformers.modeling_tf_outputs.TFSeq2SeqLMOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFSeq2SeqLMOutput) 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 ([Speech2TextConfig](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextConfig)) and inputs.

- **loss** (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of non-masked labels, 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 (scores for each vocabulary token before SoftMax).
- **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 pre-computed 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.
- **decoder_hidden_states** (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
  `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
- **decoder_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 decoder, after the attention softmax, used to compute the weighted average in the
  self-attention heads.
- **cross_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 decoder's cross-attention layer, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.
- **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 encoder of the model.
- **encoder_hidden_states** (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
  `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
- **encoder_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 encoder, after the attention softmax, used to compute the weighted average in the
  self-attention heads.</retdesc></docstring>
The [TFSpeech2TextForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.TFSpeech2TextForConditionalGeneration) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> import tensorflow as tf
>>> from transformers import Speech2TextProcessor, TFSpeech2TextForConditionalGeneration
>>> from datasets import load_dataset
>>> import soundfile as sf

>>> model = TFSpeech2TextForConditionalGeneration.from_pretrained(
...     "facebook/s2t-small-librispeech-asr", from_pt=True
... )
>>> processor = Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr")


>>> def map_to_array(batch):
...     speech, _ = sf.read(batch["file"])
...     batch["speech"] = speech
...     return batch


>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.map(map_to_array)
>>> ds.set_format(type="tf")

>>> input_features = processor(
...     ds["speech"][0], sampling_rate=16000, return_tensors="tf"
>>> ).input_features  # Batch size 1
>>> generated_ids = model.generate(input_features)

>>> transcription = processor.batch_decode(generated_ids)
```

</div></div>
