Transformers 文档

无缝M4T

无缝M4T

概述

SeamlessM4T模型由Meta AI的Seamless Communication团队在SeamlessM4T — 大规模多语言和多模态机器翻译中提出。

这是模型的版本1发布。有关更新的版本2发布,请参阅Seamless M4T v2 文档

SeamlessM4T 是一组旨在提供高质量翻译的模型,使来自不同语言社区的人们能够通过语音和文本轻松交流。

SeamlessM4T 支持多种任务,无需依赖单独的模型:

  • 语音到语音翻译 (S2ST)
  • 语音到文本翻译 (S2TT)
  • 文本到语音翻译 (T2ST)
  • 文本到文本翻译 (T2TT)
  • 自动语音识别 (ASR)

SeamlessM4TModel 可以执行上述所有任务,但每个任务也有其专用的子模型。

论文的摘要如下:

创建一个能够帮助个人在任何两种语言之间进行语音翻译的工具——巴别鱼,需要什么条件?尽管最近基于文本的模型的突破已经将机器翻译的覆盖范围推到了200多种语言,但统一的语音到语音翻译模型尚未取得类似的进展。更具体地说,传统的语音到语音翻译系统依赖于逐步执行翻译的级联系统,这使得高性能的统一系统难以实现。为了解决这些差距,我们引入了SeamlessM4T,这是一个支持语音到语音翻译、语音到文本翻译、文本到语音翻译、文本到文本翻译以及多达100种语言的自动语音识别的单一模型。为了构建这个模型,我们使用了100万小时的开放语音音频数据,通过w2v-BERT 2.0学习自监督的语音表示。随后,我们创建了一个自动对齐的语音翻译多模态语料库。通过过滤并结合人工标注和伪标注数据,我们开发了第一个能够从英语和向英语进行语音和文本翻译的多语言系统。在FLEURS上,SeamlessM4T为翻译到多种目标语言设定了新的标准,在直接语音到文本翻译中比之前的SOTA提高了20%的BLEU分数。与强大的级联模型相比,SeamlessM4T在语音到文本翻译中的英语翻译质量提高了1.3个BLEU分数,在语音到语音翻译中提高了2.6个ASR-BLEU分数。在鲁棒性测试中,与当前的SOTA模型相比,我们的系统在语音到文本任务中对背景噪音和说话者变化的处理表现更好。重要的是,我们评估了SeamlessM4T在性别偏见和添加毒性方面的表现,以评估翻译的安全性。最后,本工作的所有贡献都已开源,并可在https://github.com/facebookresearch/seamless_communication访问。

用法

首先,加载处理器和模型的检查点:

>>> from transformers import AutoProcessor, SeamlessM4TModel

>>> processor = AutoProcessor.from_pretrained("facebook/hf-seamless-m4t-medium")
>>> model = SeamlessM4TModel.from_pretrained("facebook/hf-seamless-m4t-medium")

您可以无缝地在文本或音频上使用此模型,以生成翻译后的文本或翻译后的音频。

以下是使用处理器处理文本和音频的方法:

>>> # let's load an audio sample from an Arabic speech corpus
>>> from datasets import load_dataset
>>> dataset = load_dataset("arabic_speech_corpus", split="test", streaming=True)
>>> audio_sample = next(iter(dataset))["audio"]

>>> # now, process it
>>> audio_inputs = processor(audios=audio_sample["array"], return_tensors="pt")

>>> # now, process some English test as well
>>> text_inputs = processor(text = "Hello, my dog is cute", src_lang="eng", return_tensors="pt")

语音

SeamlessM4TModel 可以无缝地生成文本或语音,几乎不需要或不需要任何更改。让我们以俄语语音翻译为目标:

>>> audio_array_from_text = model.generate(**text_inputs, tgt_lang="rus")[0].cpu().numpy().squeeze()
>>> audio_array_from_audio = model.generate(**audio_inputs, tgt_lang="rus")[0].cpu().numpy().squeeze()

使用基本相同的代码,我已经将英文文本和阿拉伯语语音翻译成了俄语语音样本。

文本

同样地,您可以使用相同的模型从音频文件或文本生成翻译文本。您只需将generate_speech=False传递给SeamlessM4TModel.generate()。 这次,让我们翻译成法语。

>>> # from audio
>>> output_tokens = model.generate(**audio_inputs, tgt_lang="fra", generate_speech=False)
>>> translated_text_from_audio = processor.decode(output_tokens[0].tolist()[0], skip_special_tokens=True)

>>> # from text
>>> output_tokens = model.generate(**text_inputs, tgt_lang="fra", generate_speech=False)
>>> translated_text_from_text = processor.decode(output_tokens[0].tolist()[0], skip_special_tokens=True)

提示

1. 使用专用模型

SeamlessM4TModel 是 transformers 的顶级模型,用于生成语音和文本,但你也可以使用专门的模型来执行任务,而无需额外的组件,从而减少内存占用。 例如,你可以用专门用于 S2ST 任务的模型替换音频到音频生成的代码片段,其余部分是完全相同的代码:

>>> from transformers import SeamlessM4TForSpeechToSpeech
>>> model = SeamlessM4TForSpeechToSpeech.from_pretrained("facebook/hf-seamless-m4t-medium")

或者你可以将文本到文本生成的代码片段替换为专门用于T2TT任务的模型,你只需要移除generate_speech=False

>>> from transformers import SeamlessM4TForTextToText
>>> model = SeamlessM4TForTextToText.from_pretrained("facebook/hf-seamless-m4t-medium")

请随意尝试 SeamlessM4TForSpeechToTextSeamlessM4TForTextToSpeech

2. 更改说话者身份

您可以使用spkr_id参数来更改用于语音合成的扬声器。对于某些语言,某些spkr_id比其他spkr_id效果更好!

3. 更改生成策略

您可以使用不同的生成策略进行语音和文本生成,例如.generate(input_ids=input_ids, text_num_beams=4, speech_do_sample=True),这将在文本模型上依次执行束搜索解码,并在语音模型上执行多项式采样。

4. 同时生成语音和文本

使用 return_intermediate_token_ids=TrueSeamlessM4TModel 一起返回语音和文本!

模型架构

SeamlessM4T 具有一个多功能架构,能够流畅地处理文本和语音的顺序生成。该设置包括两个序列到序列(seq2seq)模型。第一个模型将输入模态转换为翻译后的文本,而第二个模型从翻译后的文本生成语音标记,称为“单元标记”。

每种模态都有其专用的编码器,具有独特的架构。此外,对于语音输出,一个受HiFi-GAN架构启发的声码器被放置在第二个seq2seq模型的顶部。

以下是生成过程的工作原理:

  • 输入的文本或语音通过其特定的编码器进行处理。
  • 解码器生成所需语言的文本标记。
  • 如果需要生成语音,第二个seq2seq模型,遵循标准的编码器-解码器结构,生成单元标记。
  • 这些单元标记随后通过最终的声码器生成实际的语音。

