Transformers 文档
XLM
并获得增强的文档体验
开始使用
该模型于 2019-01-22 发布,并于 2020-11-16 添加到 Hugging Face Transformers。
XLM
XLM 展示了两种跨语言预训练方法:在单一语言上进行无监督训练,以及在多种语言上进行有监督训练并采用跨语言语言模型目标(BERT 掩码语言模型目标的扩展)。XLM 模型支持因果语言模型目标、掩码语言模型和翻译语言模型(多语言输入的 BERT 掩码语言模型目标的扩展)。
您可以在 Facebook AI 社区 组织下找到所有原始 XLM 检查点。
单击右侧边栏中的 XLM 模型,了解如何将 XLM 应用于分类、翻译和问答等不同跨语言任务的更多示例。
以下示例演示了如何使用 Pipeline、AutoModel 和命令行预测 <mask> 标记。
import torch
from transformers import pipeline
pipeline = pipeline(
task="fill-mask",
model="facebook/xlm-roberta-xl",
dtype=torch.float16,
device=0
)
pipeline("Bonjour, je suis un modèle <mask>.")XLMConfig
class transformers.XLMConfig
< source >( vocab_size = 30145 emb_dim = 2048 n_layers = 12 n_heads = 16 dropout = 0.1 attention_dropout = 0.1 gelu_activation = True sinusoidal_embeddings = False causal = False asm = False n_langs = 1 use_lang_emb = True max_position_embeddings = 512 embed_init_std = 0.02209708691207961 layer_norm_eps = 1e-12 init_std = 0.02 unk_index = 3 mask_index = 5 is_encoder = True summary_type = 'first' summary_use_proj = True summary_activation = None summary_proj_to_labels = True summary_first_dropout = 0.1 start_n_top = 5 end_n_top = 5 mask_token_id = 0 lang_id = 0 pad_token_id = 2 bos_token_id = 0 eos_token_id = 1 tie_word_embeddings = True **kwargs )
参数
- vocab_size (
int, optional, defaults to 30145) — BERT 模型的词汇表大小。定义了调用 XLMModel 时传入的inputs_ids可以表示的不同标记的数量。 - emb_dim (
int, optional, defaults to 2048) — 编码器层和池化层的维度。 - n_layer (
int, optional, defaults to 12) — Transformer 编码器中的隐藏层数。 - n_head (
int, optional, defaults to 16) — Transformer 编码器中每个注意力层的注意力头数。 - dropout (
float, optional, defaults to 0.1) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。 - attention_dropout (
float, optional, defaults to 0.1) — 注意力机制的 dropout 概率。 - gelu_activation (
bool, optional, defaults toTrue) — 是否使用 gelu 激活函数而不是 relu。 - sinusoidal_embeddings (
bool, optional, defaults toFalse) — 是否使用正弦位置嵌入而不是绝对位置嵌入。 - causal (
bool, optional, defaults toFalse) — 模型是否应以因果方式运行。因果模型使用三角形注意力掩码,只关注左侧上下文,而不是双向上下文。 - asm (
bool, optional, defaults toFalse) — 是否使用自适应对数 softmax 投影层作为预测层,而不是线性层。 - n_langs (
int, optional, defaults to 1) — 模型处理的语言数量。单语言模型设置为 1。 - use_lang_emb (
bool, optional, defaults toTrue) — 是否使用语言嵌入。一些模型使用额外的语言嵌入,请参阅 多语言模型页面 了解如何使用它们。 - max_position_embeddings (
int, optional, defaults to 512) — 此模型可能用于的最大序列长度。通常为了以防万一会设置一个较大的值(例如 512、1024 或 2048)。 - embed_init_std (
float, optional, defaults to 2048^-0.5) — 用于初始化嵌入矩阵的 truncated_normal_initializer 的标准差。 - init_std (
int, optional, defaults to 50257) — 用于初始化除嵌入矩阵之外的所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float, optional, defaults to 1e-12) — 层归一化层使用的 epsilon。 - bos_index (
int, optional, defaults to 0) — 词汇表中句子开始标记的索引。 - eos_index (
int, optional, defaults to 1) — 词汇表中句子结束标记的索引。 - pad_index (
int, optional, defaults to 2) — 词汇表中填充标记的索引。 - unk_index (
int, optional, defaults to 3) — 词汇表中未知标记的索引。 - mask_index (
int, optional, defaults to 5) — 词汇表中掩码标记的索引。 - is_encoder(
bool, optional, defaults toTrue) — 初始化的模型是否应为 Vaswani 等人所见的 transformer 编码器或解码器。 - summary_type (
string, optional, defaults to “first”) — 在进行序列摘要时使用的参数。用于序列分类和多项选择模型。必须是以下选项之一:
"last":取最后一个 token 隐藏状态(如 XLNet)。"first":取第一个 token 隐藏状态(如 BERT)。"mean":取所有 token 隐藏状态的平均值。"cls_index":提供一个分类 token 位置的张量(如 GPT/GPT-2)。"attn":目前未实现,使用多头注意力。
- summary_use_proj (
bool, optional, defaults toTrue) — 在进行序列摘要时使用的参数。用于序列分类和多项选择模型。是否在向量提取后添加投影。
- summary_activation (
str, optional) — 在进行序列摘要时使用的参数。用于序列分类和多项选择模型。传入
"tanh"以对输出应用 tanh 激活函数,任何其他值将导致不应用激活函数。 - summary_proj_to_labels (
bool, optional, defaults toTrue) — 用于序列分类和多项选择模型。投影输出应具有
config.num_labels还是config.hidden_size类。 - summary_first_dropout (
float, optional, defaults to 0.1) — 用于序列分类和多项选择模型。投影和激活后的 dropout 比率。
- start_n_top (
int, optional, defaults to 5) — 用于 SQuAD 评估脚本。 - end_n_top (
int, optional, defaults to 5) — 用于 SQuAD 评估脚本。 - mask_token_id (
int, optional, defaults to 0) — 模型无关的参数,用于在 MLM 上下文中生成文本时识别被掩盖的 token。 - lang_id (
int, optional, defaults to 1) — 模型使用的语言 ID。此参数用于生成给定语言的文本。
这是用于存储 XLMModel 配置的配置类。它用于根据指定的参数实例化 XLM 模型,定义模型架构。使用默认值实例化配置将生成与 FacebookAI/xlm-mlm-en-2048 架构相似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PreTrainedConfig 的文档。
示例
>>> from transformers import XLMConfig, XLMModel
>>> # Initializing a XLM configuration
>>> configuration = XLMConfig()
>>> # Initializing a model (with random weights) from the configuration
>>> model = XLMModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configXLMTokenizer
class transformers.XLMTokenizer
< source >( vocab_file merges_file unk_token = '<unk>' bos_token = '<s>' sep_token = '</s>' pad_token = '<pad>' cls_token = '</s>' mask_token = '<special1>' additional_special_tokens = ['<special0>', '<special1>', '<special2>', '<special3>', '<special4>', '<special5>', '<special6>', '<special7>', '<special8>', '<special9>'] lang2id = None id2lang = None do_lowercase_and_remove_accent = True **kwargs )
参数
- vocab_file (
str) — 词汇表文件。 - merges_file (
str) — 合并文件。 - unk_token (
str, optional, defaults to"<unk>") — 未知 token。词汇表中没有的 token 无法转换为 ID,并设置为此 token。 - bos_token (
str, optional, defaults to"<s>") — 预训练期间使用的序列开始 token。可以用作序列分类 token。使用特殊 token 构建序列时,这不是用于序列开始的 token。使用的 token 是
cls_token。 - sep_token (
str, optional, defaults to"</s>") — 分隔 token,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊 token 构建的序列的最后一个 token。 - pad_token (
str, optional, defaults to"<pad>") — 用于填充的 token,例如在批处理不同长度的序列时使用。 - cls_token (
str, optional, defaults to"</s>") — 分类器 token,用于进行序列分类(对整个序列进行分类,而不是对每个 token 进行分类)。它是使用特殊 token 构建的序列的第一个 token。 - mask_token (
str, optional, defaults to"<special1>") — 用于掩盖值的 token。这是使用掩码语言建模训练此模型时使用的 token。这是模型将尝试预测的 token。 - additional_special_tokens (
List[str], optional, defaults to['<special0>', '<special1>', '<special2>', '<special3>', '<special4>', '<special5>', '<special6>', '<special7>', '<special8>', '<special9>']) — 附加特殊 token 列表。 - lang2id (
Dict[str, int], optional) — 将语言字符串标识符映射到其 ID 的字典。 - id2lang (
Dict[int, str], optional) — 将语言 ID 映射到其字符串标识符的字典。 - do_lowercase_and_remove_accent (
bool, optional, defaults toTrue) — 对 token 进行分词时是否将文本转换为小写并去除重音。
构建 XLM 分词器。基于字节对编码(Byte-Pair Encoding)。分词过程如下:
- 对大多数支持的语言进行 Moses 预处理和分词。
- 针对中文(Jieba)、日文(KyTea)和泰文(PyThaiNLP)的特定语言分词。
- 可选地将所有输入文本转换为小写并规范化。
- 参数 `special_tokens` 和函数 `set_special_tokens` 可用于向词汇表添加额外的符号(如 “classify”)。
- 如果提供了
lang2id属性(对于预训练词汇表会自动设置),则将模型支持的语言映射到其 ID。 - 如果提供了
id2lang属性(对于预训练词汇表会自动设置),则执行反向映射。
此分词器继承自 PreTrainedTokenizer,其中包含大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。
build_inputs_with_special_tokens
< source >( token_ids_0: list token_ids_1: list[int] | None = None already_has_special_tokens: bool = False ) → List[int]
参数
- token_ids_0 (
List[int]) — 要添加特殊 token 的 ID 列表。 - token_ids_1 (
List[int], optional) — 可选的第二个 ID 列表,用于序列对。
返回
List[int]
带有适当特殊标记的输入ID列表。
通过连接和添加特殊词元,为序列分类任务从一个序列或一对序列构建模型输入。XLM 序列具有以下格式
- 单个序列:
<s> X </s> - 序列对:
<s> A </s> B </s>
get_special_tokens_mask
< source >( token_ids_0: list token_ids_1: list[int] | None = None already_has_special_tokens: bool = False ) → List[int]
从没有添加特殊标记的标记列表中检索序列ID。此方法在使用分词器prepare_for_model方法添加特殊标记时调用。
create_token_type_ids_from_sequences
< source >( token_ids_0: list token_ids_1: list[int] | None = None ) → list[int]
为用于序列对分类任务的两个序列创建一个掩码。
此方法根据分词器的配置属性动态构建 token 类型 ID
token_type_ids_pattern: 要使用的模式 ("all_zeros" 或 "bert_style")token_type_ids_include_special_tokens: 在长度计算中是否计入特殊标记
示例
# All zeros pattern (default, used by RoBERTa, BART, etc.)
tokenizer.token_type_ids_pattern = "all_zeros"
# Returns: [0, 0, 0, ...] for both sequences
# BERT-style pattern (first sequence gets 0s, second gets 1s)
tokenizer.token_type_ids_pattern = "bert_style"
# Returns: [0, 0, 0, ..., 1, 1, 1, ...] for sequence pairsXLM 特定输出
class transformers.models.xlm.modeling_xlm.XLMForQuestionAnsweringOutput
< source >( loss: torch.FloatTensor | None = None start_top_log_probs: torch.FloatTensor | None = None start_top_index: torch.LongTensor | None = None end_top_log_probs: torch.FloatTensor | None = None end_top_index: torch.LongTensor | None = None cls_logits: torch.FloatTensor | None = None hidden_states: tuple[torch.FloatTensor, ...] | None = None attentions: tuple[torch.FloatTensor, ...] | None = None )
参数
- loss (
torch.FloatTensorof shape(1,), optional, if bothstart_positionsandend_positionsare provided) — 分类损失,作为起始 token、结束 token(如果提供了 is_impossible 则包括 is_impossible)分类损失的总和。 - start_top_log_probs (
torch.FloatTensorof shape(batch_size, config.start_n_top), optional, returned ifstart_positionsorend_positionsis not provided) — 前 config.start_n_top 个起始 token 可能性(束搜索)的对数概率。 - start_top_index (
torch.LongTensorof shape(batch_size, config.start_n_top), optional, returned ifstart_positionsorend_positionsis not provided) — 前 config.start_n_top 个起始 token 可能性(束搜索)的索引。 - end_top_log_probs (
torch.FloatTensorof shape(batch_size, config.start_n_top * config.end_n_top), optional, returned ifstart_positionsorend_positionsis not provided) — 前config.start_n_top * config.end_n_top个结束 token 可能性(束搜索)的对数概率。 - end_top_index (
torch.LongTensorof shape(batch_size, config.start_n_top * config.end_n_top), optional, returned ifstart_positionsorend_positionsis not provided) — 前config.start_n_top * config.end_n_top个结束 token 可能性(束搜索)的索引。 - cls_logits (
torch.FloatTensorof shape(batch_size,), optional, returned ifstart_positionsorend_positionsis not provided) — 答案的is_impossible标签的对数概率。 - hidden_states (
tuple[torch.FloatTensor, ...] | None.hidden_states, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — 形状为(batch_size, sequence_length, hidden_size)的torch.FloatTensor元组(一个用于嵌入层的输出(如果模型有嵌入层),加上一个用于每个层的输出)。模型在每个层输出的隐藏状态,加上可选的初始嵌入输出。
- attentions (
tuple[torch.FloatTensor, ...] | None.attentions, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — 形状为(batch_size, num_heads, sequence_length, sequence_length)的torch.FloatTensor元组(每个层一个)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
使用 XLMSQuADHead 的问答模型的输出基类。
XLMModel
class transformers.XLMModel
< source >( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )
参数
- config (XLMModel) — 包含所有模型参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
裸 Xlm 模型输出原始隐藏状态,顶部没有特定头部。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None langs: torch.Tensor | None = None token_type_ids: torch.Tensor | None = None position_ids: torch.Tensor | None = None lengths: torch.Tensor | None = None cache: dict[str, torch.Tensor] | None = None inputs_embeds: torch.Tensor | 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.BaseModelOutput or tuple(torch.FloatTensor)
参数
- input_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) — 输入序列 token 在词汇表中的索引。默认情况下将忽略填充。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — 用于避免对填充 token 索引执行注意力的掩码。掩码值选择在[0, 1]之间:- 1 表示**未被掩盖**的 token,
- 0 表示**被掩盖**的 token。
- langs (
torch.LongTensorof shape(batch_size, sequence_length), optional) — A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name to language id mapping is inmodel.config.lang2id(which is a dictionary string to int) and the language id to language name mapping is inmodel.config.id2lang(dictionary int to string).See usage examples detailed in the multilingual documentation.
- token_type_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - lengths (
torch.LongTensorof shape(batch_size,), optional) — Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatibility. Indices selected in[0, ..., input_ids.size(-1)]. - cache (
dict[str, torch.FloatTensor], optional) — Instance ofEncoderDecoderCachethat contains precomputed KV states. Can be used to speed up sequential decoding. - inputs_embeds (
torch.Tensorof 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. - 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.BaseModelOutput 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.BaseModelOutput 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 (XLMConfig) and inputs.
-
last_hidden_state (
torch.FloatTensor, 形状为(batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。 -
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 后的注意力权重,用于计算自注意力头中的加权平均值。
The XLMModel forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
XLMWithLMHeadModel
class transformers.XLMWithLMHeadModel
< source >( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )
参数
- config (XLMWithLMHeadModel) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None langs: torch.Tensor | None = None token_type_ids: torch.Tensor | None = None position_ids: torch.Tensor | None = None lengths: torch.Tensor | None = None cache: dict[str, torch.Tensor] | None = None inputs_embeds: torch.Tensor | None = None labels: torch.Tensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None cache_position: torch.Tensor | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs ) → transformers.modeling_outputs.MaskedLMOutput or tuple(torch.FloatTensor)
参数
- input_ids (
torch.Tensorof 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.Tensorof 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.
- langs (
torch.LongTensorof shape(batch_size, sequence_length), optional) — A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name to language id mapping is inmodel.config.lang2id(which is a dictionary string to int) and the language id to language name mapping is inmodel.config.id2lang(dictionary int to string).See usage examples detailed in the multilingual documentation.
- token_type_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - lengths (
torch.LongTensorof shape(batch_size,), optional) — Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatibility. Indices selected in[0, ..., input_ids.size(-1)]. - cache (
dict[str, torch.FloatTensor], optional) — Instance ofEncoderDecoderCachethat contains precomputed KV states. Can be used to speed up sequential decoding. - inputs_embeds (
torch.Tensorof 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.LongTensorof shape(batch_size, sequence_length), optional) — Labels for language modeling. Note that the labels are shifted inside the model, i.e. you can setlabels = input_idsIndices are selected in[-100, 0, ..., config.vocab_size]All labels set to-100are ignored (masked), the loss is only computed for labels in[0, ..., config.vocab_size] - 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. - 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.MaskedLMOutput 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.MaskedLMOutput 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 (XLMConfig) and inputs.
-
loss (形状为
(1,)的torch.FloatTensor,可选,当提供labels时返回) — 掩码语言建模 (MLM) 损失。 -
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 后的注意力权重,用于计算自注意力头中的加权平均值。
The XLMWithLMHeadModel forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> import torch
>>> from transformers import AutoTokenizer, XLMWithLMHeadModel
>>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> model = XLMWithLMHeadModel.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs, labels=inputs["input_ids"])
>>> loss = outputs.loss
>>> logits = outputs.logitsXLMForSequenceClassification
class transformers.XLMForSequenceClassification
< source >( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )
参数
- config (XLMForSequenceClassification) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None langs: torch.Tensor | None = None token_type_ids: torch.Tensor | None = None position_ids: torch.Tensor | None = None lengths: torch.Tensor | None = None cache: dict[str, torch.Tensor] | None = None inputs_embeds: torch.Tensor | None = None labels: torch.Tensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) → transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor)
参数
- input_ids (
torch.Tensorof 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.Tensorof 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.
- langs (
torch.LongTensorof shape(batch_size, sequence_length), optional) — A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name to language id mapping is inmodel.config.lang2id(which is a dictionary string to int) and the language id to language name mapping is inmodel.config.id2lang(dictionary int to string).See usage examples detailed in the multilingual documentation.
- token_type_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - lengths (
torch.LongTensorof shape(batch_size,), optional) — Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatibility. Indices selected in[0, ..., input_ids.size(-1)]. - cache (
dict[str, torch.FloatTensor], optional) — Instance ofEncoderDecoderCachethat contains precomputed KV states. Can be used to speed up sequential decoding. - inputs_embeds (
torch.Tensorof 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.LongTensorof shape(batch_size,), optional) — Labels for computing the sequence classification/regression loss. Indices should be in[0, ..., config.num_labels - 1]. Ifconfig.num_labels == 1a regression loss is computed (Mean-Square loss), Ifconfig.num_labels > 1a classification loss is computed (Cross-Entropy). - 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) — 是否返回 ModelOutput 对象,而非普通的元组。
返回
transformers.modeling_outputs.SequenceClassifierOutput 或 tuple(torch.FloatTensor)
返回 transformers.modeling_outputs.SequenceClassifierOutput 对象或 torch.FloatTensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其中包含取决于配置 (XLMConfig) 和输入的不同元素。
-
loss (形状为
(1,)的torch.FloatTensor,可选,当提供labels时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。 -
logits (形状为
(batch_size, config.num_labels)的torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(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 后的注意力权重,用于计算自注意力头中的加权平均值。
XLMForSequenceClassification 的 forward 方法,它重写了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
单标签分类示例
>>> import torch
>>> from transformers import AutoTokenizer, XLMForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> model = XLMForSequenceClassification.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_class_id = logits.argmax().item()
>>> model.config.id2label[predicted_class_id]
...
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = XLMForSequenceClassification.from_pretrained("FacebookAI/xlm-mlm-en-2048", num_labels=num_labels)
>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...多标签分类示例
>>> import torch
>>> from transformers import AutoTokenizer, XLMForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> model = XLMForSequenceClassification.from_pretrained("FacebookAI/xlm-mlm-en-2048", problem_type="multi_label_classification")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5]
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = XLMForSequenceClassification.from_pretrained(
... "FacebookAI/xlm-mlm-en-2048", num_labels=num_labels, problem_type="multi_label_classification"
... )
>>> labels = torch.sum(
... torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1
... ).to(torch.float)
>>> loss = model(**inputs, labels=labels).lossXLMForMultipleChoice
class transformers.XLMForMultipleChoice
< source >( config *inputs **kwargs )
参数
- config (XLMForMultipleChoice) — 包含模型所有参数的模型配置类。使用配置文件初始化模型不会加载与模型相关的权重,只会加载配置。请查阅 from_pretrained() 方法来加载模型权重。
XLM 模型,顶部带有多项选择分类头(在池化输出之上有一个线性层和一个 softmax),例如用于 RocStories/SWAG 任务。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None langs: torch.Tensor | None = None token_type_ids: torch.Tensor | None = None position_ids: torch.Tensor | None = None lengths: torch.Tensor | None = None cache: dict[str, torch.Tensor] | None = None inputs_embeds: torch.Tensor | None = None labels: torch.Tensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) → transformers.modeling_outputs.MultipleChoiceModelOutput or tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor,形状为(batch_size, num_choices, sequence_length)) — 词汇表中输入序列 token 的索引。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor,形状为(batch_size, sequence_length), optional) — 用于避免在填充 token 索引上执行注意力的掩码。掩码值选择在[0, 1]中:- 1 表示**未被掩码**的 token,
- 0 表示**被掩码**的 token。
- langs (
torch.LongTensor,形状为(batch_size, num_choices, sequence_length), optional) — 用于指示输入中每个 token 语言的并行 token 序列。索引是语言 ID,可以通过使用模型配置中提供的两个转换映射(仅适用于多语言模型)从语言名称中获取。更具体地说,*语言名称到语言 ID* 的映射在model.config.lang2id(一个字符串到 int 的字典)中,*语言 ID 到语言名称* 的映射在model.config.id2lang(一个 int 到字符串的字典)中。有关详细用法示例,请参阅 多语言文档。
- token_type_ids (
torch.LongTensor,形状为(batch_size, num_choices, sequence_length), optional) — 分段 token 索引,用于指示输入的第一个和第二个部分。索引选择在[0, 1]中:- 0 对应于 *句子 A* token,
- 1 对应于 *句子 B* token。
- position_ids (
torch.LongTensor,形状为(batch_size, num_choices, sequence_length), optional) — 位置嵌入中每个输入序列 token 位置的索引。选择范围为[0, config.max_position_embeddings - 1]。 - lengths (
torch.LongTensor,形状为(batch_size,), optional) — 每句话的长度,可用于避免在填充 token 索引上执行注意力。您也可以使用 attention_mask 达到同样的效果(见上文),此处保留是为了兼容性。索引选择范围为[0, ..., input_ids.size(-1)]。 - cache (
dict[str, torch.FloatTensor], optional) —EncoderDecoderCache的实例,包含预先计算的 KV 状态。可用于加快顺序解码速度。 - inputs_embeds (
torch.FloatTensor,形状为(batch_size, num_choices, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传入嵌入表示而不是input_ids。如果您希望对如何将input_ids索引转换为关联向量有比模型内部嵌入查找矩阵更多的控制,这很有用。 - labels (
torch.LongTensor,形状为(batch_size,), optional) — 用于计算多项选择分类损失的标签。索引应在[0, ..., num_choices-1]范围内,其中num_choices是输入张量第二维的大小。(请参阅上面的input_ids) - output_attentions (
bool, optional) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的attentions。 - output_hidden_states (
bool, optional) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的hidden_states。 - return_dict (
bool, optional) — 是否返回 ModelOutput 对象,而非普通的元组。
返回
transformers.modeling_outputs.MultipleChoiceModelOutput 或 tuple(torch.FloatTensor)
返回 transformers.modeling_outputs.MultipleChoiceModelOutput 对象或 torch.FloatTensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其中包含取决于配置 (XLMConfig) 和输入的不同元素。
-
loss (形状为 (1,) 的
torch.FloatTensor,可选,当提供labels时返回) — 分类损失。 -
logits (形状为
(batch_size, num_choices)的torch.FloatTensor) — num_choices 是输入张量的第二维大小。(请参阅上面的 input_ids)。分类分数(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 后的注意力权重,用于计算自注意力头中的加权平均值。
XLMForMultipleChoice 的 forward 方法,它重写了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, XLMForMultipleChoice
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> model = XLMForMultipleChoice.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> choice0 = "It is eaten with a fork and a knife."
>>> choice1 = "It is eaten while held in the hand."
>>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1
>>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="pt", padding=True)
>>> outputs = model(**{k: v.unsqueeze(0) for k, v in encoding.items()}, labels=labels) # batch size is 1
>>> # the linear classifier still needs to be trained
>>> loss = outputs.loss
>>> logits = outputs.logitsXLMForTokenClassification
class transformers.XLMForTokenClassification
< source >( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )
参数
- config (XLMForTokenClassification) — 包含模型所有参数的模型配置类。使用配置文件初始化模型不会加载与模型相关的权重,只会加载配置。请查阅 from_pretrained() 方法来加载模型权重。
Xlm transformer,顶部带有 token 分类头(在隐藏状态输出之上有一个线性层),例如用于命名实体识别 (NER) 任务。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None langs: torch.Tensor | None = None token_type_ids: torch.Tensor | None = None position_ids: torch.Tensor | None = None lengths: torch.Tensor | None = None cache: dict[str, torch.Tensor] | None = None inputs_embeds: torch.Tensor | None = None labels: torch.Tensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) → transformers.modeling_outputs.TokenClassifierOutput or tuple(torch.FloatTensor)
参数
- input_ids (
torch.Tensor,形状为(batch_size, sequence_length), optional) — 词汇表中输入序列 token 的索引。默认情况下会忽略填充。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor,形状为(batch_size, sequence_length), optional) — 用于避免在填充 token 索引上执行注意力的掩码。掩码值选择在[0, 1]中:- 1 表示**未被掩码**的 token,
- 0 表示**被掩码**的 token。
- langs (
torch.LongTensor,形状为(batch_size, sequence_length), optional) — 用于指示输入中每个 token 语言的并行 token 序列。索引是语言 ID,可以通过使用模型配置中提供的两个转换映射(仅适用于多语言模型)从语言名称中获取。更具体地说,*语言名称到语言 ID* 的映射在model.config.lang2id(一个字符串到 int 的字典)中,*语言 ID 到语言名称* 的映射在model.config.id2lang(一个 int 到字符串的字典)中。有关详细用法示例,请参阅 多语言文档。
- token_type_ids (
torch.Tensor,形状为(batch_size, sequence_length), optional) — 分段 token 索引,用于指示输入的第一个和第二个部分。索引选择在[0, 1]中:- 0 对应于 *句子 A* token,
- 1 对应于 *句子 B* token。
- position_ids (
torch.Tensor,形状为(batch_size, sequence_length), optional) — 位置嵌入中每个输入序列 token 位置的索引。选择范围为[0, config.n_positions - 1]。 - lengths (
torch.LongTensor,形状为(batch_size,), optional) — 每句话的长度,可用于避免在填充 token 索引上执行注意力。您也可以使用 attention_mask 达到同样的效果(见上文),此处保留是为了兼容性。索引选择范围为[0, ..., input_ids.size(-1)]。 - cache (
dict[str, torch.FloatTensor], optional) —EncoderDecoderCache的实例,包含预先计算的 KV 状态。可用于加快顺序解码速度。 - inputs_embeds (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传入嵌入表示而不是input_ids。如果您希望对如何将input_ids索引转换为关联向量有比模型内部嵌入查找矩阵更多的控制,这很有用。 - labels (
torch.LongTensor,形状为(batch_size, sequence_length), optional) — 用于计算 token 分类损失的标签。索引应在[0, ..., config.num_labels - 1]范围内。 - output_attentions (
bool, optional) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的attentions。 - output_hidden_states (
bool, optional) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的hidden_states。 - return_dict (
bool, optional) — 是否返回 ModelOutput 对象,而非普通的元组。
返回
transformers.modeling_outputs.TokenClassifierOutput 或 tuple(torch.FloatTensor)
返回 transformers.modeling_outputs.TokenClassifierOutput 对象或 torch.FloatTensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其中包含取决于配置 (XLMConfig) 和输入的不同元素。
-
loss (形状为
(1,)的torch.FloatTensor,可选,当提供labels时返回) — 分类损失。 -
logits (形状为
(batch_size, sequence_length, config.num_labels)的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 后的注意力权重,用于计算自注意力头中的加权平均值。
XLMForTokenClassification 的 forward 方法,它重写了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, XLMForTokenClassification
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> model = XLMForTokenClassification.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> inputs = tokenizer(
... "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
... )
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_token_class_ids = logits.argmax(-1)
>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]
>>> predicted_tokens_classes
...
>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...XLMForQuestionAnsweringSimple
class transformers.XLMForQuestionAnsweringSimple
< source >( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )
参数
- config (XLMForQuestionAnsweringSimple) — 包含模型所有参数的模型配置类。使用配置文件初始化模型不会加载与模型相关的权重,只会加载配置。请查阅 from_pretrained() 方法来加载模型权重。
XLM 模型,顶部带有用于 SQuAD 等抽取式问答任务的 span 分类头(在隐藏状态输出之上有一个线性层,用于计算 span start logits 和 span end logits)。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None langs: torch.Tensor | None = None token_type_ids: torch.Tensor | None = None position_ids: torch.Tensor | None = None lengths: torch.Tensor | None = None cache: dict[str, torch.Tensor] | None = None inputs_embeds: torch.Tensor | None = None start_positions: torch.Tensor | None = None end_positions: torch.Tensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) → transformers.modeling_outputs.QuestionAnsweringModelOutput or tuple(torch.FloatTensor)
参数
- input_ids (
torch.Tensor,形状为(batch_size, sequence_length), optional) — 词汇表中输入序列 token 的索引。默认情况下会忽略填充。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor,形状为(batch_size, sequence_length), optional) — 用于避免在填充 token 索引上执行注意力的掩码。掩码值选择在[0, 1]中:- 1 表示**未被掩码**的 token,
- 0 表示**被掩码**的 token。
- langs (
torch.LongTensor,形状为(batch_size, sequence_length), optional) — 用于指示输入中每个 token 语言的并行 token 序列。索引是语言 ID,可以通过使用模型配置中提供的两个转换映射(仅适用于多语言模型)从语言名称中获取。更具体地说,*语言名称到语言 ID* 的映射在model.config.lang2id(一个字符串到 int 的字典)中,*语言 ID 到语言名称* 的映射在model.config.id2lang(一个 int 到字符串的字典)中。有关详细用法示例,请参阅 多语言文档。
- token_type_ids (
torch.Tensor,形状为(batch_size, sequence_length), optional) — 分段 token 索引,用于指示输入的第一个和第二个部分。索引选择在[0, 1]中:- 0 对应于 *句子 A* token,
- 1 对应于 *句子 B* token。
- position_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) — 输入序列中每个 token 在位置嵌入中的位置索引。选择范围为[0, config.n_positions - 1]。 - lengths (
torch.LongTensorof shape(batch_size,), optional) — 每句话的长度,可用于避免对填充 token 索引执行注意力操作。您也可以使用 attention_mask 达到同样的效果(见上文),这里保留是为了兼容性。选择范围为[0, ..., input_ids.size(-1)]。 - cache (
dict[str, torch.FloatTensor], optional) —EncoderDecoderCache的实例,包含预先计算的 KV 状态。可用于加速顺序解码。 - inputs_embeds (
torch.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — 可选参数,您可以直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相关向量有比模型内部嵌入查找矩阵更多的控制,这很有用。 - start_positions (
torch.Tensorof shape(batch_size,), optional) — 用于计算 token 分类损失的标注范围起点的标签位置(索引)。位置被限制在序列长度 (sequence_length) 范围内。序列以外的位置不计入损失计算。 - end_positions (
torch.Tensorof shape(batch_size,), optional) — 用于计算 token 分类损失的标注范围结束点的标签位置(索引)。位置被限制在序列长度 (sequence_length) 范围内。序列以外的位置不计入损失计算。 - output_attentions (
bool, optional) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool, optional) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, optional) — 是否返回 ModelOutput 而不是普通的元组。
返回
transformers.modeling_outputs.QuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.QuestionAnsweringModelOutput or a tuple of torch.FloatTensor (如果传入 return_dict=False 或 config.return_dict=False) ,包含根据配置 (XLMConfig) 和输入的不同元素。
-
loss (
torch.FloatTensorof shape(1,), 可选, 当提供labels时返回) — 总范围提取损失是起始位置和结束位置的交叉熵之和。 -
start_logits (
torch.FloatTensorof shape(batch_size, sequence_length)) — 范围起始分数(SoftMax 之前)。 -
end_logits (
torch.FloatTensorof shape(batch_size, sequence_length)) — 范围结束分数(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 后的注意力权重,用于计算自注意力头中的加权平均值。
XLMForQuestionAnsweringSimple 的前向传播方法,重写了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, XLMForQuestionAnsweringSimple
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> model = XLMForQuestionAnsweringSimple.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
>>> inputs = tokenizer(question, text, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> answer_start_index = outputs.start_logits.argmax()
>>> answer_end_index = outputs.end_logits.argmax()
>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
>>> tokenizer.decode(predict_answer_tokens, skip_special_tokens=True)
...
>>> # target is "nice puppet"
>>> target_start_index = torch.tensor([14])
>>> target_end_index = torch.tensor([15])
>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = outputs.loss
>>> round(loss.item(), 2)
...XLMForQuestionAnswering
class transformers.XLMForQuestionAnswering
< source >( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )
参数
- config (XLMForQuestionAnswering) — 模型的配置类,包含模型的所有参数。使用配置文件初始化模型不会加载与模型相关的权重,只会加载配置。要加载模型权重,请查看 from_pretrained() 方法。
XLM transformer 模型,顶部带有一个用于抽取式问答任务(如 SQuAD)的 span 分类头(在隐藏状态输出之上添加一个线性层来计算 span start logits 和 span end logits)。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None langs: torch.Tensor | None = None token_type_ids: torch.Tensor | None = None position_ids: torch.Tensor | None = None lengths: torch.Tensor | None = None cache: dict[str, torch.Tensor] | None = None inputs_embeds: torch.Tensor | None = None start_positions: torch.Tensor | None = None end_positions: torch.Tensor | None = None is_impossible: torch.Tensor | None = None cls_index: torch.Tensor | None = None p_mask: torch.Tensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) → transformers.models.xlm.modeling_xlm.XLMForQuestionAnsweringOutput or tuple(torch.FloatTensor)
参数
- input_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) — 输入序列 token 在词汇表中的索引。默认情况下将忽略填充。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — 用于避免对填充 token 索引执行注意力操作的掩码。掩码值选择范围为[0, 1]:- 1 表示 未被掩码 的 token,
- 0 表示 被掩码 的 token。
- langs (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 与输入序列并行的 token 序列,用于指示输入中每个 token 的语言。索引是语言 ID,可以通过使用模型配置中提供的两个转换映射从语言名称中获取(仅为多语言模型提供)。更具体地说,*语言名称到语言 ID* 的映射在model.config.lang2id(一个字符串到整数的字典)中,而 *语言 ID 到语言名称* 的映射在model.config.id2lang(一个整数到字符串的字典)中。请参阅 多语言文档 中详细的使用示例。
- token_type_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) — 用于指示输入第一部分和第二部分的段 token 索引。索引选择范围为[0, 1]:- 0 对应于 *句子 A* token,
- 1 对应于 *句子 B* token。
- position_ids (
torch.Tensorof shape(batch_size, sequence_length), optional) — 输入序列中每个 token 在位置嵌入中的位置索引。选择范围为[0, config.n_positions - 1]。 - lengths (
torch.LongTensorof shape(batch_size,), optional) — 每句话的长度,可用于避免对填充 token 索引执行注意力操作。您也可以使用 attention_mask 达到同样的效果(见上文),这里保留是为了兼容性。选择范围为[0, ..., input_ids.size(-1)]。 - cache (
dict[str, torch.FloatTensor], optional) —EncoderDecoderCache的实例,包含预先计算的 KV 状态。可用于加速顺序解码。 - inputs_embeds (
torch.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — 可选参数,您可以直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相关向量有比模型内部嵌入查找矩阵更多的控制,这很有用。 - start_positions (
torch.Tensorof shape(batch_size,), optional) — 用于计算 token 分类损失的标注范围起点的标签位置(索引)。位置被限制在序列长度 (sequence_length) 范围内。序列以外的位置不计入损失计算。 - end_positions (
torch.Tensorof shape(batch_size,), optional) — 用于计算 token 分类损失的标注范围结束点的标签位置(索引)。位置被限制在序列长度 (sequence_length) 范围内。序列以外的位置不计入损失计算。 - is_impossible (
torch.LongTensorof shape(batch_size,), optional) — 用于标注问题是否有答案(SQuAD 2.0)的标签。 - cls_index (
torch.LongTensorof shape(batch_size,), optional) — 用于计算答案合理性时作为输入的分类 token 位置(索引)的标签。 - p_mask (
torch.FloatTensorof shape(batch_size, sequence_length), optional) — 可选掩码,用于指示不能出现在答案中的 token(例如 [CLS]、[PAD] 等)。1.0 表示 token 应该被掩码,0.0 表示 token 未被掩码。 - output_attentions (
bool, optional) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool, optional) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, optional) — 是否返回 ModelOutput 而不是普通的元组。
返回
transformers.models.xlm.modeling_xlm.XLMForQuestionAnsweringOutput or tuple(torch.FloatTensor)
A transformers.models.xlm.modeling_xlm.XLMForQuestionAnsweringOutput or a tuple of torch.FloatTensor (如果传入 return_dict=False 或 config.return_dict=False) ,包含根据配置 (XLMConfig) 和输入的不同元素。
-
loss (
torch.FloatTensorof shape(1,), optional, 如果同时提供start_positions和end_positions则返回) — 分类损失,是起始 token、结束 token(如果提供则包括 is_impossible)分类损失的总和。 -
start_top_log_probs (
torch.FloatTensorof shape(batch_size, config.start_n_top), optional, 如果未提供start_positions或end_positions则返回) — 前 config.start_n_top 个起始 token 可能性(束搜索)的对数概率。 -
start_top_index (
torch.LongTensorof shape(batch_size, config.start_n_top), optional, 如果未提供start_positions或end_positions则返回) — 前 config.start_n_top 个起始 token 可能性(束搜索)的索引。 -
end_top_log_probs (
torch.FloatTensorof shape(batch_size, config.start_n_top * config.end_n_top), optional, 如果未提供start_positions或end_positions则返回) — 前config.start_n_top * config.end_n_top个结束 token 可能性(束搜索)的对数概率。 -
end_top_index (
torch.LongTensorof shape(batch_size, config.start_n_top * config.end_n_top), optional, 如果未提供start_positions或end_positions则返回) — 前config.start_n_top * config.end_n_top个结束 token 可能性(束搜索)的索引。 -
cls_logits (
torch.FloatTensorof shape(batch_size,), optional, 如果未提供start_positions或end_positions则返回) — 答案的is_impossible标签的对数概率。 -
hidden_states (
tuple[torch.FloatTensor, ...] | None.hidden_states, 当传入output_hidden_states=True或当config.output_hidden_states=True时返回) — 形状为(batch_size, sequence_length, hidden_size)的torch.FloatTensor元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 每个层的输出)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple[torch.FloatTensor, ...] | None.attentions, 当传入output_attentions=True或当config.output_attentions=True时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)的torch.FloatTensor元组(每个层一个)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
XLMForQuestionAnswering 的前向传播方法,重写了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, XLMForQuestionAnswering
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> model = XLMForQuestionAnswering.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(
... 0
... ) # Batch size 1
>>> start_positions = torch.tensor([1])
>>> end_positions = torch.tensor([3])
>>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
>>> loss = outputs.loss