---
local: speech-encoder-decoder-models
sections:
- local: transformers.SpeechEncoderDecoderConfig
  title: SpeechEncoderDecoderConfig
- local: transformers.SpeechEncoderDecoderModel
  title: SpeechEncoderDecoderModel
title: Speech Encoder Decoder Models
---
<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="speech-encoder-decoder-models">Speech Encoder Decoder Models</h1>

The [SpeechEncoderDecoderModel](/docs/transformers/pr_15592/en/model_doc/speech-encoder-decoder#transformers.SpeechEncoderDecoderModel) can be used to initialize a speech-sequence-to-text-sequence model
with any pretrained speech autoencoding model as the encoder (*e.g.* [Wav2Vec2](wav2vec2), [Hubert](hubert)) and any pretrained autoregressive model as the decoder.

The effectiveness of initializing speech-sequence-to-text-sequence models with pretrained checkpoints for speech
recognition and speech translation has *e.g.* been shown 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.

An example of how to use a [SpeechEncoderDecoderModel](/docs/transformers/pr_15592/en/model_doc/speech-encoder-decoder#transformers.SpeechEncoderDecoderModel) for inference can be seen in
[Speech2Text2](speech_to_text_2).


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

<div class="docstring">

<docstring><name>class transformers.SpeechEncoderDecoderConfig</name><anchor>transformers.SpeechEncoderDecoderConfig</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py#L27</source><parameters>[{"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **kwargs** (*optional*) --
  Dictionary of keyword arguments. Notably:

  - **encoder** ([PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig), *optional*) -- An instance of a configuration object that defines
    the encoder config.
  - **decoder** ([PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig), *optional*) -- An instance of a configuration object that defines
    the decoder config.</paramsdesc><paramgroups>0</paramgroups></docstring>

[SpeechEncoderDecoderConfig](/docs/transformers/pr_15592/en/model_doc/speech-encoder-decoder#transformers.SpeechEncoderDecoderConfig) is the configuration class to store the configuration of a
[SpeechEncoderDecoderModel](/docs/transformers/pr_15592/en/model_doc/speech-encoder-decoder#transformers.SpeechEncoderDecoderModel). It is used to instantiate an Encoder Decoder model according to the specified
arguments, defining the encoder and decoder configs.

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.



Examples:

```python
>>> from transformers import BertConfig, Wav2Vec2Config, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel

>>> # Initializing a Wav2Vec2 & BERT style configuration
>>> config_encoder = Wav2Vec2Config()
>>> config_decoder = BertConfig()

>>> config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder)

>>> # Initializing a Wav2Vec2Bert model from a Wav2Vec2 & bert-base-uncased style configurations
>>> model = SpeechEncoderDecoderModel(config=config)

>>> # Accessing the model configuration
>>> config_encoder = model.config.encoder
>>> config_decoder = model.config.decoder
>>> # set decoder config to causal lm
>>> config_decoder.is_decoder = True
>>> config_decoder.add_cross_attention = True

>>> # Saving the model, including its configuration
>>> model.save_pretrained("my-model")

>>> # loading model and config from pretrained folder
>>> encoder_decoder_config = SpeechEncoderDecoderConfig.from_pretrained("my-model")
>>> model = SpeechEncoderDecoderModel.from_pretrained("my-model", config=encoder_decoder_config)
```


<div class="docstring">
<docstring><name>from\_encoder\_decoder\_configs</name><anchor>transformers.SpeechEncoderDecoderConfig.from_encoder_decoder_configs</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py#L92</source><parameters>[{"name": "encoder_config", "val": ": PretrainedConfig"}, {"name": "decoder_config", "val": ": PretrainedConfig"}, {"name": "**kwargs", "val": ""}]</parameters><rettype>[SpeechEncoderDecoderConfig](/docs/transformers/pr_15592/en/model_doc/speech-encoder-decoder#transformers.SpeechEncoderDecoderConfig)</rettype><retdesc>An instance of a configuration object</retdesc></docstring>

Instantiate a [SpeechEncoderDecoderConfig](/docs/transformers/pr_15592/en/model_doc/speech-encoder-decoder#transformers.SpeechEncoderDecoderConfig) (or a derived class) from a pre-trained encoder model
configuration and decoder model configuration.






</div>
<div class="docstring">
<docstring><name>to\_dict</name><anchor>transformers.SpeechEncoderDecoderConfig.to_dict</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py#L109</source><parameters>[]</parameters><rettype>`Dict[str, any]`</rettype><retdesc>Dictionary of all the attributes that make up this configuration instance,</retdesc></docstring>

Serializes this instance to a Python dictionary. Override the default *to_dict()* from *PretrainedConfig*.






</div></div>

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

<div class="docstring">

<docstring><name>class transformers.SpeechEncoderDecoderModel</name><anchor>transformers.SpeechEncoderDecoderModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py#L174</source><parameters>[{"name": "config", "val": ": typing.Optional[transformers.configuration_utils.PretrainedConfig] = None"}, {"name": "encoder", "val": ": typing.Optional[transformers.modeling_utils.PreTrainedModel] = None"}, {"name": "decoder", "val": ": typing.Optional[transformers.modeling_utils.PreTrainedModel] = None"}]</parameters><paramsdesc>- **config** ([SpeechEncoderDecoderConfig](/docs/transformers/pr_15592/en/model_doc/speech-encoder-decoder#transformers.SpeechEncoderDecoderConfig)) -- 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>

This class can be used to initialize a speech-sequence-to-text-sequence model with any pretrained speech
autoencoding model as the encoder and any pretrained text autoregressive model as the decoder. The encoder is
loaded via `from_pretrained()`function and the decoder is loaded via
`from_pretrained()`function. Cross-attention layers are automatically added to the decoder
and should be fine-tuned on a downstream generative task, like summarization.

The effectiveness of initializing sequence-to-sequence models with pretrained checkpoints for sequence generation
tasks was shown in [Leveraging Pre-trained Checkpoints for Sequence Generation
Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. Michael Matena, Yanqi
Zhou, Wei Li, Peter J. Liu.

Additionally, in [Large-Scale Self- and Semi-Supervised Learning for Speech
Translation](https://arxiv.org/abs/2104.06678) it is shown how leveraging large pretrained speech models for speech
translation yields a significant performance improvement.

After such an Speech-Encoder Decoder model has been trained/fine-tuned, it can be saved/loaded just like any other
models (see the examples for more information).

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.



[SpeechEncoderDecoderModel](/docs/transformers/pr_15592/en/model_doc/speech-encoder-decoder#transformers.SpeechEncoderDecoderModel) is a generic model class that will be instantiated as a transformer architecture with
one of the base model classes of the library as encoder and another one as decoder when created with the
:meth*~transformers.AutoModel.from_pretrained* class method for the encoder and
:meth*~transformers.AutoModelForCausalLM.from_pretrained* class method for the decoder.



<div class="docstring">
<docstring><name>forward</name><anchor>transformers.SpeechEncoderDecoderModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py#L442</source><parameters>[{"name": "inputs", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "decoder_input_ids", "val": " = None"}, {"name": "decoder_attention_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": "input_values", "val": " = None"}, {"name": "input_features", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **inputs** (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, feature_dim)`, *optional*) --
  Float values of input raw speech waveform or speech features. Values 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 *inputs*, either the [Wav2Vec2Processor](/docs/transformers/pr_15592/en/model_doc/wav2vec2#transformers.Wav2Vec2Processor) or
  [Speech2TextProcessor](/docs/transformers/pr_15592/en/model_doc/speech_to_text#transformers.Speech2TextProcessor) should be used for padding and conversion into a tensor of type
  *torch.FloatTensor*.
- **attention_mask** (`torch.FloatTensor` 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)
- **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 [PreTrainedTokenizer](/docs/transformers/pr_15592/en/main_classes/tokenizer#transformers.PreTrainedTokenizer). 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)

  If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
  `past_key_values`).

  For training, `decoder_input_ids` are automatically created by the model by shifting the `labels` to the
  right, replacing -100 by the `pad_token_id` and prepending them with the `decoder_start_token_id`.
- **decoder_attention_mask** (`torch.BoolTensor` 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.
- **encoder_outputs** (`tuple(torch.FloatTensor)`, *optional*) --
  This tuple must consist of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
  `last_hidden_state` (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) is a tensor
  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))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`) --
  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)`.
- **inputs_embeds** (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) --
  Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  model's internal embedding lookup matrix.
- **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. 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.
- **labels** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Labels for computing the masked language modeling loss for the decoder. Indices should be in `[-100, 0,
  ..., config.vocab_size]` (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`).
- **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.
- **input_values** (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Float values of input raw speech waveform. Values 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_values*, the [Wav2Vec2Processor](/docs/transformers/pr_15592/en/model_doc/wav2vec2#transformers.Wav2Vec2Processor) should be used for padding
  and conversion into a tensor of type *torch.FloatTensor*. See [Wav2Vec2Processor.__call__()](/docs/transformers/pr_15592/en/model_doc/wav2vec2#transformers.Wav2Vec2Processor.__call__) for details.
- **input_features** (`torch.LongTensor` of shape `(batch_size, sequence_length, feature_size)`, *optional*) --
  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__)
- **return_dict** (`bool`, *optional*) --
  If set to `True`, the model will return a `Seq2SeqLMOutput` instead of a plain tuple.
  kwargs -- (*optional*) Remaining dictionary of keyword arguments. Keyword arguments come in two flavors:

  - Without a prefix which will be input as `**encoder_kwargs` for the encoder forward function.
  - With a *decoder_* prefix which will be input as `**decoder_kwargs` for the decoder forward function.</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 ([SpeechEncoderDecoderConfig](/docs/transformers/pr_15592/en/model_doc/speech-encoder-decoder#transformers.SpeechEncoderDecoderConfig)) 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 [SpeechEncoderDecoderModel](/docs/transformers/pr_15592/en/model_doc/speech-encoder-decoder#transformers.SpeechEncoderDecoderModel) 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>







Examples:

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

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

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

>>> input_values = processor(ds[0]["audio"]["array"], return_tensors="pt").input_values
>>> decoder_input_ids = torch.tensor([[model.config.decoder.decoder_start_token_id]])
>>> outputs = model(input_values=input_values, decoder_input_ids=decoder_input_ids)

>>> # inference (generation)
>>> generated = model.generate(input_values)
>>> translation = processor.batch_decode(generated)
```

</div>
<div class="docstring">
<docstring><name>from\_encoder\_decoder\_pretrained</name><anchor>transformers.SpeechEncoderDecoderModel.from_encoder_decoder_pretrained</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py#L286</source><parameters>[{"name": "encoder_pretrained_model_name_or_path", "val": ": str = None"}, {"name": "decoder_pretrained_model_name_or_path", "val": ": str = None"}, {"name": "*model_args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **encoder_pretrained_model_name_or_path** (`str`, *optional*) --
  Information necessary to initiate the encoder. Can be either:

  - A string, the *model id* of a pretrained model 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 model weights saved using
    [save_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.save_pretrained), e.g., `./my_model_directory/`.
  - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
    this case, `from_tf` should be set to `True` and a configuration object should be provided as
    `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
    PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.

- **decoder_pretrained_model_name_or_path** (`str`, *optional*, defaults to `None`) --
  Information necessary to initiate the decoder. Can be either:

  - A string, the *model id* of a pretrained model 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 model weights saved using
    [save_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.save_pretrained), e.g., `./my_model_directory/`.
  - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
    this case, `from_tf` should be set to `True` and a configuration object should be provided as
    `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
    PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.

- **model_args** (remaining positional arguments, *optional*) --
  All remaning positional arguments will be passed to the underlying model's `__init__` method.

- **kwargs** (remaining dictionary of keyword arguments, *optional*) --
  Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
  `output_attentions=True`).

  - To update the encoder configuration, use the prefix *encoder_* for each configuration parameter.
  - To update the decoder configuration, use the prefix *decoder_* for each configuration parameter.
  - To update the parent model configuration, do not use a prefix for each configuration parameter.

  Behaves differently depending on whether a `config` is provided or automatically loaded.</paramsdesc><paramgroups>0</paramgroups></docstring>

Instantiate an encoder and a decoder from one or two base classes of the library from pretrained model
checkpoints.


The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
the model, you need to first set it back in training mode with `model.train()`.



Example:

```python
>>> from transformers import SpeechEncoderDecoderModel

>>> # initialize a wav2vec2bert from a pretrained Wav2Vec2 and a pretrained BERT model. Note that the cross-attention layers will be randomly initialized
>>> model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained(
...     "facebook/wav2vec2-base-960h", "bert-base-uncased"
... )
>>> # saving model after fine-tuning
>>> model.save_pretrained("./wav2vec2bert")
>>> # load fine-tuned model
>>> model = SpeechEncoderDecoderModel.from_pretrained("./wav2vec2bert")
```

</div></div>
