Transformers 文档
MarianMT
并获得增强的文档体验
开始使用
此模型于 2018-04-01 发布,并于 2020-11-16 添加到 Hugging Face Transformers。
MarianMT
MarianMT 是一个使用 Marian 框架训练的机器翻译模型,该框架用纯 C++ 编写。该框架包含其自有的自定义自动微分引擎和高效的元算法,可用于训练 BART 等编码器-解码器模型。
所有 MarianMT 模型都是 transformer 编码器-解码器,每个组件有 6 层,使用静态正弦位置嵌入,没有 layernorm 嵌入,并且模型使用 pad_token_id 前缀而非 <s/> 开始生成。
您可以在 赫尔辛基大学语言技术研究组 组织下找到所有原始的 MarianMT 检查点。
此模型由 sshleifer 贡献。
点击右侧边栏的 MarianMT 模型,可查看更多关于如何将 MarianMT 应用于翻译任务的示例。
以下示例演示了如何使用 Pipeline 或 AutoModel 类进行文本翻译。
import torch
from transformers import pipeline
pipeline = pipeline("translation_en_to_de", model="Helsinki-NLP/opus-mt-en-de", dtype=torch.float16, device=0)
pipeline("Hello, how are you?")
使用 AttentionMaskVisualizer 可以更好地了解模型可以关注哪些 token,不能关注哪些 token。
from transformers.utils.attention_visualizer import AttentionMaskVisualizer
visualizer = AttentionMaskVisualizer("Helsinki-NLP/opus-mt-en-de")
visualizer("Hello, how are you?")
注意事项
- MarianMT 模型在磁盘上约为 298MB,有超过 1000 个模型。支持的语言对请查看此 列表。语言代码可能不一致。两位数代码可以在 此处 找到,而三位数代码可能需要进一步搜索。
- 不支持需要 BPE 预处理的模型。
- 所有模型名称都使用以下格式:
Helsinki-NLP/opus-mt-{src}-{tgt}。格式为es_AR的语言代码通常指code_{region}。例如,es_AR指阿根廷的西班牙语。 - 如果模型可以输出多种语言,请在
src_txt前加上所需的输出语言,如下所示。来自 Tatoeba-Challenge 的新多语言模型需要三个字符的语言代码。
from transformers import MarianMTModel, MarianTokenizer
# Model trained on multiple source languages → multiple target languages
# Example: multilingual to Arabic (arb)
model_name = "Helsinki-NLP/opus-mt-mul-mul" # Tatoeba Challenge model
tokenizer = MarianTokenizer.from_pretrained(model_name)
model = MarianMTModel.from_pretrained(model_name)
# Prepend the desired output language code (3-letter ISO 639-3)
src_texts = ["arb>> Hello, how are you today?"]
# Tokenize and translate
inputs = tokenizer(src_texts, return_tensors="pt", padding=True, truncation=True)
translated = model.generate(**inputs)
# Decode and print result
translated_texts = tokenizer.batch_decode(translated, skip_special_tokens=True)
print(translated_texts[0])
- 旧的多语言模型使用两个字符的语言代码。
from transformers import MarianMTModel, MarianTokenizer
# Example: older multilingual model (like en → many)
model_name = "Helsinki-NLP/opus-mt-en-ROMANCE" # English → French, Spanish, Italian, etc.
tokenizer = MarianTokenizer.from_pretrained(model_name)
model = MarianMTModel.from_pretrained(model_name)
# Prepend the 2-letter ISO 639-1 target language code (older format)
src_texts = [">>fr<< Hello, how are you today?"]
# Tokenize and translate
inputs = tokenizer(src_texts, return_tensors="pt", padding=True, truncation=True)
translated = model.generate(**inputs)
# Decode and print result
translated_texts = tokenizer.batch_decode(translated, skip_special_tokens=True)
print(translated_texts[0])
MarianConfig
class 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 bos_token_id = None forced_eos_token_id = 0 share_encoder_decoder_embeddings = True is_decoder = False tie_word_embeddings = True **kwargs )
参数
- vocab_size (
int, optional, defaults to 58101) — Marian 模型的词汇表大小。定义在调用 MarianModel 时传入的inputs_ids所能表示的不同 token 的数量。 - d_model (
int, optional, defaults to 1024) — 层和池化层的维度。 - encoder_layers (
int, optional, defaults to 12) — 编码器层数。 - decoder_layers (
int, optional, defaults to 12) — 解码器层数。 - encoder_attention_heads (
int, optional, defaults to 16) — Transformer 编码器中每个注意力层的注意力头数。 - decoder_attention_heads (
int, optional, defaults to 16) — Transformer 解码器中每个注意力层的注意力头数。 - decoder_ffn_dim (
int, optional, defaults to 4096) — 解码器中“中间”(通常称为前馈)层的维度。 - encoder_ffn_dim (
int, optional, defaults to 4096) — 解码器中“中间”(通常称为前馈)层的维度。 - activation_function (
strorfunction, optional, defaults to"gelu") — 编码器和池化层中的非线性激活函数(函数或字符串)。如果为字符串,支持"gelu"、"relu"、"silu"和"gelu_new"。 - dropout (
float, optional, defaults to 0.1) — 嵌入、编码器和池化层中所有全连接层的 dropout 概率。 - attention_dropout (
float, optional, defaults to 0.0) — 注意力概率的 dropout 比率。 - activation_dropout (
float, optional, defaults to 0.0) — 全连接层内激活值的 dropout 比率。 - max_position_embeddings (
int, optional, defaults to 1024) — 此模型可能用于的最大序列长度。通常设置为较大的值以防万一(例如,512 或 1024 或 2048)。 - init_std (
float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - encoder_layerdrop (
float, optional, defaults to 0.0) — 编码器的 LayerDrop 概率。更多细节请参阅 [LayerDrop 论文](see https://huggingface.co/papers/1909.11556)。 - decoder_layerdrop (
float, optional, defaults to 0.0) — 解码器的 LayerDrop 概率。更多细节请参阅 [LayerDrop 论文](see https://huggingface.co/papers/1909.11556)。 - scale_embedding (
bool, optional, defaults toFalse) — 通过除以 sqrt(d_model) 来缩放嵌入。 - use_cache (
bool, optional, defaults toTrue) — 模型是否应返回最后一个键/值注意力(并非所有模型都使用)。 - forced_eos_token_id (
int, optional, defaults to 0) — 当达到max_length时强制作为最后一个生成的 token 的 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.configMarianTokenizer
class transformers.MarianTokenizer
< source >( source_spm target_spm vocab target_vocab_file = None source_lang = None target_lang = None unk_token = '<unk>' eos_token = '</s>' pad_token = '<pad>' model_max_length = 512 sp_model_kwargs: dict[str, typing.Any] | None = None separate_vocabs = False **kwargs )
参数
- source_spm (
str) — SentencePiece 文件(通常以 .spm 扩展名结尾),其中包含源语言的词汇表。 - target_spm (
str) — SentencePiece 文件(通常以 .spm 扩展名结尾),其中包含目标语言的词汇表。 - source_lang (
str, 可选) — 表示源语言的字符串。 - target_lang (
str, 可选) — 表示目标语言的字符串。 - unk_token (
str, 可选, 默认为"<unk>") — 未知令牌。词汇表中不存在的令牌无法转换为 ID,而是被设置为此令牌。 - eos_token (
str, 可选, 默认为"</s>") — 序列结束令牌。 - pad_token (
str, 可选, 默认为"<pad>") — 用于填充的令牌,例如在批量处理不同长度的序列时。 - model_max_length (
int, 可选, 默认为 512) — 模型接受的最大句子长度。 - additional_special_tokens (
list[str], 可选, 默认为["<eop>", "<eod>"]) — 标记器使用的其他特殊令牌。 - sp_model_kwargs (
dict, 可选) — 将传递给SentencePieceProcessor.__init__()方法。 SentencePiece 的 Python 包装器可用于设置(除其他外):-
enable_sampling:启用子词正则化。 -
nbest_size:unigram 的采样参数。对于 BPE-Dropout 无效。nbest_size = {0,1}:不执行采样。nbest_size > 1:从 nbest_size 结果中采样。nbest_size < 0:假设 nbest_size 是无限的,并使用前向过滤和后向采样算法从所有假设(格)中采样。
-
alpha:unigram 采样的平滑参数,以及 BPE-dropout 的合并操作的 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
class transformers.MarianModel
< source >( config: MarianConfig encoder_no_repeat_ngram_size: int = 0 force_bos_token_to_be_generated: bool | int | str | None = None forced_bos_token_id: int | None = None forced_eos_token_id: int | None = None generation_emphasis_token_ids: list[int] | None = None max_length: int = 512 max_position_embeddings: int = 512 min_length: int = 0 num_beams: int = 1 num_return_sequences: int = 1 pad_token_id: int | None = None repetition_penalty: float = 1.0 suppress_tokens: list[int] | None = None temperature: float = 1.0 top_k: int = 50 top_p: float = 1.0 **kwargs )
参数
- config (MarianConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。
输出原始隐藏状态的裸 Marian 模型,没有任何顶部的特定头部。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None decoder_input_ids: torch.LongTensor | None = None decoder_attention_mask: torch.Tensor | None = None encoder_outputs: tuple[torch.Tensor] | transformers.modeling_outputs.BaseModelOutput | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None decoder_inputs_embeds: torch.FloatTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None cache_position: torch.Tensor | None = None **kwargs ) → transformers.modeling_outputs.Seq2SeqModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor, 形状(batch_size, sequence_length), 可选) — 词汇表中输入序列令牌的索引。默认情况下将忽略填充。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor, 形状(batch_size, sequence_length), 可选) — 用于避免在填充令牌索引上执行注意力的掩码。掩码值选择在[0, 1]中:- 1 表示未掩码的令牌,
- 0 表示已掩码的令牌。
- decoder_input_ids (
torch.LongTensor, 形状(batch_size, target_sequence_length), 可选) — 解码器输入序列令牌在词汇表中的索引。可以使用 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, 形状(batch_size, target_sequence_length), 可选) — 默认行为:生成一个忽略decoder_input_ids中填充令牌的张量。默认还会使用因果掩码。 - encoder_outputs (
Union[tuple, ~modeling_outputs.BaseModelOutput], 可选) — 元组包含(last_hidden_state, 可选:hidden_states, 可选:attentions)形状为(batch_size, sequence_length, hidden_size)的last_hidden_state,可选)是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力。 - past_key_values (
~cache_utils.Cache, 可选) — 可用于加速顺序解码的预计算隐藏状态(自注意力块和交叉注意力块中的键和值)。这通常由模型在解码的早期阶段返回的past_key_values组成,当use_cache=True或config.use_cache=True时。只允许 Cache 实例作为输入,请参阅我们的 kv 缓存指南。如果未传递
past_key_values,默认将初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用
past_key_values,则用户需要只输入未处理的input_ids(即尚未将其过去键值状态传递给此模型的那些),形状为(batch_size, unprocessed_length),而不是所有input_ids,形状为(batch_size, sequence_length)。 - inputs_embeds (
torch.FloatTensor, 形状(batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以直接传递嵌入表示,而不是传递input_ids。如果您想比模型内部的嵌入查找矩阵更精确地控制如何将input_ids索引转换为相关的向量,这将非常有用。 - decoder_inputs_embeds (
torch.FloatTensor, 形状(batch_size, target_sequence_length, hidden_size), 可选) — 可选地,您可以直接传递嵌入表示,而不是传递decoder_input_ids。如果使用了past_key_values,则可以选择只输入最后的decoder_inputs_embeds(请参阅past_key_values)。如果您想比模型内部的嵌入查找矩阵更精确地控制如何将decoder_input_ids索引转换为相关的向量,这将非常有用。如果
decoder_input_ids和decoder_inputs_embeds都未设置,则decoder_inputs_embeds的值为inputs_embeds。 - use_cache (
bool, optional) — If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values). - output_attentions (
bool, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail. - output_hidden_states (
bool, optional) — Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail. - return_dict (
bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. - cache_position (
torch.Tensorof shape(sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
返回
transformers.modeling_outputs.Seq2SeqModelOutput 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.Seq2SeqModelOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (MarianConfig) and inputs.
-
last_hidden_state (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size)) — 模型解码器最后一层输出的隐藏状态序列。如果使用了
past_key_values,则只输出形状为(batch_size, 1, hidden_size)的序列的最后一个隐藏状态。 -
past_key_values (
EncoderDecoderCache, optional, 当传入use_cache=True或当config.use_cache=True时返回) — 这是一个 EncoderDecoderCache 实例。有关更多详细信息,请参阅我们的 kv 缓存指南。包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。 -
decoder_hidden_states (
tuple(torch.FloatTensor), optional, 当传入output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor元组(一个用于嵌入的输出,如果模型有嵌入层,+ 一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。解码器在每个层输出的隐藏状态,加上可选的初始嵌入输出。
-
decoder_attentions (
tuple(torch.FloatTensor), optional, 当传入output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均。
-
cross_attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).解码器交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均。
-
encoder_last_hidden_state (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 模型编码器最后一层输出的隐藏状态序列。 -
encoder_hidden_states (
tuple(torch.FloatTensor), optional, 当传入output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor元组(一个用于嵌入的输出,如果模型有嵌入层,+ 一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。编码器在每个层输出的隐藏状态,加上可选的初始嵌入输出。
-
encoder_attentions (
tuple(torch.FloatTensor), optional, 当传入output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均。
The MarianModel forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
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
class transformers.MarianMTModel
< source >( config: MarianConfig encoder_no_repeat_ngram_size: int = 0 force_bos_token_to_be_generated: bool | int | str | None = None forced_bos_token_id: int | None = None forced_eos_token_id: int | None = None generation_emphasis_token_ids: list[int] | None = None max_length: int = 512 max_position_embeddings: int = 512 min_length: int = 0 num_beams: int = 1 num_return_sequences: int = 1 pad_token_id: int | None = None repetition_penalty: float = 1.0 suppress_tokens: list[int] | None = None temperature: float = 1.0 top_k: int = 50 top_p: float = 1.0 **kwargs )
参数
- config (MarianConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型关联的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
Marian 模型,带有一个语言建模头。可用于摘要。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None decoder_input_ids: torch.LongTensor | None = None decoder_attention_mask: torch.Tensor | None = None encoder_outputs: tuple[torch.Tensor] | transformers.modeling_outputs.BaseModelOutput | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None decoder_inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None cache_position: torch.Tensor | None = None **kwargs ) → transformers.modeling_outputs.Seq2SeqLMOutput or tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 词汇表中输入序列 token 的索引。默认情况下将忽略填充。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — 用于避免对填充 token 索引执行 attention 的掩码。选择的掩码值在[0, 1]:- 1 表示未掩码的 token,
- 0 表示已掩码的 token。
- decoder_input_ids (
torch.LongTensorof shape(batch_size, target_sequence_length), optional) — 解码器输入序列 token 在词汇表中的索引。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
Marian 使用
pad_token_id作为decoder_input_ids生成的起始 token。如果使用了past_key_values,则可以选择只输入最后一个decoder_input_ids(参见past_key_values)。 - decoder_attention_mask (
torch.LongTensorof shape(batch_size, target_sequence_length), optional) — 默认行为:生成一个忽略decoder_input_ids中 padding token 的张量。默认还会使用因果掩码。 - encoder_outputs (
Union[tuple, ~modeling_outputs.BaseModelOutput], optional) — 元组由(last_hidden_state,可选:hidden_states,可选:attentions)组成last_hidden_state形状为(batch_size, sequence_length, hidden_size),可选)是编码器最后一层的隐藏状态序列。用于解码器的交叉 attention。 - past_key_values (
~cache_utils.Cache, optional) — 可用于加速顺序解码的预计算隐藏状态(自 attention 块和交叉 attention 块中的键和值)。这通常由模型在解码的先前阶段返回的past_key_values组成,当use_cache=True或config.use_cache=True时。只允许 Cache 实例作为输入,请参阅我们的 kv cache 指南。如果未传递
past_key_values,默认将初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用
past_key_values,用户只需输入未处理的input_ids(其 past key value 状态未提供给此模型的那些),形状为(batch_size, unprocessed_length),而不是全部input_ids,形状为(batch_size, sequence_length)。 - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — 可选地,您可以直接传递嵌入表示,而不是传递input_ids。如果您想比模型内部的嵌入查找矩阵对input_ids索引的向量转换方式有更多控制,这将非常有用。 - decoder_inputs_embeds (
torch.FloatTensorof shape(batch_size, target_sequence_length, hidden_size), optional) — 可选地,您可以直接传递嵌入表示,而不是传递decoder_input_ids。如果使用了past_key_values,可以选择只输入最后一个decoder_inputs_embeds(参见past_key_values)。如果您想比模型内部的嵌入查找矩阵对decoder_input_ids索引的向量转换方式有更多控制,这将非常有用。如果
decoder_input_ids和decoder_inputs_embeds都未设置,则decoder_inputs_embeds的值将取自inputs_embeds。 - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 用于计算掩码语言模型损失的标签。索引应为[0, ..., config.vocab_size]或 -100(请参阅input_ids文档字符串)。索引设置为-100的 token 将被忽略(掩码),仅为标签在[0, ..., config.vocab_size]中的 token 计算损失。 - use_cache (
bool, optional) — If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values). - output_attentions (
bool, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail. - output_hidden_states (
bool, optional) — Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail. - return_dict (
bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. - cache_position (
torch.Tensorof shape(sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
返回
transformers.modeling_outputs.Seq2SeqLMOutput 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.Seq2SeqLMOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (MarianConfig) and inputs.
-
loss (
torch.FloatTensor,形状为(1,),可选,当提供labels时返回) — 语言建模损失。 -
logits (形状为
(batch_size, sequence_length, config.vocab_size)的torch.FloatTensor) — 语言建模头部的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
past_key_values (
EncoderDecoderCache, optional, 当传入use_cache=True或当config.use_cache=True时返回) — 这是一个 EncoderDecoderCache 实例。有关更多详细信息,请参阅我们的 kv 缓存指南。包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。 -
decoder_hidden_states (
tuple(torch.FloatTensor), optional, 当传入output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor元组(一个用于嵌入的输出,如果模型有嵌入层,+ 一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。解码器在每一层输出时的隐藏状态以及初始嵌入输出。
-
decoder_attentions (
tuple(torch.FloatTensor), optional, 当传入output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均。
-
cross_attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).解码器交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均。
-
encoder_last_hidden_state (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 模型编码器最后一层输出的隐藏状态序列。 -
encoder_hidden_states (
tuple(torch.FloatTensor), optional, 当传入output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor元组(一个用于嵌入的输出,如果模型有嵌入层,+ 一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。编码器在每一层输出时的隐藏状态以及初始嵌入输出。
-
encoder_attentions (
tuple(torch.FloatTensor), optional, 当传入output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均。
The MarianMTModel forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> 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
forward
< 来源 >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None encoder_hidden_states: torch.FloatTensor | None = None encoder_attention_mask: torch.FloatTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None cache_position: torch.LongTensor | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs ) → transformers.modeling_outputs.CausalLMOutputWithCrossAttentions 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor, shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensor, 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, shape(batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder. - encoder_attention_mask (
torch.FloatTensor, shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- past_key_values (
~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.FloatTensor, shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - labels (
torch.LongTensor, shape(batch_size, sequence_length), optional) — Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size]or -100 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]. - use_cache (
bool, optional) — If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values). - output_attentions (
bool, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail. - output_hidden_states (
bool, optional) — Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail. - return_dict (
bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. - cache_position (
torch.LongTensor, shape(sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length. - logits_to_keep (
Union[int, torch.Tensor], optional, defaults to0) — If anint, compute logits for the lastlogits_to_keeptokens. If0, calculate logits for allinput_ids(special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If atorch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).
返回
transformers.modeling_outputs.CausalLMOutputWithCrossAttentions or tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.CausalLMOutputWithCrossAttentions 或一个 torch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置(MarianConfig)和输入。
-
loss (
torch.FloatTensor形状为(1,),可选,当提供labels时返回) — 语言建模损失(用于下一个 token 预测)。 -
logits (形状为
(batch_size, sequence_length, config.vocab_size)的torch.FloatTensor) — 语言建模头部的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
hidden_states (
tuple(torch.FloatTensor), optional, 当传递output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor), optional, 当传递output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).注意力 softmax 后的交叉注意力权重,用于计算交叉注意力头中的加权平均。
-
past_key_values (
Cache, optional, 当传递use_cache=True或当config.use_cache=True时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南。包含预先计算的隐藏状态(注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。
MarianForCausalLM 的 forward 方法重写了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> 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")
>>> 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