该模型由ylacombe贡献。原始代码可以在这里找到。

SeamlessM4TModel

transformers.SeamlessM4TModel

< >

( config current_modality = 'text' )

参数

  • config (~SeamlessM4TConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
  • current_modality (str, 可选, 默认为 "text") — 默认模态。用于初始化模型。

原始的SeamlessM4T模型转换器,可用于所有可用任务(S2ST、S2TT、T2TT、T2ST)。 该模型是PyTorch torch.nn.Module的子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

生成

< >

( input_ids: typing.Optional[torch.Tensor] = None input_features: typing.Optional[torch.Tensor] = None return_intermediate_token_ids: typing.Optional[bool] = None tgt_lang: typing.Optional[str] = None spkr_id: typing.Optional[int] = 0 generate_speech: typing.Optional[bool] = True **kwargs ) Union[SeamlessM4TGenerationOutput, Tuple[Tensor], ModelOutput]

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary.

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

    什么是输入ID?

  • input_features (torch.FloatTensor of shape (batch_size, sequence_length, num_banks), optional) — 输入音频特征。这应该由SeamlessM4TFeatureExtractor类或SeamlessM4TProcessor类返回。详情请参见SeamlessM4TFeatureExtractor.call().
  • return_intermediate_token_ids (bool, 可选) — 如果为 True,还会返回中间生成的文本和单元标记。如果你还想要在音频旁边获取翻译文本,请设置为 True。请注意,如果 generate_speech=True,此参数将被忽略。
  • tgt_lang (str, optional) — 用于翻译的目标语言。
  • spkr_id (int, 可选, 默认为 0) — 用于语音合成的说话者ID。必须小于 config.vocoder_num_spkrs.
  • generate_speech (bool, 可选, 默认为 True) — 如果为 False,将只返回文本标记,不会生成语音。
  • kwargs (optional) — Remaining dictionary of keyword arguments that will be passed to GenerationMixin.generate(). Keyword arguments are of two types:
    • Without a prefix, they will be entered as **kwargs for the generate method of each sub-model, except for decoder_input_ids which will only be passed through the text components.
    • With a text_ or speech_ prefix, they will be input for the generate method of the text model and speech model respectively. It has the priority over the keywords without a prefix.

    这意味着你可以,例如,为一个生成指定生成策略,而不为另一个生成指定策略。

返回

Union[SeamlessM4TGenerationOutput, Tuple[Tensor], ModelOutput]

  • 如果 generate_speechreturn_intermediate_token_ids,返回 SeamlessM4TGenerationOutput
  • 如果 generate_speech 且不 return_intermediate_token_ids,返回一个由波形组成的元组,形状为 (batch_size, sequence_length)waveform_lengths,它给出了每个样本的长度。
  • 如果 generate_speech=False,它将返回 ModelOutput

生成翻译后的令牌ID和/或翻译后的音频波形。

此方法依次调用两个不同子模型的.generate函数。您可以在两个不同的级别指定关键字参数:将传递给两个模型的通用参数,或仅传递给其中一个模型的前缀参数。

例如,调用 .generate(input_ids=input_ids, num_beams=4, speech_do_sample=True) 将会依次在文本模型上执行束搜索解码,并在语音模型上执行多项式束搜索采样。

有关生成策略和代码示例的概述,请查看以下指南

无缝M4T文本转语音

class transformers.SeamlessM4TForTextToSpeech

< >

( config: SeamlessM4TConfig )

参数

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

用于T2ST的文本到语音SeamlessM4T模型转换器。 该模型是PyTorch torch.nn.Module的子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

生成

< >

( input_ids: typing.Optional[torch.Tensor] = None return_intermediate_token_ids: typing.Optional[bool] = None tgt_lang: typing.Optional[str] = None spkr_id: typing.Optional[int] = 0 **kwargs ) Union[SeamlessM4TGenerationOutput, Tuple[Tensor]]

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

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

    什么是输入ID?

  • return_intermediate_token_ids (bool, 可选) — 如果设置为 True,还会返回中间生成的文本和单元标记。如果你希望在获取音频的同时也得到翻译的文本,请设置为 True
  • tgt_lang (str, optional) — 用作翻译目标语言的语言。
  • spkr_id (int, 可选, 默认为 0) — 用于语音合成的说话者ID。必须小于 config.vocoder_num_spkrs.
  • kwargs (optional) — Remaining dictionary of keyword arguments that will be passed to GenerationMixin.generate(). Keyword arguments are of two types:
    • Without a prefix, they will be entered as **kwargs for the generate method of each sub-model, except for decoder_input_ids which will only be passed through the text components.
    • With a text_ or speech_ prefix, they will be input for the generate method of the text model and speech model respectively. It has the priority over the keywords without a prefix.

    这意味着你可以,例如,为一个生成指定生成策略,而不为另一个生成指定策略。

返回

Union[SeamlessM4TGenerationOutput, Tuple[Tensor]]

  • 如果 return_intermediate_token_ids,返回 SeamlessM4TGenerationOutput
  • 如果不是 return_intermediate_token_ids,返回一个由形状为 (batch_size, sequence_length) 的波形和 waveform_lengths 组成的元组,其中 waveform_lengths 给出每个样本的长度。

生成翻译后的音频波形。

此方法依次调用两个不同子模型的.generate函数。您可以在两个不同的级别指定关键字参数:将传递给两个模型的通用参数,或仅传递给其中一个模型的前缀参数。

例如,调用 .generate(input_ids, num_beams=4, speech_do_sample=True) 将依次在文本模型上执行束搜索解码,并在语音模型上执行多项式束搜索采样。

有关生成策略和代码示例的概述,请查看以下指南

无缝M4T语音转语音

class transformers.SeamlessM4TForSpeechToSpeech

< >

( config )

参数

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

用于语音到语音转换的SeamlessM4T模型转换器,可用于S2ST。 该模型是PyTorch torch.nn.Module 的子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

生成

< >

( input_features: typing.Optional[torch.Tensor] = None return_intermediate_token_ids: typing.Optional[bool] = None tgt_lang: typing.Optional[str] = None spkr_id: typing.Optional[int] = 0 **kwargs ) Union[SeamlessM4TGenerationOutput, Tuple[Tensor]]

参数

  • input_features (torch.FloatTensor of shape (batch_size, sequence_length, num_banks)) — 输入音频特征。这应该由SeamlessM4TFeatureExtractor类或SeamlessM4TProcessor类返回。详情请参见SeamlessM4TFeatureExtractor.call().
  • return_intermediate_token_ids (bool, optional) — 如果为 True,还会返回中间生成的文本和单元标记。如果您还想要 在音频旁边获取翻译后的文本,请设置为 True
  • tgt_lang (str, optional) — 用作翻译目标语言的语言。
  • spkr_id (int, optional, 默认为 0) — 用于语音合成的说话者ID。必须小于 config.vocoder_num_spkrs.
  • kwargs (optional) — Remaining dictionary of keyword arguments that will be passed to GenerationMixin.generate(). Keyword arguments are of two types:
    • Without a prefix, they will be entered as **kwargs for the generate method of each sub-model, except for decoder_input_ids which will only be passed through the text components.
    • With a text_ or speech_ prefix, they will be input for the generate method of the text model and speech model respectively. It has the priority over the keywords without a prefix.

    这意味着你可以,例如,为一个生成指定生成策略,而不为另一个生成指定策略。

返回

Union[SeamlessM4TGenerationOutput, Tuple[Tensor]]

  • 如果 return_intermediate_token_ids,返回 SeamlessM4TGenerationOutput
  • 如果不是 return_intermediate_token_ids,返回一个由形状为 (batch_size, sequence_length) 的波形和 waveform_lengths 组成的元组,其中 waveform_lengths 给出每个样本的长度。

生成翻译后的音频波形。

此方法依次调用两个不同子模型的.generate函数。您可以在两个不同的级别指定关键字参数:将传递给两个模型的通用参数,或仅传递给其中一个模型的前缀参数。

例如,调用 .generate(input_features, num_beams=4, speech_do_sample=True) 将依次在文本模型上执行束搜索解码,并在语音模型上执行多项式束搜索采样。

有关生成策略和代码示例的概述,请查看以下指南

SeamlessM4TForTextToText

class transformers.SeamlessM4TForTextToText

< >

( config: SeamlessM4TConfig )

参数

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

文本到文本的SeamlessM4T模型转换器,可用于T2TT。 该模型是PyTorch torch.nn.Module 的子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以了解与一般使用和行为相关的所有事项。

前进

< >

( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None inputs_embeds: typing.Optional[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 return_dict: typing.Optional[bool] = None **kwargs )

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary.

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

    什么是输入ID?

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

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

    什么是解码器输入ID?

    Bart 使用 eos_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择只输入最后一个 decoder_input_ids(参见 past_key_values)。

    对于翻译和摘要训练,应提供decoder_input_ids。如果没有提供decoder_input_ids,模型将根据论文中的去噪预训练方法,通过将input_ids向右移动来创建此张量。

  • decoder_attention_mask (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

    如果你想改变填充行为,你应该阅读modeling_bart._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

  • encoder_outputs (tuple(tuple(torch.FloatTensor), 可选的) — 元组由 (last_hidden_state, 可选的: hidden_states, 可选的: attentions) last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选的) 是编码器最后一层的输出隐藏状态序列。用于解码器的交叉注意力中。
  • past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head).

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

    如果使用了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 of shape (batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

    如果decoder_input_idsdecoder_inputs_embeds都未设置,decoder_inputs_embeds将取inputs_embeds的值。

  • 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
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

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

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

生成

< >

( input_ids = None tgt_lang = None generation_config = None logits_processor = None stopping_criteria = None prefix_allowed_tokens_fn = None synced_gpus = False **kwargs ) ModelOutputtorch.LongTensor

参数

  • input_ids (torch.Tensor of varying shape depending on the modality, optional) — Indices of input sequence tokens in the vocabulary.

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

    什么是输入ID?

  • tgt_lang (str, optional) — 用作翻译目标语言的语言。
  • generation_config (~generation.GenerationConfig, optional) — The generation configuration to be used as base parametrization for the generation call. **kwargs passed to generate matching the attributes of generation_config will override them. If generation_config is not provided, the default will be used, which had the following loading priority: 1) from the generation_config.json model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit GenerationConfig’s default values, whose documentation should be checked to parameterize generation.
  • logits_processor (LogitsProcessorList, 可选) — 自定义的logits处理器,用于补充从参数和生成配置中构建的默认logits处理器。如果传递了一个已经通过参数或生成配置创建的logit处理器,则会抛出错误。此功能面向高级用户。
  • stopping_criteria (StoppingCriteriaList, 可选) — 自定义的停止标准,用于补充从参数和生成配置中构建的默认停止标准。如果传递的停止标准已经由参数或生成配置创建,则会抛出错误。此功能面向高级用户。
  • prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], List[int]], 可选) — 如果提供,此函数将约束束搜索,使其在每一步仅允许特定的令牌。如果未提供,则不应用任何约束。此函数接受2个参数:批次ID batch_idinput_ids。它必须返回一个列表,其中包含根据批次ID batch_id 和先前生成的令牌 inputs_ids 条件允许的下一生成步骤的令牌。此参数对于基于前缀的条件生成非常有用,如自回归实体检索中所述。
  • synced_gpus (bool, 可选, 默认为 False) — 是否继续运行while循环直到达到max_length(需要避免与 FullyShardedDataParallel 和 DeepSpeed ZeRO Stage 3 发生死锁)。
  • kwargs (Dict[str, Any], 可选) — generate_config 的临时参数化和/或额外的模型特定 kwargs,这些参数将被转发到模型的 forward 函数中。

