---
local: speech2text2
sections:
- local: overview
  title: Overview
- local: inference
  title: Inference
- local: transformers.Speech2Text2Config
  title: Speech2Text2Config
- local: transformers.Speech2Text2Tokenizer
  title: Speech2TextTokenizer
- local: transformers.Speech2Text2Processor
  title: Speech2Text2Processor
- local: transformers.Speech2Text2ForCausalLM
  title: Speech2Text2ForCausalLM
title: Speech2Text2
---
<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="speech2text2">Speech2Text2</h1>

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

The Speech2Text2 model is used together with [Wav2Vec2](wav2vec2) for Speech Translation models proposed in
[Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678) by
Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.

Speech2Text2 is a *decoder-only* transformer model that can be used with any speech *encoder-only*, such as
[Wav2Vec2](wav2vec2) or [HuBERT](hubert) for Speech-to-Text tasks. Please refer to the
[SpeechEncoderDecoder](speech-encoder-decoder) class on how to combine Speech2Text2 with any speech *encoder-only*
model.

This model was contributed by [Patrick von Platen](https://huggingface.co/patrickvonplaten).

The original code can be found [here](https://github.com/pytorch/fairseq/blob/1f7ef9ed1e1061f8c7f88f8b94c7186834398690/fairseq/models/wav2vec/wav2vec2_asr.py#L266).


Tips:

- Speech2Text2 achieves state-of-the-art results on the CoVoST Speech Translation dataset. For more information, see
  the [official models](https://huggingface.co/models?other=speech2text2) .
- Speech2Text2 is always used within the [SpeechEncoderDecoder](speech-encoder-decoder) framework.
- Speech2Text2's tokenizer is based on [fastBPE](https://github.com/glample/fastBPE).

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

Speech2Text2's [SpeechEncoderDecoderModel](/docs/transformers/pr_15592/en/model_doc/speech-encoder-decoder#transformers.SpeechEncoderDecoderModel) model accepts raw waveform input values from speech and
makes use of [generate()](/docs/transformers/pr_15592/en/main_classes/model#transformers.generation_utils.GenerationMixin.generate) to translate the input speech
autoregressively to the target language.

The [Wav2Vec2FeatureExtractor](/docs/transformers/pr_15592/en/model_doc/wav2vec2#transformers.Wav2Vec2FeatureExtractor) class is responsible for preprocessing the input speech and
[Speech2Text2Tokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text_2#transformers.Speech2Text2Tokenizer) decodes the generated target tokens to the target string. The
[Speech2Text2Processor](/docs/transformers/pr_15592/en/model_doc/speech_to_text_2#transformers.Speech2Text2Processor) wraps [Wav2Vec2FeatureExtractor](/docs/transformers/pr_15592/en/model_doc/wav2vec2#transformers.Wav2Vec2FeatureExtractor) and
[Speech2Text2Tokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text_2#transformers.Speech2Text2Tokenizer) into a single instance to both extract the input features and decode the
predicted token ids.

- Step-by-step Speech Translation

```python
>>> import torch
>>> from transformers import Speech2Text2Processor, SpeechEncoderDecoderModel
>>> from datasets import load_dataset
>>> import soundfile as sf

>>> model = SpeechEncoderDecoderModel.from_pretrained("facebook/s2t-wav2vec2-large-en-de")
>>> processor = Speech2Text2Processor.from_pretrained("facebook/s2t-wav2vec2-large-en-de")


>>> 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(inputs=inputs["input_values"], attention_mask=inputs["attention_mask"])

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

- Speech Translation via Pipelines

  The automatic speech recognition pipeline can also be used to translate speech in just a couple lines of code

```python
>>> from datasets import load_dataset
>>> from transformers import pipeline

>>> librispeech_en = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> asr = pipeline(
...     "automatic-speech-recognition",
...     model="facebook/s2t-wav2vec2-large-en-de",
...     feature_extractor="facebook/s2t-wav2vec2-large-en-de",
... )

>>> translation_de = asr(librispeech_en[0]["file"])
```

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


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

<div class="docstring">

<docstring><name>class transformers.Speech2Text2Config</name><anchor>transformers.Speech2Text2Config</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text_2/configuration_speech_to_text_2.py#L29</source><parameters>[{"name": "vocab_size", "val": " = 10000"}, {"name": "decoder_layers", "val": " = 6"}, {"name": "decoder_ffn_dim", "val": " = 2048"}, {"name": "decoder_attention_heads", "val": " = 4"}, {"name": "decoder_layerdrop", "val": " = 0.0"}, {"name": "use_cache", "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": "**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.
- **decoder_layers** (`int`, *optional*, defaults to 12) --
  Number of decoder layers.
- **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.
- **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.
- **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`, *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.
  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).</paramsdesc><paramgroups>0</paramgroups></docstring>

This is the configuration class to store the configuration of a [Speech2Text2ForCausalLM](/docs/transformers/pr_15592/en/model_doc/speech_to_text_2#transformers.Speech2Text2ForCausalLM). It is used to
instantiate an Speech2Text2 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 Speech2Text2
[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 Speech2Text2ForCausalLM, Speech2Text2Config

>>> # Initializing a Speech2Text2 s2t_transformer_s style configuration
>>> configuration = Speech2Text2Config()

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

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

</div>

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

<div class="docstring">

<docstring><name>class transformers.Speech2Text2Tokenizer</name><anchor>transformers.Speech2Text2Tokenizer</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text_2/tokenization_speech_to_text_2.py#L67</source><parameters>[{"name": "vocab_file", "val": ""}, {"name": "bos_token", "val": " = '<s>'"}, {"name": "pad_token", "val": " = '<pad>'"}, {"name": "eos_token", "val": " = '</s>'"}, {"name": "unk_token", "val": " = '<unk>'"}, {"name": "do_lower_case", "val": " = False"}, {"name": "merges_file", "val": " = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **vocab_file** (`str`) --
  File containing the vocabulary.
- **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.

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

Constructs a Speech2Text2Tokenizer.

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>batch\_decode</name><anchor>transformers.PreTrainedTokenizerBase.batch_decode</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/tokenization_utils_base.py#L3250</source><parameters>[{"name": "sequences", "val": ": typing.Union[typing.List[int], typing.List[typing.List[int]], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')]"}, {"name": "skip_special_tokens", "val": ": bool = False"}, {"name": "clean_up_tokenization_spaces", "val": ": bool = True"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **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*, defaults to `True`) --
  Whether or not to clean up the tokenization spaces.
- **kwargs** (additional keyword arguments, *optional*) --
  Will be passed to the underlying model specific decode method.</paramsdesc><paramgroups>0</paramgroups><rettype>`List[str]`</rettype><retdesc>The list of decoded sentences.</retdesc></docstring>

Convert a list of lists of token ids into a list of strings by calling decode.








</div>
<div class="docstring">
<docstring><name>decode</name><anchor>transformers.PreTrainedTokenizerBase.decode</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/tokenization_utils_base.py#L3283</source><parameters>[{"name": "token_ids", "val": ": typing.Union[int, typing.List[int], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')]"}, {"name": "skip_special_tokens", "val": ": bool = False"}, {"name": "clean_up_tokenization_spaces", "val": ": bool = True"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **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*, defaults to `True`) --
  Whether or not to clean up the tokenization spaces.
- **kwargs** (additional keyword arguments, *optional*) --
  Will be passed to the underlying model specific decode method.</paramsdesc><paramgroups>0</paramgroups><rettype>`str`</rettype><retdesc>The decoded sentence.</retdesc></docstring>

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_to_tokens(token_ids))`.








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

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

<div class="docstring">

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

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

[Speech2Text2Processor](/docs/transformers/pr_15592/en/model_doc/speech_to_text_2#transformers.Speech2Text2Processor) offers all the functionalities of [AutoFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/auto#transformers.AutoFeatureExtractor) and [Speech2Text2Tokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text_2#transformers.Speech2Text2Tokenizer).
See the [__call__()](/docs/transformers/pr_15592/en/model_doc/speech_to_text_2#transformers.Speech2Text2Processor.__call__) and [decode()](/docs/transformers/pr_15592/en/model_doc/speech_to_text_2#transformers.Speech2Text2Processor.decode) for more information.





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

When used in normal mode, this method forwards all its arguments to AutoFeatureExtractor's
`__call__()`and returns its output. If used in the context
[as_target_processor()](/docs/transformers/pr_15592/en/model_doc/speech_to_text_2#transformers.Speech2Text2Processor.as_target_processor) this method forwards all its arguments to
Speech2Text2Tokenizer'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.Speech2Text2Processor.batch_decode</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text_2/processing_speech_to_text_2.py#L54</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>

This method forwards all its arguments to Speech2Text2Tokenizer'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.Speech2Text2Processor.decode</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text_2/processing_speech_to_text_2.py#L61</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>

This method forwards all its arguments to Speech2Text2Tokenizer'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.Speech2Text2Processor.as_target_processor</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text_2/processing_speech_to_text_2.py#L68</source><parameters>[]</parameters></docstring>

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


</div></div>

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

<div class="docstring">

<docstring><name>class transformers.Speech2Text2ForCausalLM</name><anchor>transformers.Speech2Text2ForCausalLM</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text_2/modeling_speech_to_text_2.py#L743</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([Speech2Text2Config](/docs/transformers/pr_15592/en/model_doc/speech_to_text_2#transformers.Speech2Text2Config)) --
  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 Speech2Text2 Decoder with a language modeling head. Can be used as the decoder part of [EncoderDecoderModel](/docs/transformers/pr_15592/en/model_doc/encoder-decoder#transformers.EncoderDecoderModel) and `SpeechEncoderDecoder`.
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.Speech2Text2ForCausalLM.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_to_text_2/modeling_speech_to_text_2.py#L774</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "encoder_hidden_states", "val": " = None"}, {"name": "encoder_attention_mask", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "cross_attn_head_mask", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "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_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
  provide it.

  Indices can be obtained using [Speech2Text2Tokenizer](/docs/transformers/pr_15592/en/model_doc/speech_to_text_2#transformers.Speech2Text2Tokenizer). 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 input IDs?](../glossary#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?](../glossary#attention-mask)
- **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 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
  tensors 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 to `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](/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.CausalLMOutputWithCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithCrossAttentions) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.CausalLMOutputWithCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#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 ([Speech2Text2Config](/docs/transformers/pr_15592/en/model_doc/speech_to_text_2#transformers.Speech2Text2Config)) and inputs.

- **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 + 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 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) of 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`.

  Contains 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.</retdesc></docstring>







Example:

```python
>>> from transformers import (
...     SpeechEncoderDecoderModel,
...     Speech2Text2ForCausalLM,
...     Wav2Vec2Model,
...     Speech2Text2Config,
...     Wav2Vec2Config,
... )

>>> encoder = Wav2Vec2Model(Wav2Vec2Config())
>>> decoder = Speech2Text2ForCausalLM(Speech2Text2Config())
# init speech2text model

>>> model = SpeechEncoderDecoderModel(encoder=encoder, decoder=decoder)
```

</div></div>
