Transformers 文档

GPT-J

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

此模型于 2021-06-04 发布,并于 2021-08-31 添加到 Hugging Face Transformers。

GPT-J

PyTorch FlashAttention

概述

由 Ben Wang 和 Aran Komatsuzaki 在 kingoflolz/mesh-transformer-jax 仓库发布的 GPT-J 模型,是在 the Pile 数据集上训练的类 GPT-2 的因果语言模型。

此模型由 Stella Biderman 贡献。

使用技巧

  • 要以 float32 加载 GPT-J,至少需要 2 倍模型大小的 RAM:1 倍用于初始权重,另 1 倍用于加载检查点。因此,对于 GPT-J,仅加载模型就需要至少 48GB RAM。为了减少 RAM 使用量,有几种选择。dtype 参数可用于仅在 CUDA 设备上以半精度初始化模型。还有一个 fp16 分支,存储 fp16 权重,可用于进一步最小化 RAM 使用量。
>>> from transformers import GPTJForCausalLM
from accelerate import Accelerator
>>> import torch

>>> device = Accelerator().device
>>> model = GPTJForCausalLM.from_pretrained(
...     "EleutherAI/gpt-j-6B",
...     revision="float16",
...     dtype=torch.float16,
... ).to(device)
  • 模型应该可以适应 16GB GPU 进行推理。训练/微调需要更多的 GPU RAM。例如,Adam 优化器会复制四份模型:模型本身、梯度、梯度的平均值和平均值的平方。因此,即使使用混合精度,由于梯度更新是 fp32,至少也需要 4 倍模型大小的 GPU 内存。这还不包括激活和数据批次,它们还需要更多的 GPU RAM。因此,应探索 DeepSpeed 等解决方案来训练/微调模型。另一种选择是使用原始代码库在 TPU 上训练/微调模型,然后将模型转换为 Transformers 格式进行推理。说明可以在这里找到。

  • 虽然嵌入矩阵的大小为 50400,但 GPT-2 分词器只使用了 50257 个条目。这些额外的标记是为了提高 TPU 的效率。为了避免嵌入矩阵大小和词汇表大小之间的不匹配,GPT-J 的分词器包含 143 个额外的标记<|extratoken_1|>... <|extratoken_143|>,因此分词器的vocab_size也变为 50400。

使用示例

可以使用 generate() 方法使用 GPT-J 模型生成文本。

>>> from transformers import AutoModelForCausalLM, AutoTokenizer

>>> model = AutoModelForCausalLM.from_pretrained("EleutherAI/gpt-j-6B")
>>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B")

>>> prompt = (
...     "In a shocking finding, scientists discovered a herd of unicorns living in a remote, "
...     "previously unexplored valley, in the Andes Mountains. Even more surprising to the "
...     "researchers was the fact that the unicorns spoke perfect English."
... )

>>> input_ids = tokenizer(prompt, return_tensors="pt").input_ids

>>> gen_tokens = model.generate(
...     input_ids,
...     do_sample=True,
...     temperature=0.9,
...     max_length=100,
... )
>>> gen_text = tokenizer.batch_decode(gen_tokens)[0]

…或使用 float16 精度

>>> from transformers import GPTJForCausalLM, AutoTokenizer
from accelerate import Accelerator
>>> import torch

>>> device = Accelerator().device
>>> model = GPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B", dtype=torch.float16).to(device)
>>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B")

>>> prompt = (
...     "In a shocking finding, scientists discovered a herd of unicorns living in a remote, "
...     "previously unexplored valley, in the Andes Mountains. Even more surprising to the "
...     "researchers was the fact that the unicorns spoke perfect English."
... )

>>> input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(model.device)

>>> gen_tokens = model.generate(
...     input_ids,
...     do_sample=True,
...     temperature=0.9,
...     max_length=100,
... )
>>> gen_text = tokenizer.batch_decode(gen_tokens)[0]

资源

一系列官方 Hugging Face 和社区(由 🌎 标识)资源,帮助您开始使用 GPT-J。如果您有兴趣提交资源在此处包含,请随时提出 Pull Request,我们将进行审查!资源应尽可能展示新内容,而不是重复现有资源。

文本生成

文档资源

GPTJConfig

class transformers.GPTJConfig

< >

( vocab_size = 50400 n_positions = 2048 n_embd = 4096 n_layer = 28 n_head = 16 rotary_dim = 64 n_inner = None activation_function = 'gelu_new' resid_pdrop = 0.0 embd_pdrop = 0.0 attn_pdrop = 0.0 layer_norm_epsilon = 1e-05 initializer_range = 0.02 use_cache = True bos_token_id = 50256 eos_token_id = 50256 pad_token_id = None tie_word_embeddings = False **kwargs )

