Speech Encoder Decoder Models
Speech Encoder Decoder Models
The SpeechEncoderDecoderModel can be used to initialize a speech-to-text model with any pretrained speech autoencoding model as the encoder (e.g. Wav2Vec2, 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 by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
An example of how to use a SpeechEncoderDecoderModel for inference can be seen in Speech2Text2.
Randomly initializing SpeechEncoderDecoderModel from model configurations.
SpeechEncoderDecoderModel can be randomly initialized from an encoder and a decoder config. In the following example, we show how to do this using the default Wav2Vec2Model configuration for the encoder and the default BertForCausalLM
configuration for the decoder.
Copied
Initialising SpeechEncoderDecoderModel from a pretrained encoder and a pretrained decoder.
SpeechEncoderDecoderModel can be initialized from a pretrained encoder checkpoint and a pretrained decoder checkpoint. Note that any pretrained Transformer-based speech model, e.g. Wav2Vec2, Hubert can serve as the encoder and both pretrained auto-encoding models, e.g. BERT, pretrained causal language models, e.g. GPT2, as well as the pretrained decoder part of sequence-to-sequence models, e.g. decoder of BART, can be used as the decoder. Depending on which architecture you choose as the decoder, the cross-attention layers might be randomly initialized. Initializing SpeechEncoderDecoderModel from a pretrained encoder and decoder checkpoint requires the model to be fine-tuned on a downstream task, as has been shown in the Warm-starting-encoder-decoder blog post. To do so, the SpeechEncoderDecoderModel
class provides a SpeechEncoderDecoderModel.from_encoder_decoder_pretrained() method.
Copied
Loading an existing SpeechEncoderDecoderModel checkpoint and perform inference.
To load fine-tuned checkpoints of the SpeechEncoderDecoderModel
class, SpeechEncoderDecoderModel provides the from_pretrained(...)
method just like any other model architecture in Transformers.
To perform inference, one uses the generate
method, which allows to autoregressively generate text. This method supports various forms of decoding, such as greedy, beam search and multinomial sampling.
Copied
Training
Once the model is created, it can be fine-tuned similar to BART, T5 or any other encoder-decoder model on a dataset of (speech, text) pairs. As you can see, only 2 inputs are required for the model in order to compute a loss: input_values
(which are the speech inputs) and labels
(which are the input_ids
of the encoded target sequence).
Copied
SpeechEncoderDecoderConfig
class transformers.SpeechEncoderDecoderConfig
( **kwargs )
Parameters
kwargs (optional) β Dictionary of keyword arguments. Notably:
encoder (PretrainedConfig, optional) β An instance of a configuration object that defines the encoder config.
decoder (PretrainedConfig, optional) β An instance of a configuration object that defines the decoder config.
SpeechEncoderDecoderConfig is the configuration class to store the configuration of a 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 and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
Examples:
Copied
from_encoder_decoder_configs
( encoder_config: PretrainedConfigdecoder_config: PretrainedConfig**kwargs ) β SpeechEncoderDecoderConfig
Returns
An instance of a configuration object
Instantiate a SpeechEncoderDecoderConfig (or a derived class) from a pre-trained encoder model configuration and decoder model configuration.
SpeechEncoderDecoderModel
class transformers.SpeechEncoderDecoderModel
( config: typing.Optional[transformers.configuration_utils.PretrainedConfig] = Noneencoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = Nonedecoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None )
Parameters
config (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() method to load the model weights.
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 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 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. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
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.
forward
( inputs: typing.Optional[torch.FloatTensor] = Noneattention_mask: typing.Optional[torch.FloatTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.BoolTensor] = Noneencoder_outputs: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonepast_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonedecoder_inputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Noneinput_values: typing.Optional[torch.FloatTensor] = Noneinput_features: typing.Optional[torch.FloatTensor] = Nonereturn_dict: typing.Optional[bool] = None**kwargs ) β transformers.modeling_outputs.Seq2SeqLMOutput or tuple(torch.FloatTensor)
Parameters
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 typeList[float]
or anumpy.ndarray
, e.g. via the soundfile library (pip install soundfile
). To prepare the array intoinputs
, either the Wav2Vec2Processor or Speech2TextProcessor should be used for padding and conversion into a tensor of typetorch.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.
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. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
If
past_key_values
is used, optionally only the lastdecoder_input_ids
have to be input (seepast_key_values
).For training,
decoder_input_ids
are automatically created by the model by shifting thelabels
to the right, replacing -100 by thepad_token_id
and prepending them with thedecoder_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 indecoder_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 lengthconfig.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 lastdecoder_input_ids
(those that donβt have their past key value states given to this model) of shape(batch_size, 1)
instead of alldecoder_input_ids
of shape(batch_size, sequence_length)
.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_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 passingdecoder_input_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convertdecoder_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]
(seeinput_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 toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
).output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_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 should be used for padding and conversion into a tensor of type torch.FloatTensor. See Wav2Vec2Processor.call() for details.input_features (
torch.FloatTensor
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 typeList[float]
or anumpy.ndarray
, e.g. via the soundfile library (pip install soundfile
). To prepare the array intoinput_features
, the Speech2TextFeatureExtractor should be used for extracting the fbank features, padding and conversion into a tensor of typetorch.FloatTensor
. See call()return_dict (
bool
, optional) β If set toTrue
, the model will return a~utils.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.
Returns
transformers.modeling_outputs.Seq2SeqLMOutput or tuple(torch.FloatTensor)
A 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) and inputs.
loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
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 whenuse_cache=True
is passed or whenconfig.use_cache=True
) β Tuple oftuple(torch.FloatTensor)
of lengthconfig.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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.
The SpeechEncoderDecoderModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Examples:
Copied
from_encoder_decoder_pretrained
( encoder_pretrained_model_name_or_path: str = Nonedecoder_pretrained_model_name_or_path: str = None*model_args**kwargs )
Parameters
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 boincai.com. Valid model ids can be located at the root-level, like
bert-base-uncased
, or namespaced under a user or organization name, likedbmdz/bert-base-german-cased
.A path to a directory containing model weights saved using 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 toTrue
and a configuration object should be provided asconfig
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 toNone
) β Information necessary to initiate the decoder. Can be either:A string, the model id of a pretrained model hosted inside a model repo on boincai.com. Valid model ids can be located at the root-level, like
bert-base-uncased
, or namespaced under a user or organization name, likedbmdz/bert-base-german-cased
.A path to a directory containing model weights saved using 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 toTrue
and a configuration object should be provided asconfig
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.
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:
Copied
FlaxSpeechEncoderDecoderModel
class transformers.FlaxSpeechEncoderDecoderModel
( config: SpeechEncoderDecoderConfiginput_shape: typing.Optional[typing.Tuple] = Noneseed: int = 0dtype: dtype = <class 'jax.numpy.float32'>_do_init: bool = True**kwargs )
Parameters
config (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() method to load the model weights.
dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) β The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If specified all the computation will be performed with the given
dtype
.Note that this only specifies the dtype of the computation and does not influence the dtype of model parameters.
If you wish to change the dtype of the model parameters, see to_fp16() and to_bf16().
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 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 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 FlaxPreTrainedModel. 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 Flax Linen flax.nn.Module subclass. Use it as a regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
FlaxSpeechEncoderDecoderModel is a generic model class that will be instantiated as a transformer architecture with the module (flax.nn.Module) of one of the base model classes of the library as encoder module and another one as decoder module when created with the :meth~transformers.FlaxAutoModel.from_pretrained class method for the encoder and :meth~transformers.FlaxAutoModelForCausalLM.from_pretrained class method for the decoder.
__call__
( inputs: Arrayattention_mask: typing.Optional[jax.Array] = Nonedecoder_input_ids: typing.Optional[jax.Array] = Nonedecoder_attention_mask: typing.Optional[jax.Array] = Nonedecoder_position_ids: typing.Optional[jax.Array] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = Nonetrain: bool = Falsefreeze_feature_encoder: bool = Falseparams: dict = Nonedropout_rng: PRNGKey = None ) β transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput or tuple(torch.FloatTensor)
Parameters
inputs (
jnp.ndarray
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 typeList[float]
or anumpy.ndarray
, e.g. via the soundfile library (pip install soundfile
). To prepare the array intoinputs
, either the Wav2Vec2Processor or Speech2TextProcessor should be used for padding and conversion into a tensor of typetorch.FloatTensor
.attention_mask (
jnp.ndarray
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.
decoder_input_ids (
jnp.ndarray
of shape(batch_size, target_sequence_length)
, optional) β Indices of decoder input sequence tokens in the vocabulary.Indices can be obtained using PreTrainedTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
If
past_key_values
is used, optionally only the lastdecoder_input_ids
have to be input (seepast_key_values
).For sequence to sequence training,
decoder_input_ids
should be provided.decoder_input_ids
should be created outside of the model by shifting thelabels
to the right, replacing -100 by thepad_token_id
and prepending them with thedecoder_start_token_id
.decoder_attention_mask (
jnp.ndarray
of shape(batch_size, target_sequence_length)
, optional) β Default behavior: generate a tensor that ignores pad tokens indecoder_input_ids
. Causal mask will also be used by default.decoder_position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) β Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range[0, config.decoder.max_position_embeddings - 1]
.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return a~utils.FlaxSeq2SeqLMOutput
instead of a plain tuple.
Returns
transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput or tuple(torch.FloatTensor)
A transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput 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) and inputs.
logits (
jnp.ndarray
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(jnp.ndarray))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) β Tuple oftuple(jnp.ndarray)
of lengthconfig.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(jnp.ndarray)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple ofjnp.ndarray
(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(jnp.ndarray)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple ofjnp.ndarray
(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(jnp.ndarray)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple ofjnp.ndarray
(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 (
jnp.ndarray
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(jnp.ndarray)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple ofjnp.ndarray
(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(jnp.ndarray)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple ofjnp.ndarray
(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.
The FlaxSpeechEncoderDecoderModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Examples:
Copied
from_encoder_decoder_pretrained
( encoder_pretrained_model_name_or_path: typing.Union[str, os.PathLike, NoneType] = Nonedecoder_pretrained_model_name_or_path: typing.Union[str, os.PathLike, NoneType] = None*model_args**kwargs )
Parameters
encoder_pretrained_model_name_or_path (
Union[str, os.PathLike]
, 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 boincai.com. Valid model ids can be located at the root-level, like
bert-base-uncased
, or namespaced under a user or organization name, likedbmdz/bert-base-german-cased
.A path to a directory containing model weights saved using save_pretrained(), e.g.,
./my_model_directory/
.
decoder_pretrained_model_name_or_path (
Union[str, os.PathLike]
, optional, defaults toNone
) β Information necessary to initiate the decoder. Can be either:A string, the model id of a pretrained model hosted inside a model repo on boincai.com. Valid model ids can be located at the root-level, like
bert-base-uncased
, or namespaced under a user or organization name, likedbmdz/bert-base-german-cased
.A path to a directory containing model weights saved using save_pretrained(), e.g.,
./my_model_directory/
.
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.
Instantiate an encoder and a decoder from one or two base classes of the library from pretrained model checkpoints.
Example:
Copied
Last updated