返回

ModelOutputtorch.LongTensor

一个 ModelOutput(如果 return_dict_in_generate=True 或当 config.return_dict_in_generate=True)或一个 torch.FloatTensor。可能的 ModelOutput 类型有:

生成令牌ID的序列。

大多数生成控制参数都在generation_config中设置,如果没有传递,将设置为模型的默认生成配置。您可以通过将相应的参数传递给generate()来覆盖任何generation_config,例如.generate(inputs, num_beams=4, do_sample=True)

有关生成策略和代码示例的概述,请查看以下指南

SeamlessM4TForSpeechToText

class transformers.SeamlessM4TForSpeechToText

< >

( config: SeamlessM4TConfig )

参数

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

用于语音转文本的SeamlessM4T模型转换器,可用于S2TT。 该模型是PyTorch torch.nn.Module的子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_features: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None inputs_embeds: typing.Optional[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 return_dict: typing.Optional[bool] = None **kwargs )

参数

  • input_features (torch.FloatTensor of shape (batch_size, sequence_length, num_banks)) — 输入音频特征。这应该由SeamlessM4TFeatureExtractor类或SeamlessM4TProcessor类返回。详情请参见SeamlessM4TFeatureExtractor.call().
  • 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.

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

    什么是解码器输入ID?

    Bart 使用 eos_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择只输入最后一个 decoder_input_ids(参见 past_key_values)。

    对于翻译和摘要训练,应提供decoder_input_ids。如果没有提供decoder_input_ids,模型将根据论文中的去噪预训练方法,通过将input_ids向右移动来创建此张量。

  • decoder_attention_mask (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

    如果你想改变填充行为,你应该阅读modeling_bart._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

  • encoder_outputs (tuple(tuple(torch.FloatTensor), 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力机制中。
  • past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head).

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

    如果使用了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 of shape (batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

    如果decoder_input_idsdecoder_inputs_embeds都未设置,decoder_inputs_embeds将取inputs_embeds的值。

  • 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, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

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

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

生成

< >

( input_features = None tgt_lang = None generation_config = None logits_processor = None stopping_criteria = None prefix_allowed_tokens_fn = None synced_gpus = False **kwargs ) ModelOutputtorch.LongTensor

参数

  • input_features (torch.FloatTensor of shape (batch_size, sequence_length, num_banks)) — 输入音频特征。这应该由SeamlessM4TFeatureExtractor类或SeamlessM4TProcessor类返回。详情请参见SeamlessM4TFeatureExtractor.call().
  • tgt_lang (str, optional) — 用于翻译的目标语言。
  • generation_config (~generation.GenerationConfig, optional) — The generation configuration to be used as base parametrization for the generation call. **kwargs passed to generate matching the attributes of generation_config will override them. If generation_config is not provided, the default will be used, which had the following loading priority: 1) from the generation_config.json model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit GenerationConfig’s default values, whose documentation should be checked to parameterize generation.
  • logits_processor (LogitsProcessorList, 可选) — 自定义的logits处理器,用于补充从参数和生成配置中构建的默认logits处理器。如果传递了一个已经通过参数或生成配置创建的logit处理器,则会抛出错误。此功能面向高级用户。
  • stopping_criteria (StoppingCriteriaList, 可选) — 自定义的停止标准,用于补充从参数和生成配置中构建的默认停止标准。如果传递的停止标准已经由参数或生成配置创建,则会抛出错误。此功能面向高级用户。
  • prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], List[int]], 可选) — 如果提供,此函数将约束束搜索,使其在每一步仅允许特定的令牌。如果未提供,则不应用任何约束。此函数接受2个参数:批次ID batch_idinput_ids。它必须返回一个列表,其中包含根据批次ID batch_id 和先前生成的令牌 inputs_ids 条件允许的下一生成步骤的令牌。此参数对于基于前缀的条件生成非常有用,如自回归实体检索中所述。
  • synced_gpus (bool, 可选, 默认为 False) — 是否继续运行 while 循环直到达到 max_length(需要避免与 FullyShardedDataParallel 和 DeepSpeed ZeRO Stage 3 发生死锁)。
  • kwargs (Dict[str, Any], 可选) — generate_config 的临时参数化和/或额外的模型特定 kwargs,这些参数将被转发到模型的 forward 函数中。