参数

  • vocab_size (int, 可选, 默认为 50400) — GPT-J 模型的词汇表大小。定义在调用 GPTJModel 时传递的 inputs_ids 可以表示的不同标记的数量。
  • n_positions (int, 可选, 默认为 2048) — 此模型可能使用的最大序列长度。通常将其设置为一个较大的值以防万一(例如,512 或 1024 或 2048)。
  • n_embd (int, 可选, 默认为 4096) — 嵌入和隐藏状态的维度。
  • n_layer (int, 可选, 默认为 28) — Transformer 编码器中的隐藏层数量。
  • n_head (int, 可选, 默认为 16) — Transformer 编码器中每个注意力层的注意力头数量。
  • rotary_dim (int, 可选, 默认为 64) — 应用了旋转位置嵌入的嵌入中的维度数。
  • n_inner (int, 可选, 默认为 None) — 前馈网络内部层的维度。None 将设置为 n_embd 的 4 倍
  • activation_function (str, 可选, 默认为 "gelu_new") — 激活函数,从列表 ["relu", "silu", "gelu", "tanh", "gelu_new"] 中选择。
  • resid_pdrop (float, 可选, 默认为 0.1) — 嵌入、编码器和池化层中所有全连接层的 dropout 概率。
  • embd_pdrop (int, 可选, 默认为 0.1) — 嵌入的 dropout 比率。
  • attn_pdrop (float, 可选, 默认为 0.1) — 注意力的 dropout 比率。
  • layer_norm_epsilon (float, 可选, 默认为 1e-5) — 层归一化层中使用的 epsilon。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • use_cache (bool, 可选, 默认为 True) — 模型是否应返回最后一个键/值注意力(并非所有模型都使用)。

这是用于存储 GPTJModel 配置的配置类。它用于根据指定的参数实例化 GPT-J 模型,定义模型的架构。使用默认值实例化配置将产生与 GPT-J EleutherAI/gpt-j-6B 架构类似的配置。配置对象继承自 PreTrainedConfig,并可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例

>>> from transformers import GPTJModel, GPTJConfig

>>> # Initializing a GPT-J 6B configuration
>>> configuration = GPTJConfig()

>>> # Initializing a model from the configuration
>>> model = GPTJModel(configuration)

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

GPTJModel

class transformers.GPTJModel

< >

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

裸露的 Gptj 模型输出原始隐藏状态,没有任何特定于顶部的头部。

此模型继承自 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 use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None cache_position: torch.LongTensor | None = None **kwargs ) transformers.modeling_outputs.BaseModelOutputWithPasttuple(torch.FloatTensor)

参数

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

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

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

    注意力掩码是什么?

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

    Token 类型 ID 是什么?

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

    位置 ID 是什么?

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_dim), 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.
  • 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.
  • 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.

返回

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

一个 transformers.modeling_outputs.BaseModelOutputWithPast 或一个 torch.FloatTensor 的元组(如果传入了 return_dict=Falseconfig.return_dict=False),其包含的元素取决于配置(GPTJConfig)和输入。

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

GPTJModel 的 forward 方法,重写了 __call__ 特殊方法。

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

GPTJForCausalLM

class transformers.GPTJForCausalLM

< >

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

GPT-J Model transformer with a language modeling head on top。

此模型继承自 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 cache_position: torch.LongTensor | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs ) transformers.modeling_outputs.CausalLMOutputWithPasttuple(torch.FloatTensor)

