Transformers 文档

FlauBERT

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2019-12-11 发布,并于 2020-11-16 添加到 Hugging Face Transformers。

FlauBERT

PyTorch

概述

FlauBERT 模型由 Hang Le 等人在论文 FlauBERT: Unsupervised Language Model Pre-training for French 中提出。它是一个使用掩码语言模型(MLM)目标(类似于 BERT)进行预训练的 Transformer 模型。

论文摘要如下:

语言模型已成为在许多不同自然语言处理(NLP)任务中取得最先进结果的关键步骤。利用如今海量的无标签文本,它们提供了一种有效的方法来预训练连续词表示,这些表示可以与句子级别的上下文一起针对下游任务进行微调。这已通过英文语境化表示(Dai and Le, 2015; Peters et al., 2018; Howard and Ruder, 2018; Radford et al., 2018; Devlin et al., 2019; Yang et al., 2019b)得到了广泛证明。在本文中,我们介绍并分享 FlauBERT,一个在海量异构法语语料库上学习的模型。使用新的 CNRS(法国国家科学研究中心)Jean Zay 超级计算机训练了不同规模的模型。我们将法语语言模型应用于各种 NLP 任务(文本分类、释义、自然语言推理、解析、词义消歧),并表明它们大多数时候都优于其他预训练方法。FlauBERT 的不同版本以及一个用于下游任务的统一评估协议 FLUE(French Language Understanding Evaluation)已与研究界共享,以便进行更具可复现性的法语 NLP 实验。

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

技巧

  • 与 RoBERTa 类似,但没有句子排序预测(因此仅在 MLM 目标上进行训练)。

资源

FlaubertConfig

class transformers.FlaubertConfig

< >

( pre_norm = False layerdrop = 0.0 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 bos_index = 0 eos_index = 1 pad_index = 2 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 )

参数

  • pre_norm (bool, optional, 默认为 False) — 是否在每个层的注意力之后、前馈层之前应用层归一化(Vaswani et al., Tensor2Tensor for Neural Machine Translation. 2018)。
  • layerdrop (float, optional, 默认为 0.0) — 训练期间丢弃层的概率(Fan et al., Reducing Transformer Depth on Demand with Structured Dropout. ICLR 2020)。
  • vocab_size (int, optional, 默认为 30145) — FlauBERT 模型词汇表大小。定义调用 FlaubertModel 时传入的 inputs_ids 可以表示的不同 token 的数量。
  • emb_dim (int, optional, 默认为 2048) — 编码器层和池化层的维度。
  • n_layer (int, optional, 默认为 12) — Transformer 编码器中的隐藏层数量。
  • n_head (int, optional, 默认为 16) — Transformer 编码器中每个注意力层的注意力头数量。
  • dropout (float, optional, 默认为 0.1) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。
  • attention_dropout (float, optional, 默认为 0.1) — 注意力机制的 dropout 概率。
  • gelu_activation (bool, optional, 默认为 True) — 是否使用 gelu 激活函数而不是 relu
  • sinusoidal_embeddings (bool, optional, 默认为 False) — 是否使用正弦位置嵌入而不是绝对位置嵌入。
  • causal (bool, optional, 默认为 False) — 模型是否应采用因果行为。因果模型使用三角注意力掩码,以便仅关注左侧上下文而不是双向上下文。
  • asm (bool, optional, 默认为 False) — 是否使用自适应 log-softmax 投影层而不是线性层进行预测。
  • n_langs (int, optional, 默认为 1) — 模型处理的语言数量。单语模型设置为 1。
  • use_lang_emb (bool, optional, 默认为 True) — 是否使用语言嵌入。某些模型使用额外的语言嵌入,请参阅 多语言模型页面 以了解如何使用它们。
  • max_position_embeddings (int, optional, 默认为 512) — 该模型可能使用的最大序列长度。通常设置得大一些以防万一(例如,512、1024 或 2048)。
  • embed_init_std (float, optional, 默认为 2048^-0.5) — 用于初始化嵌入矩阵的 truncated_normal_initializer 的标准差。
  • init_std (int, optional, 默认为 50257) — 用于初始化除嵌入矩阵外的所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, optional, 默认为 1e-12) — 层归一化层使用的 epsilon 值。
  • bos_index (int, optional, defaults to 0) — 句子起始 token 在词汇表中的索引。
  • eos_index (int, optional, defaults to 1) — 句子结束 token 在词汇表中的索引。
  • pad_index (int, optional, defaults to 2) — 填充 token 在词汇表中的索引。
  • unk_index (int, optional, defaults to 3) — 未知 token 在词汇表中的索引。
  • mask_index (int, optional, defaults to 5) — 掩码 token 在词汇表中的索引。
  • is_encoder(bool, optional, defaults to True) — 初始化模型时,是 transformer 编码器还是解码器,如 Vaswani 等人所述。
  • summary_type (string, optional, defaults to “first”) — 在进行序列摘要时使用的参数。用于序列分类和多项选择模型。

    必须是以下选项之一:
    • "last":取最后一个 token 的隐藏状态(类似 XLNet)。
    • "first":取第一个 token 的隐藏状态(类似 BERT)。
    • "mean":取所有 token 隐藏状态的平均值。
    • "cls_index":提供分类 token 位置的 Tensor(类似 GPT/GPT-2)。
    • "attn":目前未实现,使用多头注意力。
  • summary_use_proj (bool, optional, defaults to True) — 在进行序列摘要时使用的参数。用于序列分类和多项选择模型。

    是否在向量提取后添加投影。

  • summary_activation (str, optional) — 在进行序列摘要时使用的参数。用于序列分类和多项选择模型。

    传递 "tanh" 以实现 tanh 激活到输出,其他任何值都将导致没有激活。

  • summary_proj_to_labels (bool, optional, defaults to True) — 用于序列分类和多项选择模型。

    投影输出是否应具有 config.num_labelsconfig.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。此参数用于生成给定语言的文本。