返回

ModelOutputtorch.LongTensor

一个 ModelOutput(如果 return_dict_in_generate=True 或当 config.return_dict_in_generate=True)或一个 torch.FloatTensor。可能的 ModelOutput 类型有:

生成令牌ID的序列。

大多数生成控制参数都在generation_config中设置,如果没有传递,将设置为模型的默认生成配置。您可以通过将相应的参数传递给generate()来覆盖任何generation_config,例如.generate(inputs, num_beams=4, do_sample=True)

有关生成策略和代码示例的概述,请查看以下指南

SeamlessM4TConfig

transformers.SeamlessM4TConfig

< >

( vocab_size = 256102 t2u_vocab_size = 10082 hidden_size = 1024 initializer_range = 0.02 layer_norm_eps = 1e-05 use_cache = True max_position_embeddings = 1024 is_encoder_decoder = True encoder_layerdrop = 0.05 decoder_layerdrop = 0.05 activation_function = 'relu' dropout = 0.1 attention_dropout = 0.1 activation_dropout = 0.0 scale_embedding = True encoder_layers = 24 encoder_ffn_dim = 8192 encoder_attention_heads = 16 decoder_layers = 24 decoder_ffn_dim = 8192 decoder_attention_heads = 16 decoder_start_token_id = 3 max_new_tokens = 256 pad_token_id = 0 bos_token_id = 2 eos_token_id = 3 speech_encoder_layers = 24 speech_encoder_attention_heads = 16 speech_encoder_intermediate_size = 4096 speech_encoder_hidden_act = 'swish' speech_encoder_dropout = 0.0 add_adapter = True speech_encoder_layerdrop = 0.1 feature_projection_input_dim = 160 num_conv_pos_embeddings = 128 num_conv_pos_embedding_groups = 16 adaptor_kernel_size = 8 adaptor_stride = 8 adaptor_dropout = 0.1 num_adapter_layers = 1 position_embeddings_type = 'relative' rotary_embedding_base = 10000 max_source_positions = 4096 conv_depthwise_kernel_size = 31 t2u_bos_token_id = 0 t2u_pad_token_id = 1 t2u_eos_token_id = 2 t2u_decoder_start_token_id = 2 t2u_max_new_tokens = 1024 t2u_encoder_layers = 6 t2u_encoder_ffn_dim = 8192 t2u_encoder_attention_heads = 16 t2u_decoder_layers = 6 t2u_decoder_ffn_dim = 8192 t2u_decoder_attention_heads = 16 t2u_max_position_embeddings = 2048 sampling_rate = 16000 upsample_initial_channel = 512 upsample_rates = [5, 4, 4, 2, 2] upsample_kernel_sizes = [11, 8, 8, 4, 4] resblock_kernel_sizes = [3, 7, 11] resblock_dilation_sizes = [[1, 3, 5], [1, 3, 5], [1, 3, 5]] leaky_relu_slope = 0.1 unit_hifi_gan_vocab_size = 10000 unit_embed_dim = 1280 lang_embed_dim = 256 spkr_embed_dim = 256 vocoder_num_langs = 36 vocoder_num_spkrs = 200 variance_predictor_kernel_size = 3 var_pred_dropout = 0.5 vocoder_offset = 4 **kwargs )

参数

