Transformers 文档

GPT-2

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

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

PyTorch FlashAttention SDPA

GPT-2

GPT-2 是 GPT 的扩展版本,一个因果 transformer 语言模型,拥有多 10 倍的参数和训练数据。该模型在 40GB 数据集上进行预训练,用于预测序列中基于所有先前词汇的下一个词汇。这种方法使模型能够以零样本设置执行许多下游任务。OpenAI 发布的博客文章可在此处找到:here

该模型架构使用单向(因果)注意力机制,其中每个标记只能关注其前面的标记,使其在文本生成任务中特别有效。

您可以在 OpenAI community 组织下找到所有原始 GPT-2 检查点。

单击右侧边栏中的 GPT-2 模型,了解有关如何将 GPT-2 应用于不同语言任务的更多示例。

下面的示例演示了如何使用 PipelineAutoModel,以及从命令行生成文本。

流水线
自动模型
Transformers CLI
import torch
from transformers import pipeline

pipeline = pipeline(task="text-generation", model="openai-community/gpt2", dtype=torch.float16, device=0)
pipeline("Hello, I'm a language model")

也可以使用 vLLM 和 `transformers backend` 来提供模型服务。

vllm serve openai-community/gpt2 --model-imp transformers

量化通过以较低精度表示权重来减少大型模型的内存负担。有关更多可用量化后端,请参阅量化概述。

以下示例使用 bitsandbytes 仅将权重量化为 4 位。

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, pipeline

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype="float16",
    bnb_4bit_use_double_quant=True
)

model = AutoModelForCausalLM.from_pretrained(
    "openai-community/gpt2-xl",
    quantization_config=quantization_config,
    device_map="auto"
)

tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2-xl")
inputs = tokenizer("Once upon a time, there was a magical forest", return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=100)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))

注意事项

GPT2Config

class transformers.GPT2Config

< >

( vocab_size = 50257 n_positions = 1024 n_embd = 768 n_layer = 12 n_head = 12 n_inner = None activation_function = 'gelu_new' resid_pdrop = 0.1 embd_pdrop = 0.1 attn_pdrop = 0.1 layer_norm_epsilon = 1e-05 initializer_range = 0.02 summary_type = 'cls_index' summary_use_proj = True summary_activation = None summary_proj_to_labels = True summary_first_dropout = 0.1 scale_attn_weights = True use_cache = True bos_token_id = 50256 eos_token_id = 50256 pad_token_id = None scale_attn_by_inverse_layer_idx = False reorder_and_upcast_attn = False add_cross_attention = False tie_word_embeddings = True **kwargs )

