Transformers 文档

语音编码解码模型

语音编码解码模型

SpeechEncoderDecoderModel 可以用来初始化一个语音到文本的模型,使用任何预训练的语音自编码模型作为编码器(例如 Wav2Vec2, Hubert)和任何预训练的自回归模型作为解码器。

使用预训练检查点初始化语音序列到文本序列模型在语音识别和语音翻译中的有效性已在大规模自监督和半监督学习用于语音翻译中展示,作者为Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau。

一个关于如何使用SpeechEncoderDecoderModel进行推理的示例可以在Speech2Text2中看到。

从模型配置中随机初始化SpeechEncoderDecoderModel。

SpeechEncoderDecoderModel 可以从编码器和解码器配置中随机初始化。在下面的示例中,我们展示了如何使用默认的 Wav2Vec2Model 配置作为编码器,以及默认的 BertForCausalLM 配置作为解码器来实现这一点。

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

>>> config_encoder = Wav2Vec2Config()
>>> config_decoder = BertConfig()

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

从预训练的编码器和预训练的解码器初始化SpeechEncoderDecoderModel。

SpeechEncoderDecoderModel 可以从预训练的编码器检查点和预训练的解码器检查点初始化。请注意,任何预训练的基于Transformer的语音模型,例如 Wav2Vec2, Hubert 都可以作为编码器,而预训练的自动编码模型,例如 BERT,预训练的因果语言模型,例如 GPT2,以及序列到序列模型的预训练解码器部分,例如 BART的解码器,都可以用作解码器。 根据您选择作为解码器的架构,交叉注意力层可能会被随机初始化。 从预训练的编码器和解码器检查点初始化 SpeechEncoderDecoderModel 需要在下游任务上对模型进行微调,如 the Warm-starting-encoder-decoder blog post 中所示。 为此,SpeechEncoderDecoderModel 类提供了 SpeechEncoderDecoderModel.from_encoder_decoder_pretrained() 方法。

>>> from transformers import SpeechEncoderDecoderModel

>>> model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained(
...     "facebook/hubert-large-ll60k", "google-bert/bert-base-uncased"
... )

加载现有的SpeechEncoderDecoderModel检查点并执行推理。

要加载SpeechEncoderDecoderModel类的微调检查点,SpeechEncoderDecoderModel提供了from_pretrained(...)方法,就像Transformers中的其他模型架构一样。

要进行推理,可以使用generate方法,该方法允许自回归生成文本。此方法支持各种形式的解码,例如贪婪、束搜索和多采样。

>>> from transformers import Wav2Vec2Processor, SpeechEncoderDecoderModel
>>> from datasets import load_dataset
>>> import torch

>>> # load a fine-tuned speech translation model and corresponding processor
>>> model = SpeechEncoderDecoderModel.from_pretrained("facebook/wav2vec2-xls-r-300m-en-to-15")
>>> processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-xls-r-300m-en-to-15")

>>> # let's perform inference on a piece of English speech (which we'll translate to German)
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> input_values = processor(ds[0]["audio"]["array"], return_tensors="pt").input_values

>>> # autoregressively generate transcription (uses greedy decoding by default)
>>> generated_ids = model.generate(input_values)
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> print(generated_text)
Mr. Quilter ist der Apostel der Mittelschicht und wir freuen uns, sein Evangelium willkommen heißen zu können.

训练

一旦模型创建完成,它可以在(语音,文本)对的数据集上进行微调,类似于BART、T5或任何其他编码器-解码器模型。 如你所见,模型只需要2个输入来计算损失:input_values(这是语音输入)和labels(这是编码目标序列的input_ids)。

>>> from transformers import AutoTokenizer, AutoFeatureExtractor, SpeechEncoderDecoderModel
>>> from datasets import load_dataset

>>> encoder_id = "facebook/wav2vec2-base-960h"  # acoustic model encoder
>>> decoder_id = "google-bert/bert-base-uncased"  # text decoder