参数

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

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

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

    注意力掩码是什么?

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

    Token 类型 ID 是什么?

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

    位置 ID 是什么?

  • inputs_embeds (torch.FloatTensor, 形状为 (batch_size, sequence_length, hidden_dim), 可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望比模型内部的嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联向量,则此功能非常有用。
  • labels (torch.LongTensor, 形状为 (batch_size, sequence_length), 可选) — 用于语言建模的标签。请注意,标签在模型内部已移位,即您可以设置 labels = input_ids。索引选择范围为 [-100, 0, ..., config.vocab_size]。所有设置为 -100 的标签都将被忽略(屏蔽),仅为 [0, ..., config.vocab_size] 中的标签计算损失。
  • use_cache (bool, 可选) — 如果设置为 True,则返回 past_key_values 键值状态,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • cache_position (torch.LongTensor, 形状为 (sequence_length), 可选) — 描绘输入序列 token 在序列中位置的索引。与 position_ids 相反,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。
  • logits_to_keep (Union[int, torch.Tensor], 可选, 默认值为 0) — 如果是 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则为所有 input_ids 计算 logits(特殊情况)。生成时只需要最后一个 token 的 logits,并且仅为该 token 计算可以节省内存,这对于长序列或大词汇量来说非常重要。如果为 torch.Tensor,则必须是 1D 的,对应于序列长度维度中要保留的索引。当使用打包张量格式(批次和序列长度的单维)时,这很有用。

返回

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

一个 transformers.modeling_outputs.CausalLMOutputWithPast 或一个元组 (如果传入 return_dict=Falseconfig.return_dict=False) 包含各种元素的 torch.FloatTensor,具体取决于配置 (GPTJConfig) 和输入。

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

  • logits (形状为 (batch_size, sequence_length, config.vocab_size)torch.FloatTensor) — 语言建模头部的预测分数(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 后的注意力权重,用于计算自注意力头中的加权平均值。

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

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

示例

GPTJForSequenceClassification

class transformers.GPTJForSequenceClassification

< >

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

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

GPTJForSequenceClassification 使用最后一个 token 进行分类,就像其他因果模型(例如 GPT、GPT-2、GPT-Neo)一样。

由于它在最后一个 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.SequenceClassifierOutputWithPasttuple(torch.FloatTensor)

参数

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

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

    输入 ID 是什么?

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

    只有 DynamicCache 实例被允许作为输入,请参阅我们的 KV 缓存指南。如果未传入 past_key_values,则默认初始化 DynamicCache

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

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

  • attention_mask (torch.FloatTensor, 形状为 (batch_size, sequence_length), 可选) — 用于避免对填充 token 索引执行注意力的掩码。掩码值选择在 [0, 1] 中:

    • 1 表示未屏蔽的 token,
    • 0 表示已屏蔽的 token。

    注意力掩码是什么?

  • token_type_ids (torch.LongTensor, 形状为 (batch_size, sequence_length), 可选) — 用于指示输入的第一个和第二个部分的 token 类型 ID。索引选择范围为 [0, 1]

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

    Token 类型 ID 是什么?

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

    位置 ID 是什么?

  • inputs_embeds (torch.FloatTensor, 形状为 (batch_size, sequence_length, hidden_dim), 可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望比模型内部的嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联向量,则此功能非常有用。
  • labels (torch.LongTensor, 形状为 (batch_size,), 可选) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • 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.SequenceClassifierOutputWithPasttuple(torch.FloatTensor)

一个 transformers.modeling_outputs.SequenceClassifierOutputWithPast 或一个元组 (如果传入 return_dict=Falseconfig.return_dict=False) 包含各种元素的 torch.FloatTensor,具体取决于配置 (GPTJConfig) 和输入。

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

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

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

单标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, GPTJForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B")
>>> model = GPTJForSequenceClassification.from_pretrained("EleutherAI/gpt-j-6B")

>>> 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 = GPTJForSequenceClassification.from_pretrained("EleutherAI/gpt-j-6B", num_labels=num_labels)

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

多标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, GPTJForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B")
>>> model = GPTJForSequenceClassification.from_pretrained("EleutherAI/gpt-j-6B", 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 = GPTJForSequenceClassification.from_pretrained(
...     "EleutherAI/gpt-j-6B", 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

GPTJForQuestionAnswering

class transformers.GPTJForQuestionAnswering

< >

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

一个 Gptj transformer,顶部带有跨度分类头,用于抽取式问答任务,如 SQuAD(在隐藏状态输出之上添加一个线性层来计算span start logitsspan 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.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

参数

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

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

    什么是输入 ID?

  • 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) — 用于区分输入中第一句和第二句的 segment 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_dim), optional) — 可选地,您可以通过直接传递嵌入表示来代替传递 input_ids。如果您想比模型内部的嵌入查找矩阵获得对如何将 input_ids 索引转换为相关向量的更多控制,这会很有用。
  • start_positions (torch.LongTensor of shape (batch_size,), optional) — 用于计算 token 分类损失的标记跨度开始位置的标签。位置被限制在序列长度(sequence_length)内。序列外的位置不会被计入损失计算。
  • end_positions (torch.LongTensor of shape (batch_size,), optional) — 用于计算 token 分类损失的标记跨度结束位置的标签。位置被限制在序列长度(sequence_length)内。序列外的位置不会被计入损失计算。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.QuestionAnsweringModelOutput 对象,或者一个 torch.FloatTensor 的元组(如果传入了 return_dict=False 或者当 config.return_dict=False 时),其中包含根据配置(GPTJConfig)和输入而产生的各种元素。

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

GPTJForQuestionAnswering 的前向传播方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, GPTJForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B")
>>> model = GPTJForQuestionAnswering.from_pretrained("EleutherAI/gpt-j-6B")

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

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