这是用于存储 FlaubertModel 配置的配置类。它用于根据指定的参数实例化一个 FlauBERT 模型,定义模型的架构。使用默认值实例化配置将生成与 FlauBERT flaubert/flaubert_base_uncased 架构类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PreTrainedConfig 的文档。

FlaubertTokenizer

class transformers.FlaubertTokenizer

< >

( vocab_file merges_file do_lowercase = False 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 **kwargs )

参数

  • vocab_file (str) — 词汇文件。
  • merges_file (str) — merges 文件。
  • do_lowercase (bool, optional, defaults to False) — 控制小写。
  • unk_token (str, optional, defaults to "<unk>") — 未知 token。词汇表中不存在的 token 将被设置为此 token。
  • bos_token (str, optional, defaults to "<s>") — 在预训练期间使用的起始序列 token。可用于序列分类器 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 到其字符串标识符的字典。

构建一个 Flaubert tokenizer。基于 Byte-Pair Encoding。标记化过程如下:

  • Moses 预处理和标记化。
  • 规范化所有输入文本。
  • 参数 `special_tokens` 和函数 `set_special_tokens` 可用于向词汇表添加额外的符号(如 “classify”)。
  • 参数 do_lowercase 控制小写(对于预训练的词汇表自动设置)。

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

build_inputs_with_special_tokens

< >