>>> feature_extractor = AutoFeatureExtractor.from_pretrained(encoder_id)
>>> tokenizer = AutoTokenizer.from_pretrained(decoder_id)
>>> # Combine pre-trained encoder and pre-trained decoder to form a Seq2Seq model
>>> model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained(encoder_id, decoder_id)

>>> model.config.decoder_start_token_id = tokenizer.cls_token_id
>>> model.config.pad_token_id = tokenizer.pad_token_id

>>> # load an audio input and pre-process (normalise mean/std to 0/1)
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> input_values = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt").input_values

>>> # load its corresponding transcription and tokenize to generate labels
>>> labels = tokenizer(ds[0]["text"], return_tensors="pt").input_ids

>>> # the forward function automatically creates the correct decoder_input_ids
>>> loss = model(input_values=input_values, labels=labels).loss
>>> loss.backward()

SpeechEncoderDecoderConfig

transformers.SpeechEncoderDecoderConfig

< >

( **kwargs )

参数

  • kwargs (可选) — 关键字参数字典。特别是:
    • encoder (PretrainedConfig, 可选) — 定义编码器配置的配置对象实例。
    • decoder (PretrainedConfig, 可选) — 定义解码器配置的配置对象实例。

SpeechEncoderDecoderConfig 是用于存储 SpeechEncoderDecoderModel 配置的配置类。它用于根据指定的参数实例化一个编码器解码器模型,定义编码器和解码器的配置。

配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。

示例:

>>> 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 & google-bert/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)

from_encoder_decoder_configs

< >

( encoder_config: PretrainedConfig decoder_config: PretrainedConfig **kwargs ) SpeechEncoderDecoderConfig

返回

SpeechEncoderDecoderConfig

配置对象的一个实例

从预训练的编码器模型配置和解码器模型配置实例化一个SpeechEncoderDecoderConfig(或派生类)。

语音编码解码模型

transformers.SpeechEncoderDecoderModel

< >

( config: typing.Optional[transformers.configuration_utils.PretrainedConfig] = None encoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None decoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None )