参数

  • vocab_size (int, optional, defaults to 50257) — GPT-2 模型的词汇表大小。定义了调用 GPT2Model 时传入的 inputs_ids 可以表示的不同标记的数量。
  • n_positions (int, optional, defaults to 1024) — 此模型可能使用的最大序列长度。通常将其设置为一个较大的值以防万一(例如 512、1024 或 2048)。
  • n_embd (int, optional, defaults to 768) — 嵌入和隐藏状态的维度。
  • n_layer (int, optional, defaults to 12) — Transformer 编码器中的隐藏层数。
  • n_head (int, optional, defaults to 12) — Transformer 编码器中每个注意力层的注意力头数。
  • n_inner (int, optional) — 内部前馈层的维度。None 将其设置为 n_embd 的 4 倍。
  • activation_function (str, optional, defaults to "gelu_new") — 激活函数,从列表 ["relu", "silu", "gelu", "tanh", "gelu_new"] 中选择。
  • resid_pdrop (float, optional, defaults to 0.1) — 所有全连接层中嵌入、编码器和池化器的 dropout 概率。
  • embd_pdrop (float, optional, defaults to 0.1) — 嵌入的 dropout 比率。
  • attn_pdrop (float, optional, defaults to 0.1) — 注意力的 dropout 比率。
  • layer_norm_epsilon (float, optional, defaults to 1e-05) — 用于层归一化层中的 epsilon 值。
  • initializer_range (float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • summary_type (string, optional, defaults to "cls_index") — 进行序列摘要时使用的参数,用于模型 GPT2DoubleHeadsModel

    必须是以下选项之一:

    • "last":获取最后一个标记的隐藏状态(如 XLNet)。
    • "first":获取第一个标记的隐藏状态(如 BERT)。
    • "mean":获取所有标记隐藏状态的平均值。
    • "cls_index":提供分类标记位置的张量(如 GPT/GPT-2)。
    • "attn":目前未实现,使用多头注意力。
  • summary_use_proj (bool, optional, defaults to True) — 进行序列摘要时使用的参数,用于模型 GPT2DoubleHeadsModel

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

  • summary_activation (str, optional) — 进行序列摘要时使用的参数。用于 GPT2DoubleHeadsModel 中的多项选择头部。

    传入 "tanh" 以对输出应用 tanh 激活,任何其他值将导致不应用激活。

  • summary_proj_to_labels (bool, optional, defaults to True) — 进行序列摘要时使用的参数,用于模型 GPT2DoubleHeadsModel

    投影输出应具有 config.num_labels 类还是 config.hidden_size 类。

  • summary_first_dropout (float, optional, defaults to 0.1) — 进行序列摘要时使用的参数,用于模型 GPT2DoubleHeadsModel

    投影和激活之后使用的 dropout 比率。

  • scale_attn_weights (bool, optional, defaults to True) — 是否通过除以 sqrt(hidden_size) 来缩放注意力权重。
  • use_cache (bool, optional, defaults to True) — 模型是否应返回最后一个 key/value 注意力(并非所有模型都使用)。
  • bos_token_id (int, optional, defaults to 50256) — 词汇表中句子开始标记的 id。
  • eos_token_id (int, optional, defaults to 50256) — 词汇表中句子结束标记的 id。
  • pad_token_id (int, optional) — 填充标记 id。
  • scale_attn_by_inverse_layer_idx (bool, optional, defaults to False) — 是否额外通过 1 / layer_idx + 1 来缩放注意力权重。
  • reorder_and_upcast_attn (bool, optional, defaults to False) — 在计算注意力(点积)之前是否缩放键(K),以及在使用混合精度训练时是否将注意力点积/softmax 升级为 float()。
  • add_cross_attention (bool, optional, defaults to False) — 是否应向模型添加交叉注意力层。
  • tie_word_embeddings (bool, optional, defaults to True) — 是否绑定词嵌入。

这是用于存储 GPT2Model 配置的配置类。它用于根据指定的参数实例化 GPT-2 模型,定义模型架构。使用默认值实例化配置将生成与 GPT-2 openai-community/gpt2 架构类似的配置。

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

示例

>>> from transformers import GPT2Config, GPT2Model

>>> # Initializing a GPT2 configuration
>>> configuration = GPT2Config()

>>> # Initializing a model (with random weights) from the configuration
>>> model = GPT2Model(configuration)

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

GPT2Tokenizer

class transformers.GPT2Tokenizer

< >

( vocab: str | dict[str, int] | None = None merges: str | list[str] | None = None errors: str = 'replace' unk_token: tokenizers.AddedToken | str = '<|endoftext|>' bos_token: tokenizers.AddedToken | str = '<|endoftext|>' eos_token: tokenizers.AddedToken | str = '<|endoftext|>' pad_token: tokenizers.AddedToken | str | None = None add_prefix_space = False **kwargs )

参数

  • vocab_file (str) — 词汇表文件的路径。
  • merges_file (str) — 合并文件(merges file)的路径。
  • errors (str, 可选, 默认为 "replace") — 将字节解码为UTF-8时遵循的范例。有关详细信息,请参阅 bytes.decode
  • unk_token (str, 可选, 默认为 "<|endoftext|>") — 未知标记。不在词汇表中的标记无法转换为ID,将被设置为此标记。
  • bos_token (str, 可选, 默认为 "<|endoftext|>") — 序列开始标记。
  • eos_token (str, 可选, 默认为 "<|endoftext|>") — 序列结束标记。
  • pad_token (str, 可选) — 用于填充的标记,例如在对不同长度的序列进行批处理时。
  • add_prefix_space (bool, 可选, 默认为 False) — 是否在输入中添加一个初始空格。这使得第一个词的处理方式与其他词相同。(GPT2 分词器通过前面的空格来检测词的开头)。
  • add_bos_token (bool, 可选, 默认为 False) — 是否在输入中添加一个初始的序列开始标记。这使得第一个词的处理方式与其他词相同。
  • vocab (strdict[str, int], 可选) — 自定义词汇表字典。如果未提供,则从 vocab_file 加载词汇表。
  • merges (strlist[str], 可选) — 自定义合并列表。如果未提供,则从 merges_file 加载合并。

构建一个 GPT-2 分词器。基于字节级字节对编码(byte-level Byte-Pair-Encoding)。

这个分词器经过训练,将空格视为词元的一部分(有点像 sentencepiece),所以一个词会

无论是否在句子开头(无空格),编码方式都会不同

>>> from transformers import GPT2Tokenizer

>>> tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
>>> tokenizer("Hello world")["input_ids"]
[15496, 995]

>>> tokenizer(" Hello world")["input_ids"]
[18435, 995]

您可以通过在实例化此分词器时或在对某些文本调用它时传递 add_prefix_space=True 来绕过此行为,但由于模型并非以这种方式进行预训练,这可能会导致性能下降。

当与 is_split_into_words=True 一起使用时,此分词器会在每个词(甚至是第一个词)之前添加一个空格。

此分词器继承自 TokenizersBackend,其中包含大部分主要方法。用户应参考此父类了解有关这些方法的更多信息。

save_vocabulary

< >

( save_directory: str filename_prefix: str | None = None )

GPT2TokenizerFast

class transformers.GPT2Tokenizer

< >

( vocab: str | dict[str, int] | None = None merges: str | list[str] | None = None errors: str = 'replace' unk_token: tokenizers.AddedToken | str = '<|endoftext|>' bos_token: tokenizers.AddedToken | str = '<|endoftext|>' eos_token: tokenizers.AddedToken | str = '<|endoftext|>' pad_token: tokenizers.AddedToken | str | None = None add_prefix_space = False **kwargs )

参数

  • vocab_file (str) — 词汇表文件的路径。
  • merges_file (str) — 合并文件(merges file)的路径。
  • errors (str, 可选, 默认为 "replace") — 将字节解码为UTF-8时遵循的范例。有关详细信息,请参阅 bytes.decode
  • unk_token (str, 可选, 默认为 "<|endoftext|>") — 未知标记。不在词汇表中的标记无法转换为ID,将被设置为此标记。
  • bos_token (str, 可选, 默认为 "<|endoftext|>") — 序列开始标记。
  • eos_token (str, 可选, 默认为 "<|endoftext|>") — 序列结束标记。
  • pad_token (str, 可选) — 用于填充的标记,例如在对不同长度的序列进行批处理时。
  • add_prefix_space (bool, 可选, 默认为 False) — 是否在输入中添加一个初始空格。这使得第一个词的处理方式与其他词相同。(GPT2 分词器通过前面的空格来检测词的开头)。
  • add_bos_token (bool, 可选, 默认为 False) — 是否在输入中添加一个初始的序列开始标记。这使得第一个词的处理方式与其他词相同。
  • vocab (strdict[str, int], 可选) — 自定义词汇表字典。如果未提供,则从 vocab_file 加载词汇表。
  • merges (strlist[str], 可选) — 自定义合并列表。如果未提供,则从 merges_file 加载合并。

构建一个 GPT-2 分词器。基于字节级字节对编码(byte-level Byte-Pair-Encoding)。

这个分词器经过训练,将空格视为词元的一部分(有点像 sentencepiece),所以一个词会

无论是否在句子开头(无空格),编码方式都会不同

>>> from transformers import GPT2Tokenizer

>>> tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
>>> tokenizer("Hello world")["input_ids"]
[15496, 995]

>>> tokenizer(" Hello world")["input_ids"]
[18435, 995]

您可以通过在实例化此分词器时或在对某些文本调用它时传递 add_prefix_space=True 来绕过此行为,但由于模型并非以这种方式进行预训练,这可能会导致性能下降。

当与 is_split_into_words=True 一起使用时,此分词器会在每个词(甚至是第一个词)之前添加一个空格。

此分词器继承自 TokenizersBackend,其中包含大部分主要方法。用户应参考此父类了解有关这些方法的更多信息。

GPT2 特有的输出

class transformers.models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput

< >

( loss: torch.FloatTensor | None = None mc_loss: torch.FloatTensor | None = None logits: torch.FloatTensor | None = None mc_logits: torch.FloatTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None hidden_states: tuple[torch.FloatTensor] | None = None attentions: tuple[torch.FloatTensor] | None = None )

参数

  • loss (torch.FloatTensor of shape (1,), 可选, 当提供 labels 时返回) — 语言建模损失。
  • mc_loss (torch.FloatTensor of shape (1,), 可选, 当提供 mc_labels 时返回) — 多项选择分类损失。
  • logits (torch.FloatTensor of shape (batch_size, num_choices, sequence_length, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前的每个词汇表标记的分数)。
  • mc_logits (torch.FloatTensor of shape (batch_size, num_choices)) — 多项选择分类头的预测分数(SoftMax 之前的每个选项的分数)。
  • past_key_values (Cache, 可选, 当传入 use_cache=Trueconfig.use_cache=True 时返回) — 这是一个 Cache 实例。有关更多详细信息,请参阅我们的 kv cache guide

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

  • hidden_states (tuple[torch.FloatTensor] | None.hidden_states, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则包含嵌入输出,加上每层的一个输出),形状为 (batch_size, sequence_length, hidden_size)

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

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

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

预测两个句子是否连续的模型输出的基类。

GPT2Model

class transformers.GPT2Model

< >

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

裸 GPT2 模型,输出原始隐藏状态,顶部没有特定头部。

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

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

forward

< >

( input_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None cache_position: torch.LongTensor | None = None attention_mask: torch.FloatTensor | None = None token_type_ids: torch.LongTensor | None = None position_ids: torch.LongTensor | None = None inputs_embeds: torch.FloatTensor | None = None encoder_hidden_states: torch.Tensor | None = None encoder_attention_mask: torch.FloatTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, input_ids_length)) — input_ids_length = sequence_length if past_key_values is None else past_key_values.get_seq_length() (输入过去键值状态的 sequence_length)。词汇表中输入序列标记的索引。

    如果使用了 past_key_values,则只应将未计算过去状态的 input_ids 作为 input_ids 传入。

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

    什么是输入 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常包括在解码的先前阶段由模型返回的 past_key_values,当 use_cache=Trueconfig.use_cache=True 时。

    只允许 Cache 实例作为输入,请参阅我们的 kv cache guide。如果未传入 past_key_values,默认将初始化 DynamicCache

    模型将输出与输入时相同的缓存格式。

    如果使用了 past_key_values,则用户应只输入未处理的 input_ids(即未将其过去键值状态提供给此模型的那些)形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的所有 input_ids

  • cache_position (torch.LongTensor of shape (sequence_length), 可选) — 描述输入序列标记在序列中位置的索引。与 position_ids 不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。
  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), 可选) — 遮罩以避免对填充标记索引执行注意力操作。遮罩值选择在 [0, 1] 中:

    • 1 表示**未被遮罩**的标记,
    • 0 表示**被遮罩**的标记。

    什么是注意力遮罩?

  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), 可选) — 段标记索引,用于指示输入的第一部分和第二部分。索引选择在 [0, 1] 中:

    • 0 对应于*句子 A* 标记,
    • 1 对应于*句子 B* 标记。

    什么是标记类型 ID?

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

    什么是位置 ID?

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), 可选) — 可选地,你可以选择直接传入嵌入表示,而不是传入 input_ids。如果你希望对如何将 input_ids 索引转换为相关向量有比模型内部嵌入查找矩阵更多的控制权,这将很有用。
  • encoder_hidden_states (torch.Tensor of shape (batch_size, sequence_length, hidden_size), 可选) — 编码器最后一层输出的隐藏状态序列。如果模型被配置为解码器,则用于交叉注意力。
  • encoder_attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), 可选) — 遮罩以避免对编码器输入中的填充标记索引执行注意力操作。如果模型被配置为解码器,此遮罩用于交叉注意力。遮罩值选择在 [0, 1] 中:

    • 1 表示**未被遮罩**的标记,
    • 0 表示**被遮罩**的标记。
  • use_cache (bool, 可选) — 如果设置为 True,则返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentionstuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions 对象或一个 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.return_dict=False),包含根据配置 (GPT2Config) 和输入的不同元素。

  • last_hidden_state (torch.FloatTensor, 形状为 (batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。

    如果使用了 past_key_values,则只输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values (Cache, optional, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南

    Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if config.is_encoder_decoder=True in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding.

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

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

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

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

  • cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True and config.add_cross_attention=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    解码器交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均。

GPT2Model forward 方法,覆盖了 __call__ 特殊方法。

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

GPT2LMHeadModel

class transformers.GPT2LMHeadModel

< >

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

带有语言建模头(与输入嵌入权重绑定的线性层)的 GPT2 模型转换器。

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

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

forward

< >

( input_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None cache_position: torch.LongTensor | None = None attention_mask: torch.FloatTensor | None = None token_type_ids: torch.LongTensor | None = None position_ids: torch.LongTensor | None = None inputs_embeds: torch.FloatTensor | None = None encoder_hidden_states: torch.Tensor | None = None encoder_attention_mask: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs ) transformers.modeling_outputs.CausalLMOutputWithCrossAttentions or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, input_ids_length)) — input_ids_length = sequence_length if past_key_values is None else past_key_values.get_seq_length() (输入过去键值状态的 sequence_length)。词汇表中输入序列标记的索引。

    如果使用了 past_key_values,则只应将未计算过去状态的 input_ids 作为 input_ids 传入。

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

    什么是输入 ID?

  • past_key_values (~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

  • cache_position (torch.LongTensor of shape (sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily to position_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.
  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    What are attention masks?

  • token_type_ids (torch.LongTensor 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.LongTensor 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?

  • inputs_embeds (torch.FloatTensor 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.
  • encoder_hidden_states (torch.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder.
  • encoder_attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.
  • labels (torch.LongTensor of shape (batch_size, input_ids_length), optional) — Labels for language modeling. Note that the labels are shifted inside the model, i.e. you can set labels = input_ids Indices are selected in [-100, 0, ..., config.vocab_size] All labels set to -100 are ignored (masked), the loss is only computed for labels in [0, ..., config.vocab_size]
  • use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).
  • 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.
  • logits_to_keep (Union[int, torch.Tensor], optional, defaults to 0) — If an int, compute logits for the last logits_to_keep tokens. If 0, calculate logits for all input_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 a torch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).

返回

transformers.modeling_outputs.CausalLMOutputWithCrossAttentions or tuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits (形状为 (batch_size, sequence_length, config.vocab_size)torch.FloatTensor) — 语言建模头部的预测分数(SoftMax 之前的每个词汇标记的分数)。

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

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

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

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

  • cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

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

  • past_key_values (Cache, optional, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南

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

The GPT2LMHeadModel forward method, overrides the __call__ special method.

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

示例

>>> import torch
>>> from transformers import AutoTokenizer, GPT2LMHeadModel

>>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
>>> model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2")

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

GPT2DoubleHeadsModel

class transformers.GPT2DoubleHeadsModel

< >

( 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 (GPT2DoubleHeadsModel) — 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 GPT2 Model transformer with a language modeling and a multiple-choice classification head on top e.g. for RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the input embeddings, the classification head takes as input the input of a specified classification token index in the input sequence).

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

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

forward

< >

( input_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None cache_position: torch.LongTensor | None = None attention_mask: torch.FloatTensor | None = None token_type_ids: torch.LongTensor | None = None position_ids: torch.LongTensor | None = None inputs_embeds: torch.FloatTensor | None = None mc_token_ids: torch.LongTensor | None = None labels: torch.LongTensor | None = None mc_labels: torch.LongTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, input_ids_length)) — input_ids_length = sequence_length if past_key_values is None else past_key_values.get_seq_length() (sequence_length of input past key value states). Indices of input sequence tokens in the vocabulary.

    If past_key_values is used, only input_ids that do not have their past calculated should be passed as input_ids.

    Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

    What are input IDs?

  • past_key_values (~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

  • cache_position (torch.LongTensor of shape (sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily to position_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.
  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    What are attention masks?

  • token_type_ids (torch.LongTensor 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.LongTensor 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?

  • inputs_embeds (torch.FloatTensor 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.
  • mc_token_ids (torch.LongTensor of shape (batch_size, num_choices), optional, default to index of the last token of the input) — Index of the classification token in each input sequence. Selected in the range [0, input_ids.size(-1) - 1].
  • labels (torch.LongTensor of shape (batch_size, input_ids_length), optional) — Labels for language modeling. Note that the labels are shifted inside the model, i.e. you can set labels = input_ids. Indices are selected in [-100, 0, ..., config.vocab_size - 1]. All labels set to -100 are ignored (masked), the loss is only computed for labels in [0, ..., config.vocab_size - 1]
  • mc_labels (torch.LongTensor of shape (batch_size), optional) — Labels for computing the multiple choice classification loss. Indices should be in [0, ..., num_choices] where num_choices is the size of the second dimension of the input tensors. (see input_ids above)
  • use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).
  • 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.models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput or tuple(torch.FloatTensor)

A transformers.models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput 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 (GPT2Config) and inputs.

  • loss (torch.FloatTensor,形状为 (1,)可选,当提供 labels 时返回) — 语言建模损失。

  • mc_loss (torch.FloatTensor of shape (1,), optional, returned when mc_labels is provided) — Multiple choice classification loss.

  • logits (torch.FloatTensor of shape (batch_size, num_choices, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

  • mc_logits (torch.FloatTensor of shape (batch_size, num_choices)) — Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).

  • past_key_values (Cache, optional, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南

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

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

The GPT2DoubleHeadsModel forward method, overrides the __call__ special method.

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

示例

>>> import torch
>>> from transformers import AutoTokenizer, GPT2DoubleHeadsModel

>>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
>>> model = GPT2DoubleHeadsModel.from_pretrained("openai-community/gpt2")

>>> # Add a [CLS] to the vocabulary (we should train it also!)
>>> num_added_tokens = tokenizer.add_special_tokens({"cls_token": "[CLS]"})
>>> # Update the model embeddings with the new vocabulary size
>>> embedding_layer = model.resize_token_embeddings(len(tokenizer))

>>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
>>> encoded_choices = [tokenizer.encode(s) for s in choices]
>>> cls_token_location = [tokens.index(tokenizer.cls_token_id) for tokens in encoded_choices]

>>> input_ids = torch.tensor(encoded_choices).unsqueeze(0)  # Batch size: 1, number of choices: 2
>>> mc_token_ids = torch.tensor([cls_token_location])  # Batch size: 1

>>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
>>> lm_logits = outputs.logits
>>> mc_logits = outputs.mc_logits

GPT2ForQuestionAnswering

class transformers.GPT2ForQuestionAnswering

< >

( 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 (GPT2ForQuestionAnswering) — 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 Gpt2 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.LongTensor | None = None attention_mask: torch.FloatTensor | None = None token_type_ids: torch.LongTensor | None = None position_ids: torch.LongTensor | None = None inputs_embeds: torch.FloatTensor | None = None start_positions: torch.LongTensor | None = None end_positions: torch.LongTensor | 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.LongTensor of shape (batch_size, input_ids_length)) — input_ids_length = sequence_length if past_key_values is None else past_key_values.get_seq_length() (sequence_length of input past key value states). Indices of input sequence tokens in the vocabulary.

    If past_key_values is used, only input_ids that do not have their past calculated should be passed as input_ids.

    Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

    What are input IDs?

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    What are attention masks?

  • token_type_ids (torch.LongTensor 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.LongTensor 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?

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选参数,如果你不想传入 input_ids,可以选择直接传入嵌入表示。如果你想更精细地控制如何将 input_ids 索引转换为关联向量,而不是使用模型内部的嵌入查找矩阵,这会很有用。
  • start_positions (torch.LongTensor of shape (batch_size,), optional) — 用于计算标记分类损失的标注片段起始位置(索引)的标签。位置将被限制在序列长度(sequence_length)范围内。超出序列的位置将不用于计算损失。
  • end_positions (torch.LongTensor of shape (batch_size,), optional) — 用于计算标记分类损失的标注片段结束位置(索引)的标签。位置将被限制在序列长度(sequence_length)范围内。超出序列的位置将不用于计算损失。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 对象而不是普通元组。

返回

transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

返回 transformers.modeling_outputs.QuestionAnsweringModelOutput 对象或 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.return_dict=False),具体包含哪些元素取决于配置(GPT2Config)和输入。

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

GPT2ForQuestionAnswering 的 forward 方法重写了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, GPT2ForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
>>> model = GPT2ForQuestionAnswering.from_pretrained("openai-community/gpt2")

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

GPT2ForSequenceClassification

class transformers.GPT2ForSequenceClassification

< >

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

GPT2 模型 Transformer,顶部带有一个序列分类头(线性层)。

GPT2ForSequenceClassification 使用最后一个 token 进行分类,这与其他因果模型(如 GPT-1)的做法相同。

由于它在最后一个 token 上进行分类,因此需要知道最后一个 token 的位置。如果在配置中定义了 pad_token_id,它会找到批次中每行中最后一个非填充 token。如果没有定义 pad_token_id,它会简单地取批次中每行的最后一个值。由于在传入 inputs_embeds 而非 input_ids 时无法猜测填充 token,因此它会执行相同的操作(取批次中每行的最后一个值)。

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

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

forward

< >

( input_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None attention_mask: torch.FloatTensor | None = None token_type_ids: torch.LongTensor | None = None position_ids: torch.LongTensor | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.modeling_outputs.SequenceClassifierOutputWithPast or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, input_ids_length)) — input_ids_length = sequence_length(如果 past_key_valuesNone)否则为 past_key_values.get_seq_length()(输入过去键值状态的 sequence_length)。词汇表中输入序列 token 的索引。

    如果使用了 past_key_values,则只应将尚未计算过去键值状态的 input_ids 作为 input_ids 传入。

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

    什么是输入 ID?

  • past_key_values (~cache_utils.Cache, optional) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。当 use_cache=Trueconfig.use_cache=True 时,这通常是模型在先前解码阶段返回的 past_key_values

    只允许使用 Cache 实例作为输入,请参阅我们的 kv cache guide。如果未传入 past_key_values,默认将初始化 DynamicCache

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,则要求用户只输入形状为 (batch_size, unprocessed_length) 的未处理 input_ids(即没有向此模型提供过去键值状态的 token),而不是形状为 (batch_size, sequence_length) 的所有 input_ids

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — 用于避免在填充 token 索引上执行注意力的掩码。掩码值选择在 [0, 1] 范围内:

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

    什么是注意力掩码?

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

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选参数,如果你不想传入 input_ids,可以选择直接传入嵌入表示。如果你想更精细地控制如何将 input_ids 索引转换为关联向量,而不是使用模型内部的嵌入查找矩阵,这会很有用。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方误差损失);如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • use_cache (bool, optional) — 如果设置为 True,将返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 对象而不是普通元组。

返回

transformers.modeling_outputs.SequenceClassifierOutputWithPasttuple(torch.FloatTensor)

返回 transformers.modeling_outputs.SequenceClassifierOutputWithPast 对象或 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.return_dict=False),具体包含哪些元素取决于配置(GPT2Config)和输入。

  • loss (形状为 (1,)torch.FloatTensor可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。

  • logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(SoftMax 之前)。

  • past_key_values (Cache, optional, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南

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

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

GPT2ForSequenceClassification 的 forward 方法重写了 __call__ 特殊方法。

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

单标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, GPT2ForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
>>> model = GPT2ForSequenceClassification.from_pretrained("openai-community/gpt2")

>>> 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 = GPT2ForSequenceClassification.from_pretrained("openai-community/gpt2", num_labels=num_labels)

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

多标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, GPT2ForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
>>> model = GPT2ForSequenceClassification.from_pretrained("openai-community/gpt2", 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 = GPT2ForSequenceClassification.from_pretrained(
...     "openai-community/gpt2", 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

GPT2ForTokenClassification

class transformers.GPT2ForTokenClassification

< >

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

Gpt2 Transformer,顶部带有一个 token 分类头(隐藏状态输出上的一个线性层),例如用于命名实体识别 (NER) 任务。

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

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

forward

< >

( input_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None attention_mask: torch.FloatTensor | None = None token_type_ids: torch.LongTensor | None = None position_ids: torch.LongTensor | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.modeling_outputs.TokenClassifierOutput or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, input_ids_length)) — input_ids_length = sequence_length(如果 past_key_valuesNone)否则为 past_key_values.get_seq_length()(输入过去键值状态的 sequence_length)。词汇表中输入序列 token 的索引。

    如果使用了 past_key_values,则只应将尚未计算过去键值状态的 input_ids 作为 input_ids 传入。

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

    什么是输入 ID?

  • past_key_values (~cache_utils.Cache, optional) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。当 use_cache=Trueconfig.use_cache=True 时,这通常是模型在先前解码阶段返回的 past_key_values

    只允许使用 Cache 实例作为输入,请参阅我们的 kv cache guide。如果未传入 past_key_values,默认将初始化 DynamicCache

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,则要求用户只输入形状为 (batch_size, unprocessed_length) 的未处理 input_ids(即没有向此模型提供过去键值状态的 token),而不是形状为 (batch_size, sequence_length) 的所有 input_ids

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — 用于避免在填充 token 索引上执行注意力的掩码。掩码值选择在 [0, 1] 范围内:

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

    什么是注意力掩码?

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

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选参数,如果你不想传入 input_ids,可以选择直接传入嵌入表示。如果你想更精细地控制如何将 input_ids 索引转换为关联向量,而不是使用模型内部的嵌入查找矩阵,这会很有用。
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方误差损失);如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • use_cache (bool, optional) — 如果设置为 True,将返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 对象而不是普通元组。

返回

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

返回 transformers.modeling_outputs.TokenClassifierOutput 对象或 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.return_dict=False),具体包含哪些元素取决于配置(GPT2Config)和输入。

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

GPT2ForTokenClassification 的 forward 方法重写了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, GPT2ForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
>>> model = GPT2ForTokenClassification.from_pretrained("openai-community/gpt2")

>>> 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)
...
在 GitHub 上更新

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