( 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>

convert_tokens_to_string

< >

( tokens )

将标记序列(字符串)转换为单个字符串。

get_special_tokens_mask

< >

( token_ids_0: list token_ids_1: list[int] | None = None already_has_special_tokens: bool = False ) List[int]

参数

  • token_ids_0 (List[int]) — ID 列表。
  • token_ids_1 (List[int], optional) — 第二个 ID 列表,用于序列对。
  • already_has_special_tokens (bool, optional, defaults to False) — token 列表是否已为模型格式化了特殊 token。

返回

List[int]

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

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

FlaubertModel

class transformers.FlaubertModel

< >

( 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 (FlaubertModel) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。

一个 Flaubert 模型,输出原始的隐藏状态,上面没有特定的头。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.FloatTensor | None = None langs: torch.Tensor | None = None token_type_ids: torch.LongTensor | None = None position_ids: torch.LongTensor | None = None lengths: torch.LongTensor | None = None cache: dict[str, torch.FloatTensor] | None = None inputs_embeds: torch.FloatTensor | 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.BaseModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 词汇表中输入序列 token 的索引。默认情况下将忽略填充。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    输入 ID 是什么?

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — 用于避免对填充 token 索引执行注意力的掩码:
    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    注意力掩码是什么?

  • langs (torch.LongTensor of shape (batch_size, sequence_length), optional) — 一个并行的 token 序列,用于指示输入中每个 token 的语言。索引是语言 ID,可以通过模型配置中的两个转换映射获得(仅多语言模型提供)。具体来说,语言名称到语言 ID 的映射在 model.config.lang2id(一个字典,字符串到 int)中,语言 ID 到语言名称 的映射在 model.config.id2lang(字典 int 到 string)中。

    请参阅 多语言文档 中详细的使用示例。

  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于指示输入的第一部分和第二部分的片段 token 索引。索引选择在 [0, 1] 中:
    • 0 对应于句子 A token,
    • 1 对应于句子 B token。

    Token 类型 ID 是什么?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 位置嵌入中每个输入序列 token 的位置索引。选择范围在 [0, config.n_positions - 1]

    位置 ID 是什么?

  • lengths (torch.LongTensor of shape (batch_size,), optional) — 每个句子的长度,可用于避免对填充 token 索引执行注意力。您也可以使用 attention_mask 来达到相同的结果(见上文),此处保留是为了兼容。索引选择在 [0, ..., input_ids.size(-1)]
  • cache (dict[str, torch.FloatTensor], optional) — 包含模型计算的预计算隐藏状态(注意力块中的键和值)的字典(字符串到 torch.FloatTensor)。可用于加速顺序解码。在正向传递期间,字典对象将被就地修改,以添加新计算的隐藏状态。
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以通过直接传递嵌入表示来代替传递 input_ids。如果您想对如何将 input_ids 索引转换为关联向量有更多控制,而不是使用模型的内部嵌入查找矩阵,则很有用。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通元组。
  • cache_position (torch.Tensor of shape (sequence_length), optional) — 描述输入序列 token 在序列中位置的张量。与 position_ids 不同,此张量不受填充的影响。它用于将缓存更新到正确的位置并推断完整序列长度。

返回

transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

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

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

FlaubertModel 的正向方法,覆盖 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

FlaubertWithLMHeadModel

class transformers.FlaubertWithLMHeadModel

< >

( 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 (FlaubertWithLMHeadModel) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。

一个 Flaubert 模型 transformer,顶部带有一个语言建模头(具有与输入嵌入权重绑定的线性层)。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( 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.MaskedLMOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.Tensor, shape (batch_size, sequence_length), optional) — 词汇表中输入序列 token 的索引。默认情况下会忽略 padding。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是 input IDs?

  • attention_mask (torch.Tensor, shape (batch_size, sequence_length), optional) — 用于避免在 padding token 索引上执行 attention 的掩码。掩码值选择在 [0, 1] 中:

    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    什么是 attention masks?

  • langs (torch.LongTensor, shape (batch_size, sequence_length), optional) — 一个并行 token 序列,用于指示输入中每个 token 的语言。索引是语言 ID,可以通过模型配置中提供的两个转换映射(仅适用于多语言模型)从语言名称获取。具体来说,语言名称到语言 ID 的映射在 model.config.lang2id(这是一个字典 string 到 int)中,而语言 ID 到语言名称的映射在 model.config.id2lang(字典 int 到 string)中。

    请参阅 多语言文档中详述的使用示例。

  • token_type_ids (torch.Tensor, shape (batch_size, sequence_length), optional) — 用于指示输入的第一个和第二个部分的 token 类型 ID。索引选择在 [0, 1] 中:

    • 0 对应于句子 A token,
    • 1 对应于句子 B token。

    什么是 token type IDs?

  • position_ids (torch.Tensor, shape (batch_size, sequence_length), optional) — 位置嵌入中每个输入序列 token 的位置索引。选择范围为 [0, config.n_positions - 1]

    什么是 position IDs?

  • lengths (torch.LongTensor, shape (batch_size,), optional) — 每个句子的长度,可用于避免在 padding token 索引上执行 attention。您也可以使用 attention_mask 来获得相同的结果(见上文),为兼容性保留此参数。索引选择范围为 [0, ..., input_ids.size(-1)]
  • cache (dict[str, torch.FloatTensor], optional) — 包含预计算的 hidden-states(attention 块中的 key 和 values)的字典,这些 hidden-states 是由模型计算得出的(参见下面的 cache 输出)。可用于加速顺序解码。在 forward pass 期间,字典对象将被原地修改以添加新计算的 hidden-states。
  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您想比模型内部嵌入查找矩阵拥有更多控制权来将 input_ids 索引转换为关联向量,这一点很有用。
  • labels (torch.LongTensor, shape (batch_size, sequence_length), optional) — 用于语言建模的标签。请注意,标签会在模型内部进行移位,即您可以设置 labels = input_ids。索引选择在 [-100, 0, ..., config.vocab_size] 中。所有设置为 -100 的标签都会被忽略(掩码),损失只为 [0, ..., config.vocab_size] 中的标签计算。
  • output_attentions (bool, optional) — 是否返回所有 attention 层的 attentions 张量。有关更多详细信息,请参阅返回的张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的 hidden states。有关更多详细信息,请参阅返回的张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_outputs.MaskedLMOutputtuple(torch.FloatTensor)

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

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

FlaubertWithLMHeadModel 的 forward 方法,它覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> import torch
>>> from transformers import AutoTokenizer, FlaubertWithLMHeadModel

>>> tokenizer = AutoTokenizer.from_pretrained("flaubert/flaubert_base_uncased")
>>> model = FlaubertWithLMHeadModel.from_pretrained("flaubert/flaubert_base_uncased")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs, labels=inputs["input_ids"])
>>> loss = outputs.loss
>>> logits = outputs.logits

FlaubertForSequenceClassification

class transformers.FlaubertForSequenceClassification

< >

( 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 (transformers.FlaubertForSequenceClassification) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。

Flaubert 模型,顶部有一个序列分类/回归头(一个位于池化输出之上的线性层),例如用于 GLUE 任务。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( 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.SequenceClassifierOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.Tensor, shape (batch_size, sequence_length), optional) — 词汇表中输入序列 token 的索引。默认情况下会忽略 padding。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是 input IDs?

  • attention_mask (torch.Tensor, shape (batch_size, sequence_length), optional) — 用于避免在 padding token 索引上执行 attention 的掩码。掩码值选择在 [0, 1] 中:

    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    什么是 attention masks?

  • langs (torch.LongTensor, shape (batch_size, sequence_length), optional) — 一个并行 token 序列,用于指示输入中每个 token 的语言。索引是语言 ID,可以通过模型配置中提供的两个转换映射(仅适用于多语言模型)从语言名称获取。具体来说,语言名称到语言 ID 的映射在 model.config.lang2id(这是一个字典 string 到 int)中,而语言 ID 到语言名称的映射在 model.config.id2lang(字典 int 到 string)中。

    请参阅 多语言文档中详述的使用示例。

  • token_type_ids (torch.Tensor, shape (batch_size, sequence_length), optional) — 用于指示输入的第一个和第二个部分的 token 类型 ID。索引选择在 [0, 1] 中:

    • 0 对应于句子 A token,
    • 1 对应于句子 B token。

    什么是 token type IDs?

  • position_ids (torch.Tensor, shape (batch_size, sequence_length), optional) — 位置嵌入中每个输入序列 token 的位置索引。选择范围为 [0, config.n_positions - 1]

    什么是 position IDs?

  • lengths (torch.LongTensor, shape (batch_size,), optional) — 每个句子的长度,可用于避免在 padding token 索引上执行 attention。您也可以使用 attention_mask 来获得相同的结果(见上文),为兼容性保留此参数。索引选择范围为 [0, ..., input_ids.size(-1)]
  • cache (dict[str, torch.FloatTensor], optional) — 包含预计算的 KV states 的 EncoderDecoderCache 实例。可用于加速顺序解码。
  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您想比模型内部嵌入查找矩阵拥有更多控制权来将 input_ids 索引转换为关联向量,这一点很有用。
  • labels (torch.LongTensor, shape (batch_size,), optional) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失);如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • output_attentions (bool, optional) — 是否返回所有 attention 层的 attentions 张量。有关更多详细信息,请参阅返回的张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的 hidden states。有关更多详细信息,请参阅返回的张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_outputs.SequenceClassifierOutputtuple(torch.FloatTensor)

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

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

FlaubertForSequenceClassification 的 forward 方法,它覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

单标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, FlaubertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("flaubert/flaubert_base_uncased")
>>> model = FlaubertForSequenceClassification.from_pretrained("flaubert/flaubert_base_uncased")

>>> 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 = FlaubertForSequenceClassification.from_pretrained("flaubert/flaubert_base_uncased", num_labels=num_labels)

>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...

多标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, FlaubertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("flaubert/flaubert_base_uncased")
>>> model = FlaubertForSequenceClassification.from_pretrained("flaubert/flaubert_base_uncased", 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 = FlaubertForSequenceClassification.from_pretrained(
...     "flaubert/flaubert_base_uncased", 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).loss

FlaubertForMultipleChoice

class transformers.FlaubertForMultipleChoice

< >

( config *inputs **kwargs )

参数

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

Flaubert 模型,顶部有一个多项选择分类头(一个位于池化输出之上的线性层和一个 softmax),例如用于 RocStories/SWAG 任务。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( 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.MultipleChoiceModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor, shape (batch_size, num_choices, sequence_length)) — 词汇表中输入序列 token 的索引。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是 input IDs?

  • attention_mask (torch.Tensor, shape (batch_size, sequence_length), optional) — 用于避免在 padding token 索引上执行 attention 的掩码。掩码值选择在 [0, 1] 中:

    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    什么是 attention masks?

  • langs (torch.LongTensor, shape (batch_size, num_choices, sequence_length), optional) — 一个并行 token 序列,用于指示输入中每个 token 的语言。索引是语言 ID,可以通过模型配置中提供的两个转换映射(仅适用于多语言模型)从语言名称获取。具体来说,语言名称到语言 ID 的映射在 model.config.lang2id(这是一个字典 string 到 int)中,而语言 ID 到语言名称的映射在 model.config.id2lang(字典 int 到 string)中。

    请参阅 多语言文档中详述的使用示例。

  • token_type_ids (torch.LongTensor, shape (batch_size, num_choices, sequence_length), optional) — 用于指示输入的第一个和第二个部分的 token 类型 ID。索引选择在 [0, 1] 中:

    • 0 对应于句子 A token,
    • 1 对应于句子 B token。

    什么是 token type IDs?

  • position_ids (torch.LongTensor, shape (batch_size, num_choices, sequence_length), optional) — 位置嵌入中每个输入序列 token 的位置索引。选择范围为 [0, config.max_position_embeddings - 1]

    什么是 position IDs?

  • lengths (torch.LongTensor, shape (batch_size,), optional) — 每个句子的长度,可用于避免在 padding token 索引上执行 attention。您也可以使用 attention_mask 来获得相同的结果(见上文),为兼容性保留此参数。索引选择范围为 [0, ..., input_ids.size(-1)]
  • cache (dict[str, torch.FloatTensor], optional) — 包含预计算的 KV states 的 EncoderDecoderCache 实例。可用于加速顺序解码。
  • inputs_embeds (torch.FloatTensor, shape (batch_size, num_choices, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您想比模型内部嵌入查找矩阵拥有更多控制权来将 input_ids 索引转换为关联向量,这一点很有用。
  • labels (torch.LongTensor of shape (batch_size,), optional) — Labels for computing the multiple choice classification loss. Indices should be in [0, ..., num_choices-1] where num_choices is the size of the second dimension of the input tensors. (See input_ids above)
  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.
  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.
  • return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.

返回

transformers.modeling_outputs.MultipleChoiceModelOutputtuple(torch.FloatTensor)

A transformers.modeling_outputs.MultipleChoiceModelOutput 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 (FlaubertConfig) and inputs.

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

The FlaubertForMultipleChoice forward method, overrides the __call__ special method.

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> from transformers import AutoTokenizer, FlaubertForMultipleChoice
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("flaubert/flaubert_base_uncased")
>>> model = FlaubertForMultipleChoice.from_pretrained("flaubert/flaubert_base_uncased")

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

FlaubertForTokenClassification

class transformers.FlaubertForTokenClassification

< >

( 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 (FlaubertForTokenClassification) — 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 Flaubert transformer with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( 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 of 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.

    What are input IDs?

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

    What are attention masks?

  • langs (torch.LongTensor of 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 in model.config.lang2id (which is a dictionary string to int) and the language id to language name mapping is in model.config.id2lang (dictionary int to string).

    See usage examples detailed in the multilingual documentation.

  • token_type_ids (torch.Tensor of 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.

    What are token type IDs?

  • position_ids (torch.Tensor of 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].

    What are position IDs?

  • lengths (torch.LongTensor of 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 of EncoderDecoderCache that contains precomputed KV states. Can be used to speed up sequential decoding.
  • inputs_embeds (torch.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — Labels for computing the token classification loss. Indices should be in [0, ..., config.num_labels - 1].
  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.
  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.
  • return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.

返回

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

A transformers.modeling_outputs.TokenClassifierOutput 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 (FlaubertConfig) and inputs.

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

The FlaubertForTokenClassification forward method, overrides the __call__ special method.

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> from transformers import AutoTokenizer, FlaubertForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("flaubert/flaubert_base_uncased")
>>> model = FlaubertForTokenClassification.from_pretrained("flaubert/flaubert_base_uncased")

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

FlaubertForQuestionAnsweringSimple

class transformers.FlaubertForQuestionAnsweringSimple

< >

( 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 (FlaubertForQuestionAnsweringSimple) — 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.

Flaubert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute span start logits and span end logits).

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( 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 of 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.

    What are input IDs?

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

    What are attention masks?

  • langs (torch.LongTensor of 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 in model.config.lang2id (which is a dictionary string to int) and the language id to language name mapping is in model.config.id2lang (dictionary int to string).

    See usage examples detailed in the multilingual documentation.

  • token_type_ids (torch.Tensor of 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.

    What are token type IDs?

  • position_ids (torch.Tensor of 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].

    What are position IDs?

  • lengths (torch.LongTensor of 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 of EncoderDecoderCache that contains precomputed KV states. Can be used to speed up sequential decoding.
  • inputs_embeds (torch.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • start_positions (torch.Tensor of shape (batch_size,), optional) — Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.
  • end_positions (torch.Tensor of shape (batch_size,), optional) — Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.
  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.
  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.
  • return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.

返回

transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

A transformers.modeling_outputs.QuestionAnsweringModelOutput 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 (FlaubertConfig) and inputs.

  • loss (torch.FloatTensor of shape (1,), 可选, 当提供 labels 时返回) — 总范围提取损失是起始位置和结束位置的交叉熵之和。

  • start_logits (torch.FloatTensor of shape (batch_size, sequence_length)) — 范围起始分数(SoftMax 之前)。

  • end_logits (torch.FloatTensor of 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 后的注意力权重,用于计算自注意力头中的加权平均值。

The FlaubertForQuestionAnsweringSimple forward method, overrides the __call__ special method.

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> from transformers import AutoTokenizer, FlaubertForQuestionAnsweringSimple
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("flaubert/flaubert_base_uncased")
>>> model = FlaubertForQuestionAnsweringSimple.from_pretrained("flaubert/flaubert_base_uncased")

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

FlaubertForQuestionAnswering

class transformers.FlaubertForQuestionAnswering

< >

( 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 (FlaubertForQuestionAnswering) — 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 Flaubert transformer with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layer on top of the hidden-states output to compute span start logits and span end logits).

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( 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.flaubert.modeling_flaubert.FlaubertForQuestionAnsweringOutput or tuple(torch.FloatTensor)

参数

  • input_ids (torch.Tensor of 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.

    What are input IDs?

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

    What are attention masks?

  • langs (torch.LongTensor of 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 in model.config.lang2id (which is a dictionary string to int) and the language id to language name mapping is in model.config.id2lang (dictionary int to string).

    See usage examples detailed in the multilingual documentation.

  • token_type_ids (torch.Tensor of 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.

    What are token type IDs?

  • position_ids (torch.Tensor of 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].

    What are position IDs?

  • lengths (torch.LongTensor of 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) — 实例EncoderDecoderCache,其中包含预计算的 KV 状态。可用于加速顺序解码。
  • inputs_embeds (torch.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — 可以选择,而不是传递input_ids,您可以选择直接传递嵌入表示。如果您想更精细地控制如何将input_ids索引转换为相关的向量,而不是模型的内部嵌入查找矩阵,这将非常有用。
  • start_positions (torch.Tensor of shape (batch_size,), optional) — 用于计算词分类损失的标记跨度起始位置(索引)的标签。位置会被截断到序列长度(sequence_length)。序列外的未计入损失计算。
  • end_positions (torch.Tensor of shape (batch_size,), optional) — 用于计算词分类损失的标记跨度结束位置(索引)的标签。位置会被截断到序列长度(sequence_length)。序列外的未计入损失计算。
  • is_impossible (torch.LongTensor of shape (batch_size,), optional) — 标签,指示问题是否有答案(SQuAD 2.0)
  • cls_index (torch.LongTensor of shape (batch_size,), optional) — 用于计算答案可能性的分类标记位置(索引)的标签。
  • p_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — 无法在答案中的标记的可选掩码(例如 [CLS]、[PAD] 等)。1.0 表示标记应被掩码。0.0 表示标记未被掩码。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。更多细节请参阅返回张量下的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。更多细节请参阅返回张量下的hidden_states
  • return_dict (bool, optional) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.models.flaubert.modeling_flaubert.FlaubertForQuestionAnsweringOutputtuple(torch.FloatTensor)

transformers.models.flaubert.modeling_flaubert.FlaubertForQuestionAnsweringOutputtorch.FloatTensor 的元组(如果传递了return_dict=False或当config.return_dict=False时),包含各种元素,具体取决于配置(FlaubertConfig)和输入。

  • loss (torch.FloatTensor of shape (1,), optional, 如果同时提供 start_positionsend_positions 则返回) — 分类损失,是起始 token、结束 token(如果提供则包括 is_impossible)分类损失的总和。

  • start_top_log_probs (torch.FloatTensor of shape (batch_size, config.start_n_top), optional, 如果未提供 start_positionsend_positions 则返回) — 前 config.start_n_top 个起始 token 可能性(束搜索)的对数概率。

  • start_top_index (torch.LongTensor of shape (batch_size, config.start_n_top), optional, 如果未提供 start_positionsend_positions 则返回) — 前 config.start_n_top 个起始 token 可能性(束搜索)的索引。

  • end_top_log_probs (torch.FloatTensor of shape (batch_size, config.start_n_top * config.end_n_top), optional, 如果未提供 start_positionsend_positions 则返回) — 前 config.start_n_top * config.end_n_top 个结束 token 可能性(束搜索)的对数概率。

  • end_top_index (torch.LongTensor of shape (batch_size, config.start_n_top * config.end_n_top), optional, 如果未提供 start_positionsend_positions 则返回) — 前 config.start_n_top * config.end_n_top 个结束 token 可能性(束搜索)的索引。

  • cls_logits (torch.FloatTensor of shape (batch_size,), optional, 如果未提供 start_positionsend_positions 则返回) — 答案的 is_impossible 标签的对数概率。

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

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple[torch.FloatTensor] | None.attentions, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每个层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

transformers.FlaubertForQuestionAnswering 的 forward 方法,重写了__call__特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> from transformers import AutoTokenizer, FlaubertForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-mlm-en-2048")
>>> model = FlaubertForQuestionAnswering.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
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.