MarianMT
概述
一个用于翻译模型的框架,使用与BART相同的模型。翻译结果应该相似,但不完全相同于每个模型卡片中链接的测试集输出。 该模型由sshleifer贡献。
实现说明
每个模型在磁盘上大约为298 MB,总共有超过1,000个模型。
支持的语言对列表可以在这里找到。
模型最初由Jörg Tiedemann使用Marian C++库进行训练,该库支持快速训练和翻译。
所有模型都是具有6层的变压器编码器-解码器。每个模型的性能都记录在模型卡中。
需要BPE预处理的80个opus模型不受支持。
建模代码与BartForConditionalGeneration相同,只有一些小的修改:
- static (sinusoid) positional embeddings (
MarianConfig.static_position_embeddings=True
) - no layernorm_embedding (
MarianConfig.normalize_embedding=False
) - the model starts generating with
pad_token_id
(which has 0 as a token_embedding) as the prefix (Bart uses<s/>
),
- static (sinusoid) positional embeddings (
批量转换模型的代码可以在
convert_marian_to_pytorch.py
中找到。
命名
- 所有模型名称使用以下格式:
Helsinki-NLP/opus-mt-{src}-{tgt}
- 用于命名模型的语言代码不一致。通常可以找到两位数的代码这里,三位数的代码需要谷歌搜索“语言代码 {code}”。
- 格式为
es_AR
的代码通常是code_{region}
。这个例子是来自阿根廷的西班牙语。 - 模型分两个阶段进行转换。前1000个模型使用ISO-639-2代码来识别语言,第二组使用ISO-639-5代码和ISO-639-2代码的组合。
示例
- 由于Marian模型比库中许多其他翻译模型更小,它们对于微调实验和集成测试非常有用。
- 在GPU上进行微调
多语言模型
- 所有模型名称使用以下格式:
Helsinki-NLP/opus-mt-{src}-{tgt}
: - 如果模型可以输出多种语言,你应该通过在
src_text
前添加所需的输出语言代码来指定语言。 - 您可以在模型的模型卡中查看其支持的语言代码,位于目标成分下,例如在opus-mt-en-roa中。
- 请注意,如果模型仅在源端支持多语言,例如
Helsinki-NLP/opus-mt-roa-en
,则不需要语言代码。
来自Tatoeba-Challenge 仓库的新多语言模型需要3个字符的语言代码:
>>> from transformers import MarianMTModel, MarianTokenizer
>>> src_text = [
... ">>fra<< this is a sentence in english that we want to translate to french",
... ">>por<< This should go to portuguese",
... ">>esp<< And this to Spanish",
... ]
>>> model_name = "Helsinki-NLP/opus-mt-en-roa"
>>> tokenizer = MarianTokenizer.from_pretrained(model_name)
>>> print(tokenizer.supported_language_codes)
['>>zlm_Latn<<', '>>mfe<<', '>>hat<<', '>>pap<<', '>>ast<<', '>>cat<<', '>>ind<<', '>>glg<<', '>>wln<<', '>>spa<<', '>>fra<<', '>>ron<<', '>>por<<', '>>ita<<', '>>oci<<', '>>arg<<', '>>min<<']
>>> model = MarianMTModel.from_pretrained(model_name)
>>> translated = model.generate(**tokenizer(src_text, return_tensors="pt", padding=True))
>>> [tokenizer.decode(t, skip_special_tokens=True) for t in translated]
["c'est une phrase en anglais que nous voulons traduire en français",
'Isto deve ir para o português.',
'Y esto al español']
以下是查看集线器上所有可用预训练模型的代码:
from huggingface_hub import list_models
model_list = list_models()
org = "Helsinki-NLP"
model_ids = [x.id for x in model_list if x.id.startswith(org)]
suffix = [x.split("/")[1] for x in model_ids]
old_style_multi_models = [f"{org}/{s}" for s in suffix if s != s.lower()]
旧式多语言模型
这些是从OPUS-MT-Train仓库移植的旧式多语言模型:以及每个语言组的成员:
['Helsinki-NLP/opus-mt-NORTH_EU-NORTH_EU',
'Helsinki-NLP/opus-mt-ROMANCE-en',
'Helsinki-NLP/opus-mt-SCANDINAVIA-SCANDINAVIA',
'Helsinki-NLP/opus-mt-de-ZH',
'Helsinki-NLP/opus-mt-en-CELTIC',
'Helsinki-NLP/opus-mt-en-ROMANCE',
'Helsinki-NLP/opus-mt-es-NORWAY',
'Helsinki-NLP/opus-mt-fi-NORWAY',
'Helsinki-NLP/opus-mt-fi-ZH',
'Helsinki-NLP/opus-mt-fi_nb_no_nn_ru_sv_en-SAMI',
'Helsinki-NLP/opus-mt-sv-NORWAY',
'Helsinki-NLP/opus-mt-sv-ZH']
GROUP_MEMBERS = {
'ZH': ['cmn', 'cn', 'yue', 'ze_zh', 'zh_cn', 'zh_CN', 'zh_HK', 'zh_tw', 'zh_TW', 'zh_yue', 'zhs', 'zht', 'zh'],
'ROMANCE': ['fr', 'fr_BE', 'fr_CA', 'fr_FR', 'wa', 'frp', 'oc', 'ca', 'rm', 'lld', 'fur', 'lij', 'lmo', 'es', 'es_AR', 'es_CL', 'es_CO', 'es_CR', 'es_DO', 'es_EC', 'es_ES', 'es_GT', 'es_HN', 'es_MX', 'es_NI', 'es_PA', 'es_PE', 'es_PR', 'es_SV', 'es_UY', 'es_VE', 'pt', 'pt_br', 'pt_BR', 'pt_PT', 'gl', 'lad', 'an', 'mwl', 'it', 'it_IT', 'co', 'nap', 'scn', 'vec', 'sc', 'ro', 'la'],
'NORTH_EU': ['de', 'nl', 'fy', 'af', 'da', 'fo', 'is', 'no', 'nb', 'nn', 'sv'],
'SCANDINAVIA': ['da', 'fo', 'is', 'no', 'nb', 'nn', 'sv'],
'SAMI': ['se', 'sma', 'smj', 'smn', 'sms'],
'NORWAY': ['nb_NO', 'nb', 'nn_NO', 'nn', 'nog', 'no_nb', 'no'],
'CELTIC': ['ga', 'cy', 'br', 'gd', 'kw', 'gv']
}
使用旧式2字符语言代码将英语翻译成多种罗曼语族的示例
>>> from transformers import MarianMTModel, MarianTokenizer
>>> src_text = [
... ">>fr<< this is a sentence in english that we want to translate to french",
... ">>pt<< This should go to portuguese",
... ">>es<< And this to Spanish",
... ]
>>> model_name = "Helsinki-NLP/opus-mt-en-ROMANCE"
>>> tokenizer = MarianTokenizer.from_pretrained(model_name)
>>> model = MarianMTModel.from_pretrained(model_name)
>>> translated = model.generate(**tokenizer(src_text, return_tensors="pt", padding=True))
>>> tgt_text = [tokenizer.decode(t, skip_special_tokens=True) for t in translated]
["c'est une phrase en anglais que nous voulons traduire en français",
'Isto deve ir para o português.',
'Y esto al español']
资源
MarianConfig
类 transformers.MarianConfig
< source >( vocab_size = 58101 decoder_vocab_size = None max_position_embeddings = 1024 encoder_layers = 12 encoder_ffn_dim = 4096 encoder_attention_heads = 16 decoder_layers = 12 decoder_ffn_dim = 4096 decoder_attention_heads = 16 encoder_layerdrop = 0.0 decoder_layerdrop = 0.0 use_cache = True is_encoder_decoder = True activation_function = 'gelu' d_model = 1024 dropout = 0.1 attention_dropout = 0.0 activation_dropout = 0.0 init_std = 0.02 decoder_start_token_id = 58100 scale_embedding = False pad_token_id = 58100 eos_token_id = 0 forced_eos_token_id = 0 share_encoder_decoder_embeddings = True **kwargs )
参数
- vocab_size (
int
, 可选, 默认为 58101) — Marian 模型的词汇表大小。定义了可以通过调用 MarianModel 或 TFMarianModel 时传递的inputs_ids
表示的不同标记的数量。 - d_model (
int
, optional, 默认为 1024) — 层和池化层的维度。 - encoder_layers (
int
, optional, defaults to 12) — 编码器层数. - decoder_layers (
int
, optional, 默认为 12) — 解码器层数. - encoder_attention_heads (
int
, optional, 默认为 16) — Transformer 编码器中每个注意力层的注意力头数。 - decoder_attention_heads (
int
, optional, 默认为 16) — Transformer解码器中每个注意力层的注意力头数。 - decoder_ffn_dim (
int
, optional, defaults to 4096) — 解码器中“中间”(通常称为前馈)层的维度。 - encoder_ffn_dim (
int
, optional, 默认为 4096) — 解码器中“中间”(通常称为前馈)层的维度。 - activation_function (
str
或function
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
、"relu"
、"silu"
和"gelu_new"
。 - dropout (
float
, optional, defaults to 0.1) — 嵌入层、编码器和池化器中所有全连接层的dropout概率。 - attention_dropout (
float
, optional, 默认为 0.0) — 注意力概率的丢弃比例。 - activation_dropout (
float
, optional, 默认为 0.0) — 全连接层内部激活函数的丢弃比例。 - max_position_embeddings (
int
, optional, 默认为 1024) — 此模型可能使用的最大序列长度。通常将其设置为较大的值以防万一(例如,512 或 1024 或 2048)。 - init_std (
float
, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - encoder_layerdrop (
float
, optional, 默认为 0.0) — 编码器的LayerDrop概率。有关更多详细信息,请参阅[LayerDrop论文](see https://arxiv.org/abs/1909.11556)。 - decoder_layerdrop (
float
, 可选, 默认为 0.0) — 解码器的LayerDrop概率。有关更多详细信息,请参阅[LayerDrop论文](see https://arxiv.org/abs/1909.11556)。 - scale_embedding (
bool
, optional, defaults toFalse
) — 通过除以 sqrt(d_model) 来缩放嵌入向量。 - use_cache (
bool
, optional, defaults toTrue
) — 模型是否应返回最后的键/值注意力(并非所有模型都使用) - forced_eos_token_id (
int
, 可选, 默认为 0) — 当达到max_length
时,强制作为最后生成的令牌的ID。通常设置为eos_token_id
.
这是用于存储MarianModel配置的配置类。它用于根据指定的参数实例化一个Marian模型,定义模型架构。使用默认值实例化配置将产生类似于Marian Helsinki-NLP/opus-mt-en-de架构的配置。
配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。
示例:
>>> from transformers import MarianModel, MarianConfig
>>> # Initializing a Marian Helsinki-NLP/opus-mt-en-de style configuration
>>> configuration = MarianConfig()
>>> # Initializing a model from the Helsinki-NLP/opus-mt-en-de style configuration
>>> model = MarianModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
MarianTokenizer
类 transformers.MarianTokenizer
< source >( source_spm target_spm vocab target_vocab_file = 无 source_lang = 无 target_lang = 无 unk_token = '
参数
- source_spm (
str
) — SentencePiece 文件(通常具有 .spm 扩展名),包含源语言的词汇表。 - target_spm (
str
) — SentencePiece 文件(通常具有 .spm 扩展名),包含目标语言的词汇表。 - source_lang (
str
, optional) — 表示源语言的字符串。 - target_lang (
str
, optional) — 表示目标语言的字符串。 - unk_token (
str
, optional, defaults to"
) — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。" - eos_token (
str
, optional, defaults to""
) — 序列结束标记。 - pad_token (
str
, optional, defaults to"
) — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。" - model_max_length (
int
, optional, 默认为 512) — 模型接受的最大句子长度。 - additional_special_tokens (
List[str]
, 可选, 默认为["
) — 分词器使用的额外特殊标记。", " "] - sp_model_kwargs (
dict
, optional) — Will be passed to theSentencePieceProcessor.__init__()
method. The Python wrapper for SentencePiece can be used, among other things, to set:-
enable_sampling
: 启用子词正则化。 -
nbest_size
: 用于unigram的采样参数。对于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
: 用于单字采样的平滑参数,以及BPE-dropout的合并操作丢弃概率。
-
构建一个Marian分词器。基于SentencePiece。
此分词器继承自PreTrainedTokenizer,其中包含了大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。
示例:
>>> from transformers import MarianForCausalLM, MarianTokenizer
>>> model = MarianForCausalLM.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> tokenizer = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> src_texts = ["I am a small frog.", "Tom asked his teacher for advice."]
>>> tgt_texts = ["Ich bin ein kleiner Frosch.", "Tom bat seinen Lehrer um Rat."] # optional
>>> inputs = tokenizer(src_texts, text_target=tgt_texts, return_tensors="pt", padding=True)
>>> outputs = model(**inputs) # should work
通过附加eos_token_id从序列构建模型输入。
MarianModel
类 transformers.MarianModel
< source >( config: MarianConfig )
参数
- config (MarianConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
基本的Marian模型输出原始的隐藏状态,没有任何特定的头部。 该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( 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.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None decoder_head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Union[typing.Tuple[torch.Tensor], transformers.modeling_outputs.BaseModelOutput, NoneType] = 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 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 ) → transformers.modeling_outputs.Seq2SeqModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor
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()。
Marian 使用
pad_token_id
作为decoder_input_ids
生成的起始标记。如果使用了past_key_values
,则可以选择只输入最后一个decoder_input_ids
(参见past_key_values
)。 - decoder_attention_mask (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — 默认行为:生成一个忽略decoder_input_ids
中填充标记的张量。默认情况下也会使用因果掩码。 - head_mask (
torch.Tensor
of shape(encoder_layers, encoder_attention_heads)
, optional) — 用于在编码器中取消选择注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- decoder_head_mask (
torch.Tensor
形状为(decoder_layers, decoder_attention_heads)
, 可选) — 用于在解码器中屏蔽注意力模块中选定的头。在[0, 1]
中选择的掩码值:- 1 表示头 未被屏蔽,
- 0 表示头 被屏蔽.
- cross_attn_head_mask (
torch.Tensor
形状为(decoder_layers, decoder_attention_heads)
, 可选) — 用于在解码器中取消选择交叉注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- 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 whenuse_cache=True
is passed or whenconfig.use_cache=True
) — Tuple oftuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
) and 2 additional tensors of shape(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
.包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),这些状态可用于(参见
past_key_values
输入)以加速顺序解码。如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)
的所有decoder_input_ids
。 - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - decoder_inputs_embeds (
torch.FloatTensor
of shape(batch_size, target_sequence_length, hidden_size)
, optional) — Optionally, instead of passingdecoder_input_ids
you can choose to directly pass an embedded representation. Ifpast_key_values
is used, optionally only the lastdecoder_inputs_embeds
have to be input (seepast_key_values
). This is useful if you want more control over how to convertdecoder_input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.如果
decoder_input_ids
和decoder_inputs_embeds
都未设置,decoder_inputs_embeds
将取inputs_embeds
的值。 - use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
返回
transformers.modeling_outputs.Seq2SeqModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.Seq2SeqModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(MarianConfig)和输入。
-
last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
) — 模型解码器最后一层输出的隐藏状态序列。如果使用了
past_key_values
,则只输出形状为(batch_size, 1, hidden_size)
的序列的最后一个隐藏状态。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
, 可选, 当传递了use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(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 后,用于计算自注意力头中的加权平均值。
MarianModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, MarianModel
>>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> model = MarianModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
>>> decoder_inputs = tokenizer(
... "<pad> Studien haben gezeigt dass es hilfreich ist einen Hund zu besitzen",
... return_tensors="pt",
... add_special_tokens=False,
... )
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 26, 512]
MarianMTModel
类 transformers.MarianMTModel
< source >( config: MarianConfig )
参数
- config (MarianConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
带有语言建模头的Marian模型。可用于摘要生成。 该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( 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.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None decoder_head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Union[typing.Tuple[torch.Tensor], transformers.modeling_outputs.BaseModelOutput, NoneType] = 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 ) → transformers.modeling_outputs.Seq2SeqLMOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor
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()。
Marian 使用
pad_token_id
作为decoder_input_ids
生成的起始标记。如果使用了past_key_values
,则可以选择只输入最后一个decoder_input_ids
(参见past_key_values
)。 - decoder_attention_mask (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — 默认行为:生成一个忽略decoder_input_ids
中填充标记的张量。默认情况下也会使用因果掩码。 - head_mask (
torch.Tensor
of shape(encoder_layers, encoder_attention_heads)
, optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- decoder_head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- cross_attn_head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中取消选择交叉注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- 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 whenuse_cache=True
is passed or whenconfig.use_cache=True
) — Tuple oftuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
) and 2 additional tensors of shape(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
.包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),这些状态可用于(参见
past_key_values
输入)以加速顺序解码。如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)
的所有decoder_input_ids
。 - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - decoder_inputs_embeds (
torch.FloatTensor
of shape(batch_size, target_sequence_length, hidden_size)
, optional) — Optionally, instead of passingdecoder_input_ids
you can choose to directly pass an embedded representation. Ifpast_key_values
is used, optionally only the lastdecoder_inputs_embeds
have to be input (seepast_key_values
). This is useful if you want more control over how to convertdecoder_input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.如果
decoder_input_ids
和decoder_inputs_embeds
都未设置,decoder_inputs_embeds
将取inputs_embeds
的值。 - use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — 用于计算掩码语言建模损失的标签。索引应在[0, ..., config.vocab_size]
或 -100 之间(参见input_ids
文档字符串)。索引设置为-100
的标记将被忽略 (掩码),损失仅针对标签在[0, ..., config.vocab_size]
之间的标记进行计算。
返回
transformers.modeling_outputs.Seq2SeqLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.Seq2SeqLMOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(MarianConfig)和输入。
-
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_layers
的tuple(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 之后,用于计算自注意力头中的加权平均值。
MarianMTModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
Pytorch 版本的 marian-nmt 的 transformer.h (c++)。专为 OPUS-NMT 翻译检查点设计。可用的模型列在 这里。
示例:
>>> from transformers import AutoTokenizer, MarianMTModel
>>> src = "fr" # source language
>>> trg = "en" # target language
>>> model_name = f"Helsinki-NLP/opus-mt-{src}-{trg}"
>>> model = MarianMTModel.from_pretrained(model_name)
>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
>>> sample_text = "où est l'arrêt de bus ?"
>>> batch = tokenizer([sample_text], return_tensors="pt")
>>> generated_ids = model.generate(**batch)
>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
"Where's the bus stop?"
MarianForCausalLM
前进
< source >( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None encoder_hidden_states: typing.Optional[torch.FloatTensor] = None encoder_attention_mask: typing.Optional[torch.FloatTensor] = None head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None 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 ) → transformers.modeling_outputs.CausalLMOutputWithCrossAttentions 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor
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.
- encoder_hidden_states (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 编码器最后一层输出的隐藏状态序列。如果模型配置为解码器,则在交叉注意力中使用。 - encoder_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — 用于避免在编码器输入的填充标记索引上执行注意力的掩码。如果模型配置为解码器,则在交叉注意力中使用此掩码。掩码值在[0, 1]
中选择: - head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于屏蔽注意力模块中选定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- cross_attn_head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于屏蔽交叉注意力模块中选定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- past_key_values (
tuple(tuple(torch.FloatTensor))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — Tuple oftuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
) and 2 additional tensors of shape(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
. The two additional tensors are only required when the model is used as a decoder in a Sequence to Sequence model.包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),这些状态可用于(参见
past_key_values
输入)以加速顺序解码。如果使用了
past_key_values
,用户可以选择只输入最后一个decoder_input_ids
(那些没有将其过去键值状态提供给此模型的)形状为(batch_size, 1)
,而不是所有形状为(batch_size, sequence_length)
的decoder_input_ids
。 - labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — 用于计算掩码语言建模损失的标签。索引应在[0, ..., config.vocab_size]
或 -100 之间(参见input_ids
文档字符串)。索引设置为-100
的标记将被忽略 (掩码),损失仅针对标签在[0, ..., config.vocab_size]
之间的标记计算。 - use_cache (
bool
, optional) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码 (参见past_key_values
)。- 1 表示 未屏蔽 的标记,
- 0 表示 屏蔽 的标记。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
返回
transformers.modeling_outputs.CausalLMOutputWithCrossAttentions 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.CausalLMOutputWithCrossAttentions 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(MarianConfig)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供labels
时返回) — 语言建模损失(用于下一个标记预测)。 -
logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。
-
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 后的交叉注意力权重,用于计算交叉注意力头中的加权平均值。
-
past_key_values (
tuple(tuple(torch.FloatTensor))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 由长度为config.n_layers
的torch.FloatTensor
元组组成的元组,每个元组包含自注意力和交叉注意力层的缓存键, 值状态,如果模型用于编码器-解码器设置。仅在config.is_decoder = True
时相关。包含预计算的隐藏状态(注意力块中的键和值),可用于(参见
past_key_values
输入)以加速顺序解码。
示例:
>>> from transformers import AutoTokenizer, MarianForCausalLM
>>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-fr-en")
>>> model = MarianForCausalLM.from_pretrained("Helsinki-NLP/opus-mt-fr-en", add_cross_attention=False)
>>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
>>> list(logits.shape) == expected_shape
True
TFMarianModel
类 transformers.TFMarianModel
< source >( config: MarianConfig *inputs **kwargs )
参数
- config (MarianConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的MARIAN模型输出原始隐藏状态,没有任何特定的头部。 该模型继承自TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional
API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:
- 仅包含
input_ids
的单个张量,没有其他内容:model(input_ids)
- 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!
调用
< source >( input_ids: tf.Tensor | None = None attention_mask: tf.Tensor | None = None decoder_input_ids: tf.Tensor | None = None decoder_attention_mask: tf.Tensor | None = None decoder_position_ids: tf.Tensor | None = None head_mask: tf.Tensor | None = None decoder_head_mask: tf.Tensor | None = None cross_attn_head_mask: tf.Tensor | None = None encoder_outputs: tf.Tensor | None = None past_key_values: Tuple[Tuple[tf.Tensor]] | None = None inputs_embeds: tf.Tensor | None = None decoder_inputs_embeds: tf.Tensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None training: bool = False **kwargs ) → transformers.modeling_tf_outputs.TFSeq2SeqModelOutput 或 tuple(tf.Tensor)
参数
- input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
tf.Tensor
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 (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — Indices of decoder input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
Marian 使用
pad_token_id
作为decoder_input_ids
生成的起始标记。如果使用了past_key_values
,则可以选择只输入最后一个decoder_input_ids
(参见past_key_values
)。 - decoder_attention_mask (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — 默认情况下会生成并忽略填充标记。不建议在大多数用例中设置此选项。 - decoder_position_ids (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) — 每个解码器输入序列标记在位置嵌入中的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - head_mask (
tf.Tensor
形状为(encoder_layers, encoder_attention_heads)
, 可选) — 用于在编码器中屏蔽注意力模块中选定的头。在[0, 1]
中选择的掩码值:- 1 表示头 未被屏蔽,
- 0 表示头 被屏蔽.
- decoder_head_mask (
tf.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中取消选择注意力模块的头部。在[0, 1]
中选择的掩码值:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- cross_attn_head_mask (
tf.Tensor
形状为(decoder_layers, decoder_attention_heads)
, 可选) — 用于屏蔽交叉注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- encoder_outputs (
tf.FloatTensor
, 可选) — 编码器最后一层的输出的隐藏状态。用于解码器的交叉注意力。 形状为(batch_size, sequence_length, hidden_size)
是一个序列 - past_key_values (
Tuple[Tuple[tf.Tensor]]
长度为config.n_layers
) — 包含预计算的注意力块的关键和值隐藏状态。可用于加速解码。 如果使用了past_key_values
,用户可以选择仅输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去的关键值状态提供给此模型的),而不是所有形状为(batch_size, sequence_length)
的decoder_input_ids
。 - inputs_embeds (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。 如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - use_cache (
bool
, 可选, 默认为True
) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。在训练期间设置为False
,在生成期间设置为True
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为False
) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估之间有不同的行为)。
返回
transformers.modeling_tf_outputs.TFSeq2SeqModelOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFSeq2SeqModelOutput 或一个 tf.Tensor
元组(如果
return_dict=False
被传递或当 config.return_dict=False
时)包含各种元素,取决于
配置 (MarianConfig) 和输入。
-
last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
) — 模型解码器最后一层的隐藏状态序列。如果使用了
past_key_values
,则只输出形状为(batch_size, 1, hidden_size)
的序列的最后一个隐藏状态。 -
past_key_values (
List[tf.Tensor]
, 可选, 当use_cache=True
被传递或当config.use_cache=True
时返回) — 长度为config.n_layers
的tf.Tensor
列表,每个张量的形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
。包含解码器的预计算隐藏状态(注意力块中的键和值),可以用于(参见
past_key_values
输入)加速顺序解码。 -
decoder_hidden_states (
tuple(tf.Tensor)
, 可选, 当output_hidden_states=True
被传递或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。解码器在每层输出处的隐藏状态加上初始嵌入输出。
-
decoder_attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。
-
encoder_last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 模型编码器最后一层的隐藏状态序列。 -
encoder_hidden_states (
tuple(tf.Tensor)
, 可选, 当output_hidden_states=True
被传递或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
encoder_attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
TFMarianModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFMarianModel
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> model = TFMarianModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> outputs = model(inputs)
>>> last_hidden_states = outputs.last_hidden_state
TFMarianMTModel
类 transformers.TFMarianMTModel
< source >( config *inputs **kwargs )
参数
- config (MarianConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
带有语言建模头的MARIAN模型。可用于摘要生成。 该模型继承自TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional
API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:
- 仅包含
input_ids
的单个张量,没有其他内容:model(input_ids)
- 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!
调用
< source >( input_ids: tf.Tensor | None = None attention_mask: tf.Tensor | None = None decoder_input_ids: tf.Tensor | None = None decoder_attention_mask: tf.Tensor | None = None decoder_position_ids: tf.Tensor | None = None head_mask: tf.Tensor | None = None decoder_head_mask: tf.Tensor | None = None cross_attn_head_mask: tf.Tensor | None = None encoder_outputs: TFBaseModelOutput | None = None past_key_values: Tuple[Tuple[tf.Tensor]] | None = None inputs_embeds: tf.Tensor | None = None decoder_inputs_embeds: tf.Tensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None labels: tf.Tensor | None = None training: bool = False ) → transformers.modeling_tf_outputs.TFSeq2SeqLMOutput 或 tuple(tf.Tensor)
参数
- input_ids (
tf.Tensor
of shape({0})
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
tf.Tensor
of shape({0})
, 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 (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — Indices of decoder input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
Marian 使用
pad_token_id
作为decoder_input_ids
生成的起始标记。如果使用了past_key_values
,则可以选择只输入最后一个decoder_input_ids
(参见past_key_values
)。 - decoder_attention_mask (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — 默认情况下会生成并忽略填充标记。不建议在大多数用例中设置此选项。 - decoder_position_ids (
tf.Tensor
形状为(batch_size, sequence_length)
, 可选) — 每个解码器输入序列标记在位置嵌入中的位置索引。选择范围为[0, config.max_position_embeddings - 1]
. - head_mask (
tf.Tensor
形状为(encoder_layers, encoder_attention_heads)
, 可选) — 用于在编码器中屏蔽注意力模块中选定的头。在[0, 1]
中选择的掩码值:- 1 表示头 未被屏蔽,
- 0 表示头 被屏蔽.
- decoder_head_mask (
tf.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- cross_attn_head_mask (
tf.Tensor
形状为(decoder_layers, decoder_attention_heads)
, 可选) — 用于屏蔽交叉注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- encoder_outputs (
tf.FloatTensor
, optional) — 编码器最后一层输出的隐藏状态。用于解码器的交叉注意力。 形状为(batch_size, sequence_length, hidden_size)
的序列 - past_key_values (
Tuple[Tuple[tf.Tensor]]
长度为config.n_layers
) — 包含预计算的注意力块的关键和值隐藏状态。可用于加速解码。 如果使用了past_key_values
,用户可以选择仅输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去的关键值状态提供给此模型的),而不是所有形状为(batch_size, sequence_length)
的decoder_input_ids
。 - inputs_embeds (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。 如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - use_cache (
bool
, 可选, 默认为True
) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。在训练期间设置为False
,在生成期间设置为True
- output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在急切模式下使用,在图形模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为False
) — 是否在训练模式下使用模型(某些模块如dropout模块在训练和评估之间有不同的行为)。 - labels (
tf.tensor
of shape(batch_size, sequence_length)
, optional) — 用于计算掩码语言建模损失的标签。索引应在[0, ..., config.vocab_size]
或 -100 之间(参见input_ids
文档字符串)。索引设置为-100
的标记将被忽略 (掩码),损失仅针对标签在[0, ..., config.vocab_size]
之间的标记进行计算。
返回
transformers.modeling_tf_outputs.TFSeq2SeqLMOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFSeq2SeqLMOutput 或一个 tf.Tensor
元组(如果
return_dict=False
被传递或当 config.return_dict=False
时)包含各种元素,具体取决于
配置 (MarianConfig) 和输入。
-
loss (
tf.Tensor
形状为(n,)
, 可选, 其中 n 是非掩码标签的数量,当提供labels
时返回) — 语言建模损失。 -
logits (
tf.Tensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
past_key_values (
List[tf.Tensor]
, 可选, 当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tf.Tensor
列表,每个张量的形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
)。包含解码器的预计算隐藏状态(注意力块中的键和值),可以用于(参见
past_key_values
输入)加速顺序解码。 -
decoder_hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)。解码器在每层输出处的隐藏状态加上初始嵌入输出。
-
decoder_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的tf.Tensor
元组(每层一个)。解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的tf.Tensor
元组(每层一个)。解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。
-
encoder_last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 模型编码器最后一层输出的隐藏状态序列。 -
encoder_hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)。编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
encoder_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的tf.Tensor
元组(每层一个)。编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
TFMarianMTModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
TF 版本的 marian-nmt 的 transformer.h (c++)。专为 OPUS-NMT 翻译检查点设计。可用的模型列在 这里。
示例:
>>> from transformers import AutoTokenizer, TFMarianMTModel
>>> from typing import List
>>> src = "fr" # source language
>>> trg = "en" # target language
>>> sample_text = "où est l'arrêt de bus ?"
>>> model_name = f"Helsinki-NLP/opus-mt-{src}-{trg}"
>>> model = TFMarianMTModel.from_pretrained(model_name)
>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
>>> batch = tokenizer([sample_text], return_tensors="tf")
>>> gen = model.generate(**batch)
>>> tokenizer.batch_decode(gen, skip_special_tokens=True)
"Where is the bus stop ?"
FlaxMarianModel
类 transformers.FlaxMarianModel
< source >( config: MarianConfig input_shape: typing.Tuple[int] = (1, 1) seed: int = 0 dtype: dtype =
参数
- config (MarianConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
基本的Marian模型转换器输出原始隐藏状态,没有任何特定的头部。 该模型继承自FlaxPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是一个Flax Linen flax.nn.Module 子类。将其作为常规的Flax模块使用,并参考Flax文档以获取与一般用法和行为相关的所有信息。
最后,该模型支持JAX的固有特性,例如:
__call__
< source >( input_ids: 数组 attention_mask: 可选的[jax.Array] = 无 decoder_input_ids: 可选的[jax.Array] = 无 decoder_attention_mask: 可选的[jax.Array] = 无 position_ids: 可选的[jax.Array] = 无 decoder_position_ids: 可选的[jax.Array] = 无 output_attentions: 可选的[布尔] = 无 output_hidden_states: 可选的[布尔] = 无 return_dict: 可选的[布尔] = 无 train: 布尔 = 假 params: 字典 = 无 dropout_rng: <函数 PRNGKey 在 0x7f50727b7640> = 无 ) → transformers.modeling_flax_outputs.FlaxSeq2SeqModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
jnp.ndarray
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- 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.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
对于翻译和摘要训练,应提供
decoder_input_ids
。如果没有提供decoder_input_ids
,模型将根据论文中的去噪预训练方法,通过将input_ids
向右移动来创建此张量。 - decoder_attention_mask (
jnp.ndarray
of shape(batch_size, target_sequence_length)
, optional) — Default behavior: generate a tensor that ignores pad tokens indecoder_input_ids
. Causal mask will also be used by default.如果你想改变填充行为,你应该根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。
- position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - decoder_position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — 每个解码器输入序列标记在位置嵌入中的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
返回
transformers.modeling_flax_outputs.FlaxSeq2SeqModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxSeq2SeqModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(MarianConfig)和输入。
-
last_hidden_state (
jnp.ndarray
形状为(batch_size, sequence_length, hidden_size)
) — 模型解码器最后一层输出的隐藏状态序列。如果使用了
past_key_values
,则只输出形状为(batch_size, 1, hidden_size)
的序列的最后一个隐藏状态。 -
past_key_values (
tuple(tuple(jnp.ndarray))
, 可选, 当传递了use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(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 后,用于计算自注意力头中的加权平均值。
FlaxMarianPreTrainedModel
的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, FlaxMarianModel
>>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> model = FlaxMarianModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
FlaxMarianMTModel
类 transformers.FlaxMarianMTModel
< source >( config: MarianConfig input_shape: typing.Tuple[int] = (1, 1) seed: int = 0 dtype: dtype =
参数
- config (MarianConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
, optional, defaults tojax.numpy.float32
) — The data type of the computation. Can be one ofjax.numpy.float32
,jax.numpy.float16
(on GPUs) andjax.numpy.bfloat16
(on TPUs).这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。
带有语言建模头的MARIAN模型。可用于翻译。 该模型继承自FlaxPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头等)。
该模型也是一个Flax Linen flax.nn.Module 子类。将其作为常规的Flax模块使用,并参考Flax文档以获取与一般用法和行为相关的所有信息。
最后,该模型支持JAX的固有特性,例如:
__call__
< source >( input_ids: 数组 attention_mask: 可选的[jax.Array] = 无 decoder_input_ids: 可选的[jax.Array] = 无 decoder_attention_mask: 可选的[jax.Array] = 无 position_ids: 可选的[jax.Array] = 无 decoder_position_ids: 可选的[jax.Array] = 无 output_attentions: 可选的[bool] = 无 output_hidden_states: 可选的[bool] = 无 return_dict: 可选的[bool] = 无 train: bool = 假 params: 字典 = 无 dropout_rng: tuple(torch.FloatTensor)
参数
- input_ids (
jnp.ndarray
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- 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.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
对于翻译和摘要训练,应提供
decoder_input_ids
。如果没有提供decoder_input_ids
,模型将根据论文中的去噪预训练方法,通过将input_ids
向右移动来创建此张量。 - decoder_attention_mask (
jnp.ndarray
of shape(batch_size, target_sequence_length)
, optional) — Default behavior: generate a tensor that ignores pad tokens indecoder_input_ids
. Causal mask will also be used by default.如果你想改变填充行为,你应该根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。
- position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — 每个输入序列标记在位置嵌入中的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - decoder_position_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — 每个解码器输入序列标记在位置嵌入中的位置索引。选择范围在[0, config.max_position_embeddings - 1]
之间。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
返回
transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput 或一个元组
torch.FloatTensor
(如果传递了 return_dict=False
或当 config.return_dict=False
时)包含各种
元素,取决于配置(MarianConfig)和输入。
-
logits(形状为
(batch_size, sequence_length, config.vocab_size)
的jnp.ndarray
)— 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
past_key_values(
tuple(tuple(jnp.ndarray))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回)— 长度为config.n_layers
的tuple(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(形状为
(batch_size, sequence_length, hidden_size)
的jnp.ndarray
,可选)— 模型编码器最后一层输出的隐藏状态序列。 -
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 之后,用于计算自注意力头中的加权平均值。
FlaxMarianPreTrainedModel
的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, FlaxMarianMTModel
>>> model = FlaxMarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> text = "My friends are cool but they eat too many carbs."
>>> input_ids = tokenizer(text, max_length=64, return_tensors="jax").input_ids
>>> sequences = model.generate(input_ids, max_length=64, num_beams=2).sequences
>>> outputs = tokenizer.batch_decode(sequences, skip_special_tokens=True)
>>> # should give *Meine Freunde sind cool, aber sie essen zu viele Kohlenhydrate.*