参数

  • config (SpeechEncoderDecoderConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。

该类可用于初始化一个语音序列到文本序列的模型,其中编码器可以是任何预训练的语音自动编码模型,解码器可以是任何预训练的文本自回归模型。编码器通过from_pretrained()函数加载,解码器也通过from_pretrained()函数加载。交叉注意力层会自动添加到解码器中,并且应该在生成任务(如摘要生成)上进行微调。

使用预训练检查点初始化序列到序列模型在序列生成任务中的有效性在Leveraging Pre-trained Checkpoints for Sequence Generation Tasks中由Sascha Rothe、Shashi Narayan、Aliaksei Severyn、Michael Matena、Yanqi Zhou、Wei Li和Peter J. Liu展示。

此外,在大规模自监督和半监督学习用于语音翻译中展示了如何利用大规模预训练语音模型进行语音翻译,从而显著提高性能。

在训练/微调这样的Speech-Encoder Decoder模型之后,它可以像其他模型一样保存/加载(更多信息请参见示例)。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

SpeechEncoderDecoderModel 是一个通用模型类,当使用 :meth~transformers.AutoModel.from_pretrained 类方法创建编码器和使用 :meth~transformers.AutoModelForCausalLM.from_pretrained 类方法创建解码器时,它将作为一个具有库中基础模型类之一的编码器和另一个作为解码器的变压器架构实例化。

前进

< >

( inputs: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None encoder_outputs: typing.Optional[typing.Tuple[torch.FloatTensor]] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None input_values: typing.Optional[torch.FloatTensor] = None input_features: typing.Optional[torch.FloatTensor] = None return_dict: typing.Optional[bool] = None **kwargs ) transformers.modeling_outputs.Seq2SeqLMOutputtuple(torch.FloatTensor)

参数

  • 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 or 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.

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用PreTrainedTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

    如果使用了past_key_values,则可以选择性地仅输入最后一个decoder_input_ids(参见past_key_values)。

    在训练过程中,decoder_input_ids 由模型自动生成,通过将 labels 向右移动,用 pad_token_id 替换 -100,并在前面加上 decoder_start_token_id

  • decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), optional) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。
  • encoder_outputs (tuple(torch.FloatTensor), optional) — 这个元组必须包含 (last_hidden_state, optional: hidden_states, optional: attentions) last_hidden_state (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size)) 是一个张量, 表示编码器最后一层的隐藏状态输出。用于解码器的交叉注意力机制中。
  • 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.

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后一个decoder_input_ids(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)的所有decoder_input_ids

  • inputs_embeds (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • decoder_inputs_embeds (torch.FloatTensor 形状为 (batch_size, target_sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 decoder_input_ids。如果您希望对如何将 decoder_input_ids 索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于计算解码器的掩码语言建模损失的标签。索引应在 [-100, 0, ..., config.vocab_size] 范围内(参见 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略 (掩码),损失仅针对标签在 [0, ..., config.vocab_size] 范围内的标记计算
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • input_values (torch.FloatTensor of shape (batch_size, sequence_length), optional) — 输入原始语音波形的浮点数值。可以通过将.flac.wav音频文件加载到List[float]类型的数组或numpy.ndarray中获取这些值,例如通过soundfile库(pip install soundfile)。要将数组准备为input_values,应使用Wav2Vec2Processor进行填充并转换为torch.FloatTensor类型的张量。详情请参见Wav2Vec2Processor.call()
  • 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 type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the Speech2TextFeatureExtractor should be used for extracting the fbank features, padding and conversion into a tensor of type torch.FloatTensor. See call()
  • return_dict (bool, 可选) — 如果设置为 True,模型将返回一个 ~utils.Seq2SeqLMOutput 而不是一个普通的元组。
  • kwargs (可选) — 剩余的关键字参数字典。关键字参数有两种形式:
    • 没有前缀的将作为编码器前向函数的**encoder_kwargs输入。
    • 带有decoder_前缀的将作为解码器前向函数的**decoder_kwargs输入。

返回

transformers.modeling_outputs.Seq2SeqLMOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.Seq2SeqLMOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(SpeechEncoderDecoderConfig)和输入。

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 语言建模损失。

  • logits (torch.FloatTensor 形状为 (batch_size, sequence_length, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。

  • past_key_values (tuple(tuple(torch.FloatTensor))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(torch.FloatTensor) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量和 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的额外张量。

    包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • decoder_hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    解码器在每层输出处的隐藏状态加上初始嵌入输出。

  • decoder_attentions (tuple(torch.FloatTensor)可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

  • cross_attentions (tuple(torch.FloatTensor)可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

  • encoder_last_hidden_state (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size)可选) — 模型编码器最后一层输出的隐藏状态序列。

  • encoder_hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    编码器在每层输出处的隐藏状态加上初始嵌入输出。

  • encoder_attentions (tuple(torch.FloatTensor)可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

SpeechEncoderDecoderModel 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import SpeechEncoderDecoderModel, AutoProcessor
>>> from datasets import load_dataset
>>> import torch

>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-xls-r-300m-en-to-15")
>>> model = SpeechEncoderDecoderModel.from_pretrained("facebook/wav2vec2-xls-r-300m-en-to-15")

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

>>> input_values = processor(ds[0]["audio"]["array"], return_tensors="pt").input_values
>>> # Inference: Translate English speech to German
>>> generated = model.generate(input_values)
>>> decoded = processor.batch_decode(generated, skip_special_tokens=True)[0]
>>> decoded
'Mr. Quilter ist der Apostel der Mittelschicht und wir freuen uns, sein Evangelium willkommen heißen zu können.'

>>> # Training: Train model on English transcription
>>> labels = processor(text=ds[0]["text"], return_tensors="pt").input_ids

>>> loss = model(input_values, labels=labels).loss
>>> loss.backward()

from_encoder_decoder_pretrained

< >

( encoder_pretrained_model_name_or_path: str = None decoder_pretrained_model_name_or_path: str = None *model_args **kwargs )

参数

  • 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.
    • 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 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.
    • 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 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 (剩余的位置参数, 可选) — 所有剩余的位置参数将被传递给底层模型的 __init__ 方法.
  • 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.

    根据是否提供了config或自动加载而表现不同。

从一个或多个库的基类实例化编码器和解码器,使用预训练模型的检查点。

模型默认使用model.eval()设置为评估模式(Dropout模块被停用)。要训练模型,你需要首先使用model.train()将其重新设置为训练模式。

示例:

>>> 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", "google-bert/bert-base-uncased"
... )
>>> # saving model after fine-tuning
>>> model.save_pretrained("./wav2vec2bert")
>>> # load fine-tuned model
>>> model = SpeechEncoderDecoderModel.from_pretrained("./wav2vec2bert")

FlaxSpeechEncoderDecoderModel

transformers.FlaxSpeechEncoderDecoderModel

< >

( config: SpeechEncoderDecoderConfig input_shape: typing.Optional[typing.Tuple] = None seed: int = 0 dtype: dtype = _do_init: bool = True **kwargs )

参数

  • config (SpeechEncoderDecoderConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs).

    这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的dtype执行。

    请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。

    如果您希望更改模型参数的dtype,请参阅to_fp16()to_bf16().

该类可用于初始化一个语音序列到文本序列的模型,其中编码器可以是任何预训练的语音自动编码模型,解码器可以是任何预训练的文本自回归模型。编码器通过from_pretrained()函数加载,解码器也通过from_pretrained()函数加载。交叉注意力层会自动添加到解码器中,并且应该在生成任务(如摘要生成)上进行微调。

使用预训练检查点初始化序列到序列模型在序列生成任务中的有效性在Leveraging Pre-trained Checkpoints for Sequence Generation Tasks中由Sascha Rothe、Shashi Narayan、Aliaksei Severyn、Michael Matena、Yanqi Zhou、Wei Li和Peter J. Liu展示。

此外,在大规模自监督和半监督学习用于语音翻译中展示了如何利用大规模预训练语音模型进行语音翻译,从而显著提高性能。

在训练/微调这样的Speech-Encoder Decoder模型之后,它可以像其他模型一样保存/加载(更多信息请参见示例)。

该模型继承自FlaxPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头等)。

该模型也是一个Flax Linen flax.nn.Module 子类。将其作为常规的Flax模块使用,并参考Flax文档以获取与一般用法和行为相关的所有信息。

FlaxSpeechEncoderDecoderModel 是一个通用模型类,当使用 :meth~transformers.FlaxAutoModel.from_pretrained 类方法创建编码器和使用 :meth~transformers.FlaxAutoModelForCausalLM.from_pretrained 类方法创建解码器时,它将作为变压器架构实例化,其中编码器模块是库中一个基础模型类的模块(flax.nn.Module),解码器模块是另一个基础模型类的模块。

__call__

< >

( inputs: 数组 attention_mask: 可选的[jax.Array] = 无 decoder_input_ids: 可选的[jax.Array] = 无 decoder_attention_mask: 可选的[jax.Array] = 无 decoder_position_ids: 可选的[jax.Array] = 无 output_attentions: 可选的[bool] = 无 output_hidden_states: 可选的[bool] = 无 return_dict: 可选的[bool] = 无 train: bool = 假 freeze_feature_encoder: bool = 假 params: 字典 = 无 dropout_rng: = 无 ) transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutputtuple(torch.FloatTensor)

参数

  • 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 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 or Speech2TextProcessor should be used for padding and conversion into a tensor of type torch.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.

    可以使用PreTrainedTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

    如果使用了past_key_values,则可以选择性地仅输入最后一个decoder_input_ids(参见past_key_values)。

    对于序列到序列的训练,应该提供decoder_input_idsdecoder_input_ids应该在模型外部通过将labels向右移动,用pad_token_id替换-100,并在前面加上decoder_start_token_id来创建。

  • decoder_attention_mask (jnp.ndarray of shape (batch_size, target_sequence_length), optional) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。
  • decoder_position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — 每个解码器输入序列标记在位置嵌入中的位置索引。选择范围在 [0, config.decoder.max_position_embeddings - 1] 之间。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 如果设置为 True,模型将返回一个 ~utils.FlaxSeq2SeqLMOutput 而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutputtuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(SpeechEncoderDecoderConfig)和输入。

  • logits (jnp.ndarray 形状为 (batch_size, sequence_length, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。

  • past_key_values (tuple(tuple(jnp.ndarray)), 可选, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(jnp.ndarray) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量和 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的额外张量。

    包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • decoder_hidden_states (tuple(jnp.ndarray), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入的输出 + 一个用于每层的输出)。

    解码器在每层输出处的隐藏状态加上初始嵌入输出。

  • decoder_attentions (tuple(jnp.ndarray), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

    解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

  • cross_attentions (tuple(jnp.ndarray), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

  • encoder_last_hidden_state (jnp.ndarray 形状为 (batch_size, sequence_length, hidden_size), 可选) — 模型编码器最后一层输出的隐藏状态序列。

  • encoder_hidden_states (tuple(jnp.ndarray), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入的输出 + 一个用于每层的输出)。

    编码器在每层输出处的隐藏状态加上初始嵌入输出。

  • encoder_attentions (tuple(jnp.ndarray), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

    编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

FlaxSpeechEncoderDecoderModel 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import FlaxSpeechEncoderDecoderModel, AutoTokenizer

>>> # load a fine-tuned wav2vec2-2-bart model
>>> model = FlaxSpeechEncoderDecoderModel.from_pretrained("patrickvonplaten/wav2vec2-2-bart-large")
>>> # load output tokenizer
>>> tokenizer_output = AutoTokenizer.from_pretrained("facebook/bart-large")

>>> inputs = jnp.ones((2, 5000), dtype=jnp.float32)

>>> # use bart's special bos, pad and eos tokens
>>> model.config.decoder_start_token_id = model.decoder.config.bos_token_id
>>> model.config.pad_token_id = model.decoder.config.pad_token_id
>>> model.config.eos_token_id = model.decoder.config.eos_token_id

>>> outputs = model.generate(inputs)
# Assert something? More interesting input? dtype correct?

from_encoder_decoder_pretrained

< >

( encoder_pretrained_model_name_or_path: typing.Union[str, os.PathLike, NoneType] = None decoder_pretrained_model_name_or_path: typing.Union[str, os.PathLike, NoneType] = None *model_args **kwargs )

参数

  • encoder_pretrained_model_name_or_path (Union[str, os.PathLike], 可选) — 初始化编码器所需的信息。可以是以下之一:
    • 一个字符串,表示托管在huggingface.co上的模型仓库中的预训练模型的模型ID
    • 一个路径,指向使用save_pretrained()保存的模型权重的目录,例如./my_model_directory/
  • decoder_pretrained_model_name_or_path (Union[str, os.PathLike], 可选, 默认为 None) — 初始化解码器所需的信息。可以是以下之一:
    • 一个字符串,表示托管在 huggingface.co 上的模型仓库中的预训练模型的 模型 id
    • 一个路径,指向使用 save_pretrained() 保存的模型权重的 目录,例如 ./my_model_directory/
  • model_args (剩余的位置参数, 可选) — 所有剩余的位置参数将传递给底层模型的 __init__ 方法.
  • 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.

    根据是否提供了config或自动加载而表现不同。

从一个或多个库的基类实例化编码器和解码器,使用预训练模型的检查点。

示例:

>>> from transformers import FlaxSpeechEncoderDecoderModel

>>> # initialize a wav2vec2-2-bart from pretrained wav2vec2 and bart models. Note that the cross-attention layers will be randomly initialized
>>> model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(
...     "facebook/wav2vec2-large-lv60", "facebook/bart-large"
... )
>>> # saving model after fine-tuning
>>> model.save_pretrained("./wav2vec2-2-bart-large")
>>> # load fine-tuned model
>>> model = FlaxSpeechEncoderDecoderModel.from_pretrained("./wav2vec2-2-bart-large")
< > Update on GitHub