Speech2TextΒΆ
OverviewΒΆ
The Speech2Text model was proposed in fairseq S2T: Fast Speech-to-Text Modeling with fairseq by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino. Itβs a transformer-based seq2seq (encoder-decoder) model designed for end-to-end Automatic Speech Recognition (ASR) and Speech Translation (ST). It uses a convolutional downsampler to reduce the length of speech inputs by 3/4th before they are fed into the encoder. The model is trained with standard autoregressive cross-entropy loss and generates the transcripts/translations autoregressively. Speech2Text has been fine-tuned on several datasets for ASR and ST: LibriSpeech, CoVoST 2, MuST-C.
This model was contributed by valhalla. The original code can be found here.
InferenceΒΆ
Speech2Text is a speech model that accepts a float tensor of log-mel filter-bank features extracted from the speech
signal. Itβs a transformer-based seq2seq model, so the transcripts/translations are generated autoregressively. The
generate() method can be used for inference.
The Speech2TextFeatureExtractor class is responsible for extracting the log-mel filter-bank
features. The Speech2TextProcessor wraps Speech2TextFeatureExtractor and
Speech2TextTokenizer into a single instance to both extract the input features and decode the
predicted token ids.
The feature extractor depends on torchaudio and the tokenizer depends on sentencepiece so be sure to
install those packages before running the examples. You could either install those as extra speech dependancies with
pip install transformers"[speech, sentencepiece]" or install the packages seperatly with pip install torchaudio
sentencepiece. Also torchaudio requires the development version of the libsndfile package which can be installed via a system package manager. On Ubuntu it can
be installed as follows: apt install libsndfile1-dev
ASR and Speech Translation
>>> import torch
>>> from transformers import Speech2TextProcessor, Speech2TextForConditionalGeneration
>>> from datasets import load_dataset
>>> import soundfile as sf
>>> model = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-librispeech-asr")
>>> processor = Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr")
>>> def map_to_array(batch):
... speech, _ = sf.read(batch["file"])
... batch["speech"] = speech
... return batch
>>> ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.map(map_to_array)
>>> inputs = processor(ds["speech"][0], sampling_rate=16_000, return_tensors="pt")
>>> generated_ids = model.generate(input_ids=inputs["input_features"], attention_mask=inputs["attention_mask"])
>>> transcription = processor.batch_decode(generated_ids)
Multilingual speech translation
For multilingual speech translation models,
eos_token_idis used as thedecoder_start_token_idand the target language id is forced as the first generated token. To force the target language id as the first generated token, pass theforced_bos_token_idparameter to thegenerate()method. The following example shows how to transate English speech to French text using the facebook/s2t-medium-mustc-multilingual-st checkpoint.
>>> import torch
>>> from transformers import Speech2TextProcessor, Speech2TextForConditionalGeneration
>>> from datasets import load_dataset
>>> import soundfile as sf
>>> model = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-medium-mustc-multilingual-st")
>>> processor = Speech2TextProcessor.from_pretrained("facebook/s2t-medium-mustc-multilingual-st")
>>> def map_to_array(batch):
... speech, _ = sf.read(batch["file"])
... batch["speech"] = speech
... return batch
>>> ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.map(map_to_array)
>>> inputs = processor(ds["speech"][0], sampling_rate=16_000, return_tensors="pt")
>>> generated_ids = model.generate(input_ids=inputs["input_features"], attention_mask=inputs["attention_mask], forced_bos_token_id=processor.tokenizer.lang_code_to_id["fr"])
>>> translation = processor.batch_decode(generated_ids)
See the model hub to look for Speech2Text checkpoints.
Speech2TextConfigΒΆ
-
class
transformers.Speech2TextConfig(vocab_size=10000, encoder_layers=12, encoder_ffn_dim=2048, encoder_attention_heads=4, decoder_layers=6, decoder_ffn_dim=2048, decoder_attention_heads=4, encoder_layerdrop=0.0, decoder_layerdrop=0.0, use_cache=True, is_encoder_decoder=True, activation_function='relu', d_model=256, dropout=0.1, attention_dropout=0.0, activation_dropout=0.0, init_std=0.02, decoder_start_token_id=2, classifier_dropout=0.0, scale_embedding=True, gradient_checkpointing=False, pad_token_id=1, bos_token_id=0, eos_token_id=2, max_source_positions=6000, max_target_positions=1024, num_conv_layers=2, conv_kernel_sizes=(5, 5), conv_channels=1024, input_feat_per_channel=80, input_channels=1, **kwargs)[source]ΒΆ This is the configuration class to store the configuration of a
Speech2TextModel. It is used to instantiate an Speech2Text model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Speech2Text facebook/s2t-small-librispeech-asr architecture.Configuration objects inherit from
PretrainedConfigand can be used to control the model outputs. Read the documentation fromPretrainedConfigfor more information.- Parameters
vocab_size (
int, optional, defaults to 50265) β Vocabulary size of the Speech2Text model. Defines the number of different tokens that can be represented by theinputs_idspassed when callingSpeech2TextModeld_model (
int, optional, defaults to 1024) β Dimensionality of the layers and the pooler layer.encoder_layers (
int, optional, defaults to 12) β Number of encoder layers.decoder_layers (
int, optional, defaults to 12) β Number of decoder layers.encoder_attention_heads (
int, optional, defaults to 16) β Number of attention heads for each attention layer in the Transformer encoder.decoder_attention_heads (
int, optional, defaults to 16) β Number of attention heads for each attention layer in the Transformer decoder.decoder_ffn_dim (
int, optional, defaults to 4096) β Dimensionality of the βintermediateβ (often named feed-forward) layer in decoder.encoder_ffn_dim (
int, optional, defaults to 4096) β Dimensionality of the βintermediateβ (often named feed-forward) layer in decoder.activation_function (
strorfunction, optional, defaults to"gelu") β The non-linear activation function (function or string) in the encoder and pooler. If string,"gelu","relu","silu"and"gelu_new"are supported.dropout (
float, optional, defaults to 0.1) β The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.attention_dropout (
float, optional, defaults to 0.0) β The dropout ratio for the attention probabilities.activation_dropout (
float, optional, defaults to 0.0) β The dropout ratio for activations inside the fully connected layer.classifier_dropout (
float, optional, defaults to 0.0) β The dropout ratio for classifier.init_std (
float, optional, defaults to 0.02) β The standard deviation of the truncated_normal_initializer for initializing all weight matrices.encoder_layerdrop β (
float, optional, defaults to 0.0): The LayerDrop probability for the encoder. See the LayerDrop paper for more details.decoder_layerdrop β (
float, optional, defaults to 0.0): The LayerDrop probability for the decoder. See the LayerDrop paper for more details.use_cache (
bool, optional, defaults toTrue) β Whether or not the model should return the last key/values attentions (not used by all models).max_source_positions (
int, optional, defaults to 6000) β The maximum sequence length of log-mel filter-bank features that this model might ever be used with.max_target_positions β (
int, optional, defaults to 1024): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048).num_conv_layers (
int, optional, defaults to 2) β Number of 1D convolutional layers in the conv module.conv_kernel_sizes (
Tuple[int], optional, defaults to(5, 5)) β A tuple of integers defining the kernel size of each 1D convolutional layer in the conv module. The length ofconv_kernel_sizeshas to matchnum_conv_layers.conv_channels (
int, optional, defaults to 1024) β An integer defining the number of output channels of each convolution layers except the final one in the conv module.input_feat_per_channel (
int, optional, defaults to 80) β An integer specifying the size of feature vector. This is also the dimensions of log-mel filter-bank features.input_channels (
int, optional, defaults to 1) β An integer specifying number of input channels of the input feature vector.Example:: β
from transformers import Speech2TextModel (>>>) β
Speech2TextConfig β
# Initializing a Speech2Text s2t_transformer_s style configuration (>>>) β
configuration = Speech2TextConfig() (>>>) β
# Initializing a model from the s2t_transformer_s style configuration (>>>) β
model = Speech2TextModel (>>>) β
# Accessing the model configuration (>>>) β
configuration = model.config (>>>) β
Speech2TextTokenizerΒΆ
-
class
transformers.Speech2TextTokenizer(vocab_file, spm_file, bos_token='<s>', eos_token='</s>', pad_token='<pad>', unk_token='<unk>', do_upper_case=False, do_lower_case=False, tgt_lang=None, lang_codes=None, sp_model_kwargs: Optional[Dict[str, Any]] = None, **kwargs)[source]ΒΆ Construct an Speech2Text tokenizer.
This tokenizer inherits from
PreTrainedTokenizerwhich contains some of the main methods. Users should refer to the superclass for more information regarding such methods.- Parameters
vocab_file (
str) β File containing the vocabulary.spm_file (
str) β Path to the SentencePiece model filebos_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"<unk>") β The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead.pad_token (
str, optional, defaults to"<pad>") β The token used for padding, for example when batching sequences of different lengths.do_upper_case (
bool, optional, defaults toFalse) β Whether or not to uppercase the output when decoding.do_lower_case (
bool, optional, defaults toFalse) β Whether or not to lowercase the input when tokenizing.tgt_lang (
str, optional) β A string representing the target language.sp_model_kwargs (
dict, optional) βWill be passed to the
SentencePieceProcessor.__init__()method. The Python wrapper for SentencePiece can be used, among other things, to set:enable_sampling: Enable subword regularization.nbest_size: Sampling parameters for unigram. Invalid for BPE-Dropout.nbest_size = {0,1}: No sampling is performed.nbest_size > 1: samples from the nbest_size results.nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm.
alpha: Smoothing parameter for unigram sampling, and dropout probability of merge operations for BPE-dropout.
**kwargs β Additional keyword arguments passed along to
PreTrainedTokenizer
-
build_inputs_with_special_tokens(token_ids_0, token_ids_1=None) → List[int][source]ΒΆ Build model inputs from a sequence by appending eos_token_id.
-
create_token_type_ids_from_sequences(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None) → List[int]ΒΆ Create the token type IDs corresponding to the sequences passed. What are token type IDs?
Should be overridden in a subclass if the model has a special way of building those.
- Parameters
token_ids_0 (
List[int]) β The first tokenized sequence.token_ids_1 (
List[int], optional) β The second tokenized sequence.
- Returns
The token type ids.
- Return type
List[int]
-
get_special_tokens_mask(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False) → List[int][source]ΒΆ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer
prepare_for_modelmethod.- Parameters
token_ids_0 (
List[int]) β List of IDs.token_ids_1 (
List[int], optional) β Optional second list of IDs for sequence pairs.already_has_special_tokens (
bool, optional, defaults toFalse) β Whether or not the token list is already formatted with special tokens for the model.
- Returns
A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
- Return type
List[int]
-
save_vocabulary(save_directory: str, filename_prefix: Optional[str] = None) → Tuple[str][source]ΒΆ Save only the vocabulary of the tokenizer (vocabulary + added tokens).
This method wonβt save the configuration and special token mappings of the tokenizer. Use
_save_pretrained()to save the whole state of the tokenizer.- Parameters
save_directory (
str) β The directory in which to save the vocabulary.filename_prefix (
str, optional) β An optional prefix to add to the named of the saved files.
- Returns
Paths to the files saved.
- Return type
Tuple(str)
Speech2TextFeatureExtractorΒΆ
-
class
transformers.Speech2TextFeatureExtractor(feature_size=80, sampling_rate=16000, num_mel_bins=80, padding_value=0.0, do_ceptral_normalize=True, normalize_means=True, normalize_vars=True, **kwargs)[source]ΒΆ Constructs a Speech2Text feature extractor.
This feature extractor inherits from
Speech2TextFeatureExtractorwhich contains most of the main methods. Users should refer to this superclass for more information regarding those methods.This class extracts mel-filter bank features from raw speech using TorchAudio and applies utterance-level cepstral mean and variance normalization to the extracted features.
- Parameters
feature_size (
int, defaults to 80) β The feature dimension of the extracted features.sampling_rate (
int, defaults to 16000) β The sampling rate at which the audio files should be digitalized expressed in Hertz per second (Hz).num_mel_bins (
int, defaults to 80) β Number of Mel-frequency bins.padding_value (
float, defaults to 0.0) β The value that is used to fill the padding vectors.do_ceptral_normalize (
bool, optional, defaults toTrue) β Whether or not to apply utterance-level cepstral mean and variance normalization to extracted features.normalize_means (
bool, optional, defaults toTrue) β Whether or not to zero-mean normalize the extracted features.normalize_vars (
bool, optional, defaults toTrue) β Whether or not to unit-variance normalize the extracted features.
-
__call__(raw_speech: Union[numpy.ndarray, List[float], List[numpy.ndarray], List[List[float]]], padding: Union[bool, str, transformers.file_utils.PaddingStrategy] = False, max_length: Optional[int] = None, pad_to_multiple_of: Optional[int] = None, return_tensors: Optional[Union[str, transformers.file_utils.TensorType]] = None, sampling_rate: Optional[int] = None, return_attention_mask: Optional[bool] = None, **kwargs) → transformers.feature_extraction_utils.BatchFeature[source]ΒΆ Main method to featurize and prepare for the model one or several sequence(s). sequences.
- Parameters
raw_speech (
np.ndarray,List[float],List[np.ndarray],List[List[float]]) β The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float values, a list of numpy arrays or a list of list of float values.padding (
bool,strorPaddingStrategy, optional, defaults toTrue) βSelect a strategy to pad the returned sequences (according to the modelβs padding side and padding index) among:
Trueor'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).'max_length': Pad to a maximum length specified with the argumentmax_lengthor to the maximum acceptable input length for the model if that argument is not provided.Falseor'do_not_pad'(default): No padding (i.e., can output a batch with sequences of different lengths).
max_length (
int, optional) β Maximum length of the returned list and optionally padding length (see above).pad_to_multiple_of (
int, optional) βIf set will pad the sequence to a multiple of the provided value.
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
return_attention_mask (
bool, optional) βWhether to return the attention mask. If left to the default, will return the attention mask according to the specific feature_extractorβs default.
Note
For Speech2TextTransoformer models,
attention_maskshould alwys be passed for batched inference, to avoid subtle bugs.return_tensors (
strorTensorType, optional) βIf set, will return tensors instead of list of python integers. Acceptable values are:
'tf': Return TensorFlowtf.constantobjects.'pt': Return PyTorchtorch.Tensorobjects.'np': Return Numpynp.ndarrayobjects.
sampling_rate (
int, optional) β The sampling rate at which theraw_speechinput was sampled. It is strongly recommended to passsampling_rateat the forward call to prevent silent errors.padding_value (
float, defaults to 0.0) β The value that is used to fill the padding values / vectors.
Speech2TextProcessorΒΆ
-
class
transformers.Speech2TextProcessor(feature_extractor, tokenizer)[source]ΒΆ Constructs a Speech2Text processor which wraps a Speech2Text feature extractor and a Speech2Text tokenizer into a single processor.
Speech2TextProcessoroffers all the functionalities ofSpeech2TextFeatureExtractorandSpeech2TextTokenizer. See the__call__()anddecode()for more information.- Parameters
feature_extractor (
Speech2TextFeatureExtractor) β An instance ofSpeech2TextFeatureExtractor. The feature extractor is a required input.tokenizer (
Speech2TextTokenizer) β An instance ofSpeech2TextTokenizer. The tokenizer is a required input.
-
__call__(*args, **kwargs)[source]ΒΆ When used in normal mode, this method forwards all its arguments to Speech2TextFeatureExtractorβs
__call__()and returns its output. If used in the contextas_target_processor()this method forwards all its arguments to Speech2TextTokenizerβs__call__(). Please refer to the doctsring of the above two methods for more information.
-
as_target_processor()[source]ΒΆ Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning Speech2Text.
-
batch_decode(*args, **kwargs)[source]ΒΆ This method forwards all its arguments to Speech2TextTokenizerβs
batch_decode(). Please refer to the docstring of this method for more information.
-
decode(*args, **kwargs)[source]ΒΆ This method forwards all its arguments to Speech2TextTokenizerβs
decode(). Please refer to the docstring of this method for more information.
-
classmethod
from_pretrained(pretrained_model_name_or_path, **kwargs)[source]ΒΆ Instantiate a
Speech2TextProcessorfrom a pretrained Speech2Text processor.Note
This class method is simply calling Speech2TextFeatureExtractorβs
from_pretrained()and Speech2TextTokenizerβsfrom_pretrained(). Please refer to the docstrings of the methods above for more information.- Parameters
pretrained_model_name_or_path (
stroros.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, likedbmdz/bert-base-german-cased.a path to a directory containing a feature extractor file saved using the
save_pretrained()method, e.g.,./my_model_directory/.a path or url to a saved feature extractor JSON file, e.g.,
./my_model_directory/preprocessor_config.json.
**kwargs β Additional keyword arguments passed along to both
PreTrainedFeatureExtractorandPreTrainedTokenizer
-
save_pretrained(save_directory)[source]ΒΆ Save a Speech2Text feature extractor object and Speech2Text tokenizer object to the directory
save_directory, so that it can be re-loaded using thefrom_pretrained()class method.Note
This class method is simply calling
save_pretrained()andsave_pretrained(). Please refer to the docstrings of the methods above for more information.- Parameters
save_directory (
stroros.PathLike) β Directory where the feature extractor JSON file and the tokenizer files will be saved (directory will be created if it does not exist).
Speech2TextModelΒΆ
-
class
transformers.Speech2TextModel(config: transformers.models.speech_to_text.configuration_speech_to_text.Speech2TextConfig)[source]ΒΆ The bare Speech2Text Model outputting raw hidden-states without any specific head on top. 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.
- Parameters
config (
Speech2TextConfig) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()method to load the model weights.
-
forward(input_features=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs=None, past_key_values=None, decoder_inputs_embeds=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
Speech2TextModelforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_features (
torch.LongTensorof shape(batch_size, sequence_length, feature_size)) β Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a.flacor.wavaudio 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, theSpeech2TextTokenizershould be used for extracting the fbank features, padding and conversion into a tensor of typetorch.FloatTensor. See__call__()attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) βMask to avoid performing convolution and attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
decoder_input_ids (
torch.LongTensorof shape(batch_size, target_sequence_length), optional) βIndices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using
SpeechToTextTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.SpeechToText uses the
eos_token_idas the starting token fordecoder_input_idsgeneration. Ifpast_key_valuesis used, optionally only the lastdecoder_input_idshave to be input (seepast_key_values).decoder_attention_mask (
torch.LongTensorof 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. <<<<<<< HEADIf you want to change padding behavior, you should read
modeling_speech_to_text._prepare_decoder_inputs()and modify to your needs. See diagram 1 in the paper for more information on the default strategy.head_mask (
torch.Tensorof shape(encoder_layers, encoder_attention_heads), optional) βMask to nullify selected heads of the attention modules in the encoder. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
decoder_head_mask (
torch.Tensorof shape(decoder_layers, decoder_attention_heads), optional) βMask to nullify selected heads of the attention modules in the decoder. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
cross_attn_head_mask (
torch.Tensorof shape(decoder_layers, decoder_attention_heads), optional) βMask to nullify selected heads of the cross-attention modules. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
encoder_outputs (
tuple(tuple(torch.FloatTensor), optional) β Tuple consists of (last_hidden_state, optional:hidden_states, optional:attentions)last_hidden_stateof shape(batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.past_key_values (
tuple(tuple(torch.FloatTensor)), optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) βTuple of
tuple(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_valuesinput) to speed up sequential decoding.If
past_key_valuesare 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).decoder_inputs_embeds (
torch.FloatTensorof shape(batch_size, target_sequence_length, hidden_size), optional) βOptionally, instead of passing
decoder_input_idsyou can choose to directly pass an embedded representation. Ifpast_key_valuesis used, optionally only the lastdecoder_inputs_embedshave to be input (seepast_key_values). This is useful if you want more control over how to convertdecoder_input_idsindices into associated vectors than the modelβs internal embedding lookup matrix.If
decoder_input_idsanddecoder_inputs_embedsare both unset,decoder_inputs_embedstakes the value ofinputs_embeds.use_cache (
bool, optional) β If set toTrue,past_key_valueskey 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. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) β Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) β Whether or not to return aModelOutputinstead of a plain tuple.
- Returns
A
Seq2SeqModelOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (Speech2TextConfig) and inputs.last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size)) β Sequence of hidden-states at the output of the last layer of the decoder of the model.If
past_key_valuesis used only the last hidden-state of the sequences of shape(batch_size, 1, hidden_size)is output.past_key_values (
tuple(tuple(torch.FloatTensor)), optional, returned whenuse_cache=Trueis 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_valuesinput) to speed up sequential decoding.decoder_hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) β Tuple oftorch.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 whenoutput_attentions=Trueis 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=Trueis 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.FloatTensorof 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=Trueis passed or whenconfig.output_hidden_states=True) β Tuple oftorch.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 whenoutput_attentions=Trueis 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.
- Return type
Seq2SeqModelOutputortuple(torch.FloatTensor)
Example:
>>> from transformers import Speech2TextTokenizer, Speech2TextModel >>> import torch >>> tokenizer = Speech2TextTokenizer.from_pretrained('facebook/s2t-small-librispeech-asr') >>> model = Speech2TextModel.from_pretrained('facebook/s2t-small-librispeech-asr') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_states = outputs.last_hidden_state
Speech2TextForConditionalGenerationΒΆ
-
class
transformers.Speech2TextForConditionalGeneration(config: transformers.models.speech_to_text.configuration_speech_to_text.Speech2TextConfig)[source]ΒΆ The Speech2Text Model with a language modeling head. Can be used for summarization. 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.
- Parameters
config (
Speech2TextConfig) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()method to load the model weights.
-
forward(input_features=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs=None, past_key_values=None, decoder_inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
Speech2TextForConditionalGenerationforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_features (
torch.LongTensorof shape(batch_size, sequence_length, feature_size)) β Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a.flacor.wavaudio 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, theSpeech2TextTokenizershould be used for extracting the fbank features, padding and conversion into a tensor of typetorch.FloatTensor. See__call__()attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) βMask to avoid performing convolution and attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
decoder_input_ids (
torch.LongTensorof shape(batch_size, target_sequence_length), optional) βIndices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using
SpeechToTextTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.SpeechToText uses the
eos_token_idas the starting token fordecoder_input_idsgeneration. Ifpast_key_valuesis used, optionally only the lastdecoder_input_idshave to be input (seepast_key_values).decoder_attention_mask (
torch.LongTensorof 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. <<<<<<< HEADIf you want to change padding behavior, you should read
modeling_speech_to_text._prepare_decoder_inputs()and modify to your needs. See diagram 1 in the paper for more information on the default strategy.head_mask (
torch.Tensorof shape(encoder_layers, encoder_attention_heads), optional) βMask to nullify selected heads of the attention modules in the encoder. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
decoder_head_mask (
torch.Tensorof shape(decoder_layers, decoder_attention_heads), optional) βMask to nullify selected heads of the attention modules in the decoder. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
cross_attn_head_mask (
torch.Tensorof shape(decoder_layers, decoder_attention_heads), optional) βMask to nullify selected heads of the cross-attention modules. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
encoder_outputs (
tuple(tuple(torch.FloatTensor), optional) β Tuple consists of (last_hidden_state, optional:hidden_states, optional:attentions)last_hidden_stateof shape(batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.past_key_values (
tuple(tuple(torch.FloatTensor)), optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) βTuple of
tuple(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_valuesinput) to speed up sequential decoding.If
past_key_valuesare 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).decoder_inputs_embeds (
torch.FloatTensorof shape(batch_size, target_sequence_length, hidden_size), optional) βOptionally, instead of passing
decoder_input_idsyou can choose to directly pass an embedded representation. Ifpast_key_valuesis used, optionally only the lastdecoder_inputs_embedshave to be input (seepast_key_values). This is useful if you want more control over how to convertdecoder_input_idsindices into associated vectors than the modelβs internal embedding lookup matrix.If
decoder_input_idsanddecoder_inputs_embedsare both unset,decoder_inputs_embedstakes the value ofinputs_embeds.use_cache (
bool, optional) β If set toTrue,past_key_valueskey 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. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) β Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) β Whether or not to return aModelOutputinstead of a plain tuple.labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) β Labels for computing the language modeling loss. Indices should either be in[0, ..., config.vocab_size]or -100 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size].
- Returns
A
Seq2SeqLMOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (Speech2TextConfig) and inputs.loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) β Language modeling loss.logits (
torch.FloatTensorof 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=Trueis 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_valuesinput) to speed up sequential decoding.decoder_hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) β Tuple oftorch.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 whenoutput_attentions=Trueis 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=Trueis 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.FloatTensorof 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=Trueis passed or whenconfig.output_hidden_states=True) β Tuple oftorch.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 whenoutput_attentions=Trueis 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.
Example:
>>> import torch >>> from transformers import Speech2TextProcessor, Speech2TextForConditionalGeneration >>> from datasets import load_dataset >>> import soundfile as sf >>> model = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-librispeech-asr") >>> processor = Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr") >>> def map_to_array(batch): >>> speech, _ = sf.read(batch["file"]) >>> batch["speech"] = speech >>> return batch >>> ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean", split="validation") >>> ds = ds.map(map_to_array) >>> input_features = processor(ds["speech"][0], sampling_rate=16000, return_tensors="pt").input_features # Batch size 1 >>> generated_ids = model.generate(input_ids=input_features) >>> transcription = processor.batch_decode(generated_ids)
- Return type
Seq2SeqLMOutputortuple(torch.FloatTensor)