跨子模型共享的参数

  • hidden_size (int, optional, defaults to 1024) — 架构中“中间”层的维度。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • layer_norm_eps (float, optional, defaults to 1e-05) — 层归一化层使用的epsilon值。
  • use_cache (bool, 可选, 默认为 True) — 模型是否应返回最后的键/值注意力(并非所有模型都使用)。
  • max_position_embeddings (int, optional, 默认为 1024) — 此模型文本编码器和解码器可能使用的最大序列长度。通常将其设置为较大的值以防万一(例如,512 或 1024 或 2048)。
  • is_encoder_decoder (bool, optional, defaults to True) — 模型是否用作编码器/解码器。
  • encoder_layerdrop (float, optional, 默认为 0.05) — 编码器的LayerDrop概率。更多详情请参阅 [LayerDrop 论文](see https://arxiv.org/abs/1909.11556)。
  • decoder_layerdrop (float, optional, 默认为 0.05) — 解码器的 LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](见 https://arxiv.org/abs/1909.11556)。
  • activation_function (strfunction, 可选, 默认为 "relu") — 解码器和前馈层中的非线性激活函数(函数或字符串)。如果是字符串, 支持 "gelu", "relu", "selu", "swish""gelu_new".
  • dropout (float, optional, defaults to 0.1) — 嵌入层、编码器、解码器和池化器中所有全连接层的dropout概率。
  • attention_dropout (float, optional, 默认为 0.1) — 所有注意力层的 dropout 概率。
  • activation_dropout (float, optional, defaults to 0.0) — 模型中所有激活层的丢弃概率。
  • scale_embedding (bool, optional, defaults to True) — 通过除以 sqrt(d_model) 来缩放嵌入向量。

文本编码器和文本解码器的特定参数

  • encoder_layers (int, optional, defaults to 24) — Transformer文本编码器中的隐藏层数。
  • encoder_ffn_dim (int, optional, defaults to 8192) — Transformer文本编码器中“中间”(即前馈)层的维度。
  • encoder_attention_heads (int, optional, 默认为 16) — Transformer 文本编码器中每个注意力层的注意力头数。
  • decoder_layers (int, optional, defaults to 24) — Transformer文本解码器中的隐藏层数。
  • decoder_ffn_dim (int, optional, 默认为 8192) — Transformer 文本解码器中“中间”(即前馈)层的维度。
  • decoder_attention_heads (int, optional, 默认为 16) — Transformer 文本解码器中每个注意力层的注意力头数。
  • decoder_start_token_id (int, optional, defaults to 3) — 如果编码器-解码器模型使用不同于bos的标记开始解码,则该标记的ID。仅在文本解码器中应用。
  • max_new_tokens (int, optional, 默认为 256) — 生成的最大文本标记数,忽略提示中的标记数。
  • pad_token_id (int, optional, defaults to 0) — 填充文本标记的ID。仅应用于文本解码器模型。
  • bos_token_id (int, optional, defaults to 2) — beginning-of-stream 文本标记的ID。仅应用于文本解码器模型。
  • eos_token_id (int, optional, defaults to 3) — end-of-stream 文本标记的 id。仅应用于文本解码器模型。

语音编码器特定参数

  • speech_encoder_layers (int, optional, defaults to 24) — Transformer语音编码器中的隐藏层数。
  • speech_encoder_attention_heads (int, optional, defaults to 16) — Transformer语音编码器中每个注意力层的注意力头数。
  • speech_encoder_intermediate_size (int, optional, 默认为 4096) — Transformer 语音编码器中“中间”(即前馈)层的维度。
  • speech_encoder_hidden_act (strfunction, 可选, 默认为 "swish") — 语音编码器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu", "relu", "selu", "swish""gelu_new".
  • speech_encoder_dropout (float, optional, defaults to 0.0) — 语音编码器中所有层的丢弃概率。
  • add_adapter (bool, 可选, 默认为 True) — 在语音编码器顶部添加一个适配器层。
  • speech_encoder_layerdrop (float, optional, 默认为 0.1) — 语音编码器的 LayerDrop 概率。更多详情请参阅 [LayerDrop 论文](see https://arxiv.org/abs/1909.11556)。
  • feature_projection_input_dim (int, 可选, 默认为 160) — 语音编码器输入特征投影的输入维度,即使用SeamlessM4TFeatureExtractor处理输入音频后的维度。
  • num_conv_pos_embeddings (int, 可选, 默认为 128) — 卷积位置嵌入的数量。定义了语音编码器的1D卷积位置嵌入层的核大小。
  • num_conv_pos_embedding_groups (int, optional, 默认为 16) — 语音编码器的1D卷积位置嵌入层的组数。
  • adaptor_kernel_size (int, optional, 默认为 8) — 适配器网络中卷积层的核大小。仅在 add_adapter 为 True 时相关。
  • adaptor_stride (int, 可选, 默认为 8) — 适配器网络中卷积层的步幅。仅在 add_adapter is True 时相关。
  • adaptor_dropout (float, optional, defaults to 0.1) — 语音适配器中所有层的丢弃概率。
  • num_adapter_layers (int, 可选, 默认为 1) — 适配器网络中应使用的卷积层数。仅在 add_adapter is True 时相关。
  • position_embeddings_type (str, 可选, 默认为 "relative") — 可以指定为 relativerotary 分别表示相对或旋转位置嵌入。如果留空 None 则不应用相对位置嵌入。仅应用于语音编码器。
  • rotary_embedding_base (int, 可选, 默认为 10000) — 如果使用 "rotary" 位置嵌入,定义嵌入基础的大小。仅应用于语音编码器。
  • max_source_positions (int, 可选, 默认为 4096) — 如果使用 "relative" 位置嵌入,定义最大源输入位置。仅应用于语音编码器。
  • conv_depthwise_kernel_size (int, 可选, 默认为 31) — Conformer 块中卷积深度一维层的核大小。仅应用于语音编码器。

文本到单位 (t2u) 模型特定参数

  • t2u_bos_token_id (int, 可选, 默认为 0) — 流开始单元令牌的ID。仅应用于文本到单元的seq2seq模型。
  • t2u_pad_token_id (int, 可选, 默认为 1) — 填充单元令牌的ID。仅应用于文本到单元的seq2seq模型。
  • t2u_eos_token_id (int, 可选, 默认为 2) — 流结束单元标记的ID。仅应用于文本到单元的seq2seq模型。
  • t2u_decoder_start_token_id (int, optional, 默认为 2) — 如果编码器-解码器模型使用不同于 bos 的标记开始解码,则该标记的 ID。仅适用于文本到单元的 seq2seq 模型。
  • t2u_max_new_tokens (int, 可选, 默认为 1024) — 生成的最大单位标记数,忽略提示中的标记数。仅应用于文本到单位的序列到序列模型。
  • t2u_encoder_layers (int, optional, 默认为 6) — Transformer 文本到单元编码器中的隐藏层数。
  • t2u_encoder_ffn_dim (int, optional, 默认为 8192) — Transformer 文本到单元编码器中“中间”(即前馈)层的维度。
  • t2u_encoder_attention_heads (int, optional, 默认为 16) — Transformer 文本到单元编码器中每个注意力层的注意力头数。
  • t2u_decoder_layers (int, optional, defaults to 6) — Transformer文本到单元解码器中的隐藏层数。
  • t2u_decoder_ffn_dim (int, optional, 默认为 8192) — Transformer 文本到单元解码器中“中间”(即前馈)层的维度。
  • t2u_decoder_attention_heads (int, optional, 默认为 16) — Transformer 文本到单元解码器中每个注意力层的注意力头数。
  • t2u_max_position_embeddings (int, optional, defaults to 2048) — The maximum sequence length that this model text-to-unit component might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048).

    Hifi-Gan 声码器特定参数

  • sampling_rate (int, optional, defaults to 16000) — 生成输出音频的采样率,以赫兹(Hz)表示。
  • upsample_initial_channel (int, 可选, 默认为 512) — hifi-gan 上采样网络的输入通道数。仅适用于声码器。
  • upsample_rates (Tuple[int]List[int], 可选, 默认为 [5, 4, 4, 2, 2]) — 一个整数元组,定义了声码器上采样网络中每个一维卷积层的步幅。 upsample_rates 的长度定义了卷积层的数量,并且必须与 upsample_kernel_sizes 的长度匹配。仅适用于声码器。
  • upsample_kernel_sizes (Tuple[int]List[int], 可选, 默认为 [11, 8, 8, 4, 4]) — 一个整数元组,定义了声码器上采样网络中每个1D卷积层的核大小。upsample_kernel_sizes 的长度定义了卷积层的数量,并且必须与 upsample_rates 的长度匹配。仅适用于声码器。
  • resblock_kernel_sizes (Tuple[int]List[int], 可选, 默认为 [3, 7, 11]) — 一个整数元组,定义了多感受野融合(MRF)模块中声码器1D卷积层的核大小。仅适用于声码器。
  • resblock_dilation_sizes (Tuple[Tuple[int]]List[List[int]], 可选, 默认为 [[1, 3, 5], [1, 3, 5], [1, 3, 5]]) — 一个嵌套的整数元组,定义了在多感受野融合(MRF)模块中声码器扩张1D卷积层的扩张率。仅适用于声码器。
  • leaky_relu_slope (float, optional, 默认为 0.1) — 用于声码器中 leaky ReLU 激活的负斜率角度。仅适用于声码器。
  • unit_hifi_gan_vocab_size (int, optional, 默认为 10000) — SeamlessM4T 声码器的词汇量大小。定义了可以通过传递给 ~SeamlessM4TModel~SeamlessM4TForSpeechToSpeech~SeamlessM4TForTextToSpeechinputs_ids 表示的不同单元标记的数量。
  • unit_embed_dim (int, 可选, 默认为 1280) — 提供给 hifi-gan 声码器的输入 id 的投影维度。仅适用于声码器。
  • lang_embed_dim (int, 可选, 默认为 256) — 提供给 hifi-gan 声码器的目标语言的投影维度。仅适用于声码器。
  • spkr_embed_dim (int, 可选, 默认为 256) — 提供给 hifi-gan 声码器的说话者 id 的投影维度。仅适用于声码器。
  • vocoder_num_langs (int, optional, 默认为 36) — 声码器支持的语言数量。可能与 t2u_num_langs 不同。
  • vocoder_num_spkrs (int, 可选, 默认为 200) — 声码器支持的说话者数量。
  • variance_predictor_kernel_size (int, 可选, 默认为 3) — 持续时间预测器的内核大小。仅适用于声码器。
  • var_pred_dropout (float, optional, 默认为 0.5) — 持续时间预测器的丢弃概率。仅适用于声码器。
  • vocoder_offset (int, optional, 默认为 4) — 将单元标记的ID偏移此数值以考虑符号标记。仅适用于声码器。

这是用于存储~SeamlessM4TModel配置的配置类。它用于根据指定的参数实例化一个SeamlessM4T模型,定义模型架构。使用默认值实例化配置将产生与“facebook/hf-seamless-m4t-medium”架构类似的配置。

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

>>> from transformers import SeamlessM4TModel, SeamlessM4TConfig

>>> # Initializing a SeamlessM4T "facebook/hf-seamless-m4t-medium" style configuration
>>> configuration = SeamlessM4TConfig()

>>> # Initializing a model from the "facebook/hf-seamless-m4t-medium" style configuration
>>> model = SeamlessM4TModel(configuration)

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

SeamlessM4TTokenizer

transformers.SeamlessM4TTokenizer

< >

( vocab_file bos_token = '' eos_token = '' sep_token = '' cls_token = '' unk_token = '' pad_token = '' tokenizer_file = None src_lang = 'eng' tgt_lang = 'fra' sp_model_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None additional_special_tokens = None add_prefix_space = True **kwargs )

参数

  • vocab_file (str) — 词汇表文件的路径。
  • bos_token (str, optional, defaults to "<s>") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

    在使用特殊标记构建序列时,这不是用于序列开头的标记。使用的标记是cls_token

  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.

    在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是sep_token

  • sep_token (str, optional, defaults to "") — 分隔符标记,用于从多个序列构建序列时使用,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。
  • cls_token (str, 可选, 默认为 "") — 用于序列分类(对整个序列进行分类而不是对每个标记进行分类)的分类器标记。当使用特殊标记构建时,它是序列的第一个标记。
  • unk_token (str, optional, defaults to "") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • pad_token (str, optional, defaults to "") — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。
  • tokenizer_file (str, optional) — 用于替代词汇表文件的标记器文件的路径。
  • src_lang (str, optional, defaults to "eng") — 用作翻译的源语言的语言。
  • tgt_lang (str, optional, defaults to "fra") — 用作翻译目标语言的语言。
  • sp_model_kwargs (Dict[str, Any], optional) — 传递给模型初始化的额外关键字参数。
  • additional_special_tokens (元组或列表,元素类型为 strtokenizers.AddedToken, 可选) — 一个包含额外特殊标记的元组或列表。可用于指定分词器将支持的语言列表。
  • add_prefix_space (bool, 可选, 默认为 True) — 是否在输入前添加一个初始空格。这允许将前导词视为任何其他词。

构建一个SeamlessM4T分词器。

改编自 RobertaTokenizerXLNetTokenizer。基于 SentencePiece

源语言文档的分词方法是 ,而目标语言文档的分词方法是

示例:

>>> from transformers import SeamlessM4TTokenizer

>>> tokenizer = SeamlessM4TTokenizer.from_pretrained(
...     "facebook/hf-seamless-m4t-medium", src_lang="eng", tgt_lang="fra"
... )
>>> example_english_phrase = " UN Chief Says There Is No Military Solution in Syria"
>>> expected_translation_french = "Le chef de l'ONU affirme qu'il n'y a pas de solution militaire en Syrie."
>>> inputs = tokenizer(example_english_phrase, text_target=expected_translation_french, return_tensors="pt")

__call__

< >

( text: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None text_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = True pad_to_multiple_of: typing.Optional[int] = 2 src_lang: typing.Optional[str] = None tgt_lang: typing.Optional[str] = None **kwargs )

参数

  • text (str, List[str], List[List[str]], optional) — 要编码的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_pair (str, List[str], List[List[str]], optional) — 要编码的序列或序列批次。每个序列可以是一个字符串或一个字符串列表 (预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_target (str, List[str], List[List[str]], optional) — 要编码为目标文本的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_pair_target (str, List[str], List[List[str]], optional) — 要编码为目标文本的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置is_split_into_words=True(以消除与序列批次的歧义)。
  • padding (bool, str or PaddingStrategy, optional, defaults to True) — Select a strategy to pad the returned sequences (according to the model’s padding side and padding index) among:
    • True or '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 argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).
  • pad_to_multiple_of (int, optional) — If set will pad the sequence to a multiple of the provided value.

    这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Core特别有用。

  • src_lang (str, 可选) — 表示源语言的字符串。如果未指定,将使用最后指定的src_lang(在初始化时或调用此分词器时指定)。
  • tgt_lang (str, 可选) — 表示目标语言的字符串。如果未指定,则将使用最后指定的tgt_lang(在初始化时或调用此分词器时指定)。
  • kwargs (可选) — 剩余的关键字参数字典,将传递给 PreTrainedTokenizer.call().

build_inputs_with_special_tokens

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — 特殊令牌将被添加到的ID列表。
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

带有适当特殊标记的输入ID列表。

通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。一个NLLB序列具有以下格式,其中X代表序列:

  • input_ids(用于编码器)X [eos, src_lang_code]
  • decoder_input_ids: (用于解码器) X [eos, tgt_lang_code]

BOS 从未被使用。序列对不是预期的使用场景,但它们将在没有分隔符的情况下处理。

get_special_tokens_mask

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: bool = False ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。
  • already_has_special_tokens (bool, optional, defaults to False) — 是否已经为模型格式化了包含特殊标记的标记列表。

返回

List[int]

一个整数列表,范围在[0, 1]:1表示特殊标记,0表示序列标记。

从没有添加特殊标记的标记列表中检索序列ID。当使用标记器的prepare_for_model方法添加特殊标记时,会调用此方法。

create_token_type_ids_from_sequences

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

零的列表。

从传递给序列对分类任务的两个序列中创建一个掩码。nllb 不使用标记类型 ID,因此返回一个零列表。

保存词汇表

< >

( 保存目录: str 文件名前缀: typing.Optional[str] = None )

SeamlessM4TTokenizerFast

transformers.SeamlessM4TTokenizerFast

< >

( vocab_file = None tokenizer_file = None bos_token = '' eos_token = '' sep_token = '' cls_token = '' unk_token = '' pad_token = '' src_lang = 'eng' tgt_lang = 'fra' additional_special_tokens = None **kwargs )

参数

  • vocab_file (str, optional) — 词汇表文件的路径。
  • tokenizer_file (str, optional) — 用于替代词汇表文件的标记器文件的路径。
  • bos_token (str, optional, defaults to "<s>") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

    在使用特殊标记构建序列时,这不是用于序列开头的标记。使用的标记是cls_token

  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.

    在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是sep_token

  • sep_token (str, optional, defaults to "") — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。
  • cls_token (str, 可选, 默认为 "") — 用于序列分类(对整个序列进行分类而不是对每个标记进行分类)的分类器标记。当使用特殊标记构建时,它是序列的第一个标记。
  • unk_token (str, optional, defaults to "") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • pad_token (str, optional, defaults to "") — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。
  • src_lang (str, optional, defaults to "eng") — 用作翻译的源语言的语言。
  • tgt_lang (str, optional, defaults to "fra") — 用作翻译目标语言的语言。
  • additional_special_tokens (tuple or list of str or tokenizers.AddedToken, optional) — 一个元组或列表,包含额外的特殊标记。

构建一个“快速”的SeamlessM4T分词器(基于HuggingFace的tokenizers库)。基于 BPE

这个分词器继承自PreTrainedTokenizerFast,其中包含了大部分主要方法。用户应参考这个超类以获取有关这些方法的更多信息。

源语言文档的分词方法是 ,而目标语言文档的分词方法是

示例:

>>> from transformers import SeamlessM4TTokenizerFast

>>> tokenizer = SeamlessM4TTokenizerFast.from_pretrained(
...     "facebook/hf-seamless-m4t-medium", src_lang="eng", tgt_lang="fra"
... )
>>> example_english_phrase = " UN Chief Says There Is No Military Solution in Syria"
>>> expected_translation_french = "Le chef de l'ONU affirme qu'il n'y a pas de solution militaire en Syrie."
>>> inputs = tokenizer(example_english_phrase, text_target=expected_translation_french, return_tensors="pt")

__call__

< >

( text: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None text_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = True pad_to_multiple_of: typing.Optional[int] = 2 src_lang: typing.Optional[str] = None tgt_lang: typing.Optional[str] = None **kwargs )

参数

  • text (str, List[str], List[List[str]], optional) — 要编码的序列或序列批次。每个序列可以是一个字符串或字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_pair (str, List[str], List[List[str]], optional) — 要编码的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_target (str, List[str], List[List[str]], optional) — 要编码为目标文本的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_pair_target (str, List[str], List[List[str]], optional) — 要编码为目标文本的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置is_split_into_words=True(以消除与序列批次的歧义)。
  • padding (bool, str or PaddingStrategy, optional, defaults to True) — Select a strategy to pad the returned sequences (according to the model’s padding side and padding index) among:
    • True or '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 argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).
  • pad_to_multiple_of (int, optional) — If set will pad the sequence to a multiple of the provided value.

    这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Core特别有用。

  • src_lang (str, optional) — 表示源语言的字符串。如果未指定,则将使用最后指定的src_lang(在初始化时或调用此分词器时指定)。
  • tgt_lang (str, 可选) — 表示目标语言的字符串。如果未指定,将使用最后指定的tgt_lang(在初始化或调用此分词器时指定)。
  • kwargs (可选) — 剩余的关键字参数字典,将传递给 PreTrainedTokenizerFast.call().

SeamlessM4TFeatureExtractor

transformers.SeamlessM4TFeatureExtractor

< >

( feature_size = 80 sampling_rate = 16000 num_mel_bins = 80 padding_value = 0.0 stride = 2 **kwargs )

参数

  • feature_size (int, optional, defaults to 80) — 提取特征的特征维度。
  • sampling_rate (int, optional, defaults to 16000) — 音频文件应被数字化的采样率,以赫兹(Hz)表示。
  • num_mel_bins (int, optional, defaults to 80) — 梅尔频率区间的数量.
  • padding_value (float, 可选, 默认为 0.0) — 用于填充填充向量的值。
  • stride (int, optional, 默认为 2) — 用于将音频从形状 (batch_size,num_frames,num_mel_bins) 重塑为 (batch_size,num_frames//stride,num_mel_bins*stride) 的步幅。

构建一个SeamlessM4T特征提取器。

此特征提取器继承自SequenceFeatureExtractor,其中包含了大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。

该类从原始语音中提取梅尔滤波器组特征。

__call__

< >

( raw_speech: typing.Union[numpy.ndarray, typing.List[float], typing.List[numpy.ndarray], typing.List[typing.List[float]]] padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = True pad_to_multiple_of: typing.Optional[int] = 2 max_length: typing.Optional[int] = None truncation: bool = False return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None sampling_rate: typing.Optional[int] = None return_attention_mask: typing.Optional[bool] = None do_normalize_per_mel_bins: typing.Optional[bool] = True **kwargs )

参数

  • raw_speech (np.ndarray, torch.Tensor, List[float], List[np.ndarray], List[torch.Tensor], —
  • List[List[float]], List[List[List[float]]]) — The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a torch tensor, a list of float values, a list of numpy arrays, a list of torch tensors, a list of list of float values or a list of a list of list of float values. If raw_speech is a one-dimensional np.ndarray, torch.Tensor or a List[float], raw_speech is considered a single-channel, single-sample sound. In all other cases, the first dimension of raw_speech, whether from an np.ndarray, a torch.Tensor or a List[...], corresponds to the number of samples in the batch, and the number of channels (i.e. mono or stereo character) is derived from the other dimensions (1D -> single-channel waveform batches; 2D-> stereo-channel waveform batches).
  • padding (bool, str or PaddingStrategy, optional, defaults to True) — Select a strategy to pad the returned sequences (according to the model’s padding side and padding index) among:
    • True or '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 argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).
  • pad_to_multiple_of (int, optional, defaults to 2) — If set will pad the sequence to a multiple of the provided value.

    这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用,或者对于TPUs来说,序列长度为128的倍数是有益的。

  • max_length (int, 可选) — 返回列表的最大长度以及可选的填充长度(见上文)。
  • 截断 (bool) — 激活截断功能,将超过max_length的输入序列截断至max_length
  • 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.

    什么是注意力掩码?

    对于SeamlessM4T模型,attention_mask 应始终在批量推理时传递,以避免细微的错误。

  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • sampling_rate (int, optional) — raw_speech 输入被采样的采样率。强烈建议在前向调用时传递 sampling_rate 以防止静默错误。
  • do_normalize_per_mel_bins (bool, optional, defaults to True) — 是否对每个梅尔通道的输入进行零均值单位方差归一化。
  • kwargs (可选) — 剩余的关键字参数字典,将传递给分词器或特征提取器。

用于特征化并为一个或多个序列准备模型的主要方法。

SeamlessM4TProcessor

transformers.SeamlessM4TProcessor

< >

( feature_extractor tokenizer )

参数

构建一个SeamlessM4T处理器,它将SeamlessM4T特征提取器和SeamlessM4T分词器封装成一个单一的处理器。

SeamlessM4TProcessor 提供了 SeamlessM4TFeatureExtractorSeamlessM4TTokenizerFast 的所有功能。有关更多信息,请参阅 call()decode()

__call__

< >

( text = 无 audios = 无 src_lang = 无 tgt_lang = 无 **kwargs ) BatchEncoding

参数

  • text (str, List[str], List[List[str]]) — 要编码的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • audios (np.ndarray, torch.Tensor, List[np.ndarray], List[torch.Tensor]) — 要准备的音频或音频批次。每个音频可以是NumPy数组或PyTorch张量。在NumPy数组/PyTorch张量的情况下,每个音频的形状应为(C, T),其中C是通道数,T是音频的样本长度。
  • src_lang (str, optional) — 输入文本/音频的语言代码。如果未指定,将使用最后指定的 src_lang
  • tgt_lang (str, 可选) — 目标语言的代码。如果未指定,将使用最后指定的tgt_lang
  • kwargs (可选) — 剩余的关键字参数字典,这些参数将传递给特征提取器和/或分词器。

返回

BatchEncoding

一个包含以下字段的BatchEncoding

  • input_ids — 要输入模型的标记ID列表。当text不为None时返回。
  • attention_mask — 指定模型应关注哪些标记的索引列表(当return_attention_mask=True“attention_mask”self.model_input_names中且text不为None时)。
  • input_features — 要输入模型的音频输入特征。当audios不为None时返回。

准备模型的一个或多个序列和音频的主要方法。如果text不为None,则此方法将textkwargs参数转发给SeamlessM4TTokenizerFast的call()以编码文本。为了准备音频,如果audios不为None,则此方法将audioskwrags参数转发给SeamlessM4TFeatureExtractor的call()。请参考上述两个方法的文档字符串以获取更多信息。

无缝M4T代码高保真生成器

transformers.SeamlessM4TCodeHifiGan

< >

( config )

参数

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

Code HiFi-GAN 语音编码器如这个仓库中所述。 此模型继承自PreTrainedModel。查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

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

前进

< >

( input_ids: LongTensor spkr_id: Tensor lang_id: Tensor )

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用SeamlessM4TTextToUnitForConditionalGeneration获取索引。什么是输入ID?

  • spkr_id (int, 可选) — 用于语音合成的说话者ID。必须小于config.vocoder_num_spkrs.
  • tgt_lang (str, optional) — 用作翻译目标语言的语言ID。

无缝M4T高保真Gan

transformers.SeamlessM4THifiGan

< >

( 配置: SeamlessM4TConfig )

前进

< >

( input_embeds: FloatTensor ) torch.FloatTensor

参数

  • spectrogram (torch.FloatTensor) — 包含对数梅尔频谱图的张量。可以是批量的,形状为(batch_size, sequence_length, model_in_dim),也可以是非批量的,形状为(sequence_length, model_in_dim)。注意model_in_dimconfig.unit_embed_dimconfig.lang_embed_dimconfig.spkr_embed_dim的总和。

返回

torch.FloatTensor

包含语音波形的张量。如果输入的频谱图是批处理的,形状将为(batch_size, num_frames,)。如果未批处理,形状将为(num_frames,)

将log-mel频谱图转换为语音波形。传递一批log-mel频谱图将返回一批语音波形。传递单个未批处理的log-mel频谱图将返回单个未批处理的语音波形。

SeamlessM4TTextToUnitModel

class transformers.SeamlessM4TTextToUnitModel

< >

( config: SeamlessM4TConfig embed_tokens_decoder: typing.Optional[torch.nn.modules.sparse.Embedding] = None )

参数

  • config (~SeamlessM4TConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • embed_tokens_decoder (nn.Embedding, optional) — 解码器的输入嵌入.

Transformer 纯文本到单元的编码器-解码器。编码器是一个没有嵌入的 SeamlessM4TEncoder,解码器是一个 SeamlessM4TDecoder。 该模型是 PyTorch torch.nn.Module 的子类。将其用作常规的 PyTorch 模块,并参考 PyTorch 文档以了解与一般使用和行为相关的所有事项。

SeamlessM4T文本到单元条件生成

transformers.SeamlessM4TTextToUnitForConditionalGeneration

< >

( config: SeamlessM4TConfig embed_tokens_decoder: typing.Optional[torch.nn.modules.sparse.Embedding] = None )

参数

  • config (~SeamlessM4TConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • embed_tokens_decoder (nn.Embedding, optional) — 解码器的输入嵌入.

带有语言模型头的Transformer文本到单元编码器-解码器。基础编码器-解码器模型是SeamlessM4TTextToUnit。 该模型是PyTorch torch.nn.Module的子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None inputs_embeds: typing.Optional[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 return_dict: typing.Optional[bool] = None )

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary.

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

    什么是输入ID?

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

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

    什么是解码器输入ID?

    Bart 使用 eos_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择只输入最后一个 decoder_input_ids(参见 past_key_values)。

    对于翻译和摘要训练,应提供decoder_input_ids。如果没有提供decoder_input_ids,模型将根据论文中的去噪预训练方法,通过将input_ids向右移动来创建此张量。

  • decoder_attention_mask (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

    如果你想改变填充行为,你应该阅读modeling_bart._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

  • encoder_outputs (tuple(tuple(torch.FloatTensor), 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选) 是编码器最后一层的输出隐藏状态序列。用于解码器的交叉注意力中。
  • past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head).

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

    如果使用了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 of shape (batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

    如果decoder_input_idsdecoder_inputs_embeds都未设置,decoder_inputs_embeds将取inputs_embeds的值。

  • 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, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

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

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

< > Update on GitHub