Transformers 文档

Llama

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2023-02-27 发布,并于 2023-03-16 添加到 Hugging Face Transformers。

PyTorch FlashAttention SDPA Tensor parallelism

Llama

Llama 是一系列大型语言模型,参数范围从 7B 到 65B。这些模型专注于高效推理(对服务语言模型很重要),方法是使用更多 token 训练更小的模型,而不是使用更少 token 训练更大的模型。Llama 模型基于 GPT 架构,但它使用预归一化来提高训练稳定性,将 ReLU 替换为 SwiGLU 来提高性能,并用旋转位置嵌入 (RoPE) 替换绝对位置嵌入以更好地处理更长的序列长度。

您可以在 Huggy Llama 组织下找到所有原始 Llama 检查点。

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

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

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

pipeline = pipeline(
    task="text-generation",
    model="huggyllama/llama-7b",
    dtype=torch.float16,
    device=0
)
pipeline("Plants create energy through a process known as")

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

以下示例使用torchao仅将权重量化为int4。

# pip install torchao
import torch
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer

quantization_config = TorchAoConfig("int4_weight_only", group_size=128)
model = AutoModelForCausalLM.from_pretrained(
    "huggyllama/llama-30b",
    dtype=torch.bfloat16,
    device_map="auto",
    quantization_config=quantization_config
)

tokenizer = AutoTokenizer.from_pretrained("huggyllama/llama-30b")
input_ids = tokenizer("Plants create energy through a process known as", return_tensors="pt").to(model.device)

output = model.generate(**input_ids, cache_implementation="static")
print(tokenizer.decode(output[0], skip_special_tokens=True))

使用 AttentionMaskVisualizer 可以更好地了解模型可以关注哪些 token,不能关注哪些 token。

from transformers.utils.attention_visualizer import AttentionMaskVisualizer

visualizer = AttentionMaskVisualizer("huggyllama/llama-7b")
visualizer("Plants create energy through a process known as")

注意事项

  • tokenizer 是基于 SentencePiece 的字节对编码模型。在解码过程中,如果第一个 token 是单词的开头(例如,“Banana”),tokenizer 不会在字符串前面加上前缀空格。

LlamaConfig

class transformers.LlamaConfig

< >

( vocab_size: int | None = 32000 hidden_size: int | None = 4096 intermediate_size: int | None = 11008 num_hidden_layers: int | None = 32 num_attention_heads: int | None = 32 num_key_value_heads: int | None = None hidden_act: str | None = 'silu' max_position_embeddings: int | None = 2048 initializer_range: float | None = 0.02 rms_norm_eps: int | None = 1e-06 use_cache: bool | None = True pad_token_id: int | None = None bos_token_id: int | None = 1 eos_token_id: int | None = 2 pretraining_tp: int | None = 1 tie_word_embeddings: bool | None = False rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict[str, transformers.modeling_rope_utils.RopeParameters] | None = None attention_bias: bool | None = False attention_dropout: float | None = 0.0 mlp_bias: bool | None = False head_dim: int | None = None **kwargs )

参数

  • vocab_size (int, optional, defaults to 32000) — LLaMA 模型的词汇表大小。定义了调用 LlamaModel 时传递的 inputs_ids 可以表示的不同 token 的数量。
  • hidden_size (int, optional, defaults to 4096) — 隐藏表示的维度。
  • intermediate_size (int, optional, defaults to 11008) — MLP 表示的维度。
  • num_hidden_layers (int, optional, defaults to 32) — Transformer 解码器中的隐藏层数。
  • num_attention_heads (int, optional, defaults to 32) — Transformer 解码器中每个注意力层的注意力头数。
  • num_key_value_heads (int, optional) — 用于实现分组查询注意力 (Grouped Query Attention) 的 key_value 头数。如果 num_key_value_heads=num_attention_heads,模型将使用多头注意力 (MHA);如果 num_key_value_heads=1,模型将使用多查询注意力 (MQA),否则使用 GQA。将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组中的所有原始头进行均值池化来构建。有关更多详细信息,请查看 这篇论文。如果未指定,将默认为 num_attention_heads
  • hidden_act (str or function, optional, defaults to "silu") — 解码器中的非线性激活函数(函数或字符串)。
  • max_position_embeddings (int, optional, defaults to 2048) — 该模型可能使用的最大序列长度。Llama 1 支持多达 2048 个 token,Llama 2 支持多达 4096 个 token,CodeLlama 支持多达 16384 个 token。
  • initializer_range (float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • rms_norm_eps (float, optional, defaults to 1e-06) — rms 归一化层使用的 epsilon。
  • use_cache (bool, optional, defaults to True) — 模型是否应返回最后一个 key/values attention(并非所有模型都使用)。仅当 config.is_decoder=True 时相关。
  • pad_token_id (int, optional) — 填充 token id。
  • bos_token_id (int, optional, defaults to 1) — 流开始 token id。
  • eos_token_id (int, optional, defaults to 2) — 流结束 token id。
  • pretraining_tp (int, optional, defaults to 1) — 实验性功能。预训练期间使用的张量并行等级。请参阅 此文档 以了解更多信息。此值对于确保预训练结果的精确可复现性是必需的。请参阅 此问题
  • tie_word_embeddings (bool, optional, defaults to False) — 是否绑定词嵌入权重。
  • rope_parameters (RopeParameters, optional) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,以及在您希望将 RoPE 与更长的 max_position_embeddings 一起使用时用于缩放的可选参数。
  • attention_bias (bool, optional, defaults to False) — 在自注意力中是否使用偏置项(query、key、value 和 output projection 层)。
  • attention_dropout (float, optional, defaults to 0.0) — 注意力概率的 dropout 率。
  • mlp_bias (bool, optional, defaults to False) — 在 MLP 层中 up_proj、down_proj 和 gate_proj 层是否使用偏置项。
  • head_dim (int, optional) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads。

这是用于存储 LlamaModel 配置的配置类。它用于根据指定的参数实例化 LLaMA 模型,定义模型架构。使用默认值实例化配置将生成与 LLaMA-7B 类似的配置。例如 meta-llama/Llama-2-7b-hf

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

>>> from transformers import LlamaModel, LlamaConfig

>>> # Initializing a LLaMA llama-7b style configuration
>>> configuration = LlamaConfig()

>>> # Initializing a model from the llama-7b style configuration
>>> model = LlamaModel(configuration)

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

LlamaTokenizer

class transformers.LlamaTokenizer

< >

( vocab: str | dict | list | None = None merges: str | list | None = None clean_up_tokenization_spaces = False unk_token = '<unk>' bos_token = '<s>' eos_token = '</s>' use_default_system_prompt = False legacy = False add_prefix_space = None **kwargs )

参数

  • vocab (str, dict or list, optional) — 词汇表文件的路径、字典或token列表。
  • merges (str or list, optional) — 合并文件(merges file)的路径或合并列表。
  • clean_up_tokenization_spaces (bool, optional, defaults to False) — 解码后是否清理空格,清理操作包括去除多余空格等潜在的“伪影”。
  • unk_token (str or tokenizers.AddedToken, optional, defaults to "<unk>") — 未知token。词汇表中没有的token将无法转换为ID,并被设置为此token。
  • bos_token (str or tokenizers.AddedToken, optional, defaults to "<s>") — 预训练期间使用的序列开始token。可用作序列分类器token。
  • eos_token (str or tokenizers.AddedToken, optional, defaults to "</s>") — 序列结束token。
  • add_bos_token (bool, optional, defaults to True) — 是否在序列开始时添加 bos_token
  • add_eos_token (bool, optional, defaults to False) — 是否在序列结束时添加 eos_token
  • use_default_system_prompt (bool, optional, defaults to False) — 是否使用Llama的默认系统提示词
  • add_prefix_space (bool, optional) — 分词器是否应自动添加前缀空格

构建 Llama 分词器。基于字节级字节对编码。

这主要使用 ByteFallback 且不进行规范化。

>>> from transformers import LlamaTokenizer

>>> tokenizer = LlamaTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer")
>>> tokenizer.encode("Hello this is a test")
[1, 15043, 445, 338, 263, 1243]

如果您想更改 bos_tokeneos_token,请确保在初始化模型时指定它们,或调用 tokenizer.update_post_processor() 以确保后处理正确完成(否则编码序列的第一个token和最后一个token的值将不正确)。有关更多详细信息,请查看 [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) 文档。

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

get_special_tokens_mask

< >

( token_ids_0: list[int] token_ids_1: list[int] | None = None already_has_special_tokens: bool = False ) 一个介于 0 和 1 之间的整数列表

参数

  • token_ids_0 — (可能已格式化的)序列的 ID 列表。
  • token_ids_1 — 当 already_has_special_tokens=True 时未使用。在这种情况下必须为 None。
  • already_has_special_tokens — 序列是否已用特殊token格式化。

返回

一个范围在 [0, 1] 的整数列表

特殊令牌为 1,序列令牌为 0。

Retrieve sequence ids from a token list that has no special tokens added.

For fast tokenizers, data collators call this with already_has_special_tokens=True to build a mask over an already-formatted sequence. In that case, we compute the mask by checking membership in all_special_ids.

save_vocabulary

< >

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

LlamaTokenizerFast

class transformers.LlamaTokenizer

< >

( vocab: str | dict | list | None = None merges: str | list | None = None clean_up_tokenization_spaces = False unk_token = '<unk>' bos_token = '<s>' eos_token = '</s>' use_default_system_prompt = False legacy = False add_prefix_space = None **kwargs )

参数

  • vocab (str, dict or list, optional) — 词汇表文件的路径、字典或token列表。
  • merges (str or list, optional) — 合并文件(merges file)的路径或合并列表。
  • clean_up_tokenization_spaces (bool, optional, defaults to False) — 解码后是否清理空格,清理操作包括去除多余空格等潜在的“伪影”。
  • unk_token (str or tokenizers.AddedToken, optional, defaults to "<unk>") — 未知token。词汇表中没有的token将无法转换为ID,并被设置为此token。
  • bos_token (str or tokenizers.AddedToken, optional, defaults to "<s>") — 预训练期间使用的序列开始token。可用作序列分类器token。
  • eos_token (str or tokenizers.AddedToken, optional, defaults to "</s>") — 序列结束token。
  • add_bos_token (bool, optional, defaults to True) — 是否在序列开始时添加 bos_token
  • add_eos_token (bool, optional, defaults to False) — 是否在序列结束时添加 eos_token
  • use_default_system_prompt (bool, optional, defaults to False) — 是否使用Llama的默认系统提示词
  • add_prefix_space (bool, optional) — 分词器是否应自动添加前缀空格

构建 Llama 分词器。基于字节级字节对编码。

这主要使用 ByteFallback 且不进行规范化。

>>> from transformers import LlamaTokenizer

>>> tokenizer = LlamaTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer")
>>> tokenizer.encode("Hello this is a test")
[1, 15043, 445, 338, 263, 1243]

如果您想更改 bos_tokeneos_token,请确保在初始化模型时指定它们,或调用 tokenizer.update_post_processor() 以确保后处理正确完成(否则编码序列的第一个token和最后一个token的值将不正确)。有关更多详细信息,请查看 [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) 文档。

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

get_special_tokens_mask

< >

( token_ids_0: list[int] token_ids_1: list[int] | None = None already_has_special_tokens: bool = False ) 一个介于 0 和 1 之间的整数列表

参数

  • token_ids_0 — (可能已格式化的)序列的 ID 列表。
  • token_ids_1 — 当 already_has_special_tokens=True 时未使用。在这种情况下必须为 None。
  • already_has_special_tokens — 序列是否已用特殊token格式化。

返回

一个范围在 [0, 1] 的整数列表

特殊令牌为 1,序列令牌为 0。

Retrieve sequence ids from a token list that has no special tokens added.

For fast tokenizers, data collators call this with already_has_special_tokens=True to build a mask over an already-formatted sequence. In that case, we compute the mask by checking membership in all_special_ids.

update_post_processor

< >

( )

使用当前的 bos_tokeneos_token 更新底层后处理器。

save_vocabulary

< >

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

LlamaModel

class transformers.LlamaModel

< >

( config: LlamaConfig )

参数

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

输出原始隐藏状态且顶部没有特定头的Llama模型。

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

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

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None cache_position: torch.LongTensor | None = None use_cache: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.BaseModelOutputWithPast or tuple(torch.FloatTensor)

参数

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

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

    什么是输入 ID?

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

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

    什么是注意力掩码?

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

    什么是位置 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,则要求用户仅输入未处理的 input_ids(即未将其过去的键值状态提供给此模型的那些)形状为 (batch_size, unprocessed_length),而不是所有 input_ids 形状为 (batch_size, sequence_length)

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传入嵌入表示而不是 input_ids。如果您希望对如何将 input_ids 索引转换为关联向量有比模型内部嵌入查找矩阵更多的控制,这将非常有用。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 描述输入序列token在序列中位置的索引。与 position_ids 不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。
  • use_cache (bool, optional) — 如果设置为 True,将返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。

返回

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

一个 transformers.modeling_outputs.BaseModelOutputWithPast 或一个 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.return_dict=False 时),其中包含根据配置 (LlamaConfig) 和输入而定的各种元素。

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

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

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

LlamaForCausalLM

class transformers.LlamaForCausalLM

< >

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

用于因果语言建模的 Llama 模型。

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

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

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None cache_position: torch.LongTensor | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.CausalLMOutputWithPast or tuple(torch.FloatTensor)

参数

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

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

    什么是输入 ID?

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

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

    什么是注意力掩码?

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

    什么是位置 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,则要求用户仅输入未处理的 input_ids(即未将其过去的键值状态提供给此模型的那些)形状为 (batch_size, unprocessed_length),而不是所有 input_ids 形状为 (batch_size, sequence_length)

  • 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.vocab_size] 或 -100 之间(请参阅 input_ids docstring)。索引设置为 -100 的token将被忽略(被掩码),损失仅针对标签在 [0, ..., config.vocab_size] 中的token计算。
  • use_cache (bool, optional) — 如果设置为 True,将返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 描述输入序列token在序列中位置的索引。与 position_ids 不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。
  • logits_to_keep (Union[int, torch.Tensor], optional, defaults to 0) — 如果是 int,则计算最后 logits_to_keep 个 token 的 logits。如果是 0,则计算所有 input_ids 的 logits(特殊情况)。生成时只需要最后一个 token 的 logits,只计算该 token 的 logits 可以节省内存,这对于长序列或大词汇表大小非常重要。如果是 torch.Tensor,则必须是 1D 张量,对应于序列长度维度中要保留的索引。这在使用打包张量格式(batch 和 sequence length 在单个维度中)时很有用。

返回

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

一个 transformers.modeling_outputs.CausalLMOutputWithPast 或一个 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.return_dict=False 时),其中包含根据配置 (LlamaConfig) 和输入而定的各种元素。

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

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

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

示例

>>> from transformers import AutoTokenizer, LlamaForCausalLM

>>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
>>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")

>>> prompt = "Hey, are you conscious? Can you talk to me?"
>>> inputs = tokenizer(prompt, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."

LlamaForSequenceClassification

class transformers.LlamaForSequenceClassification

< >

( config )

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.SequenceClassifierOutputWithPast or tuple(torch.FloatTensor)

参数

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

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

    什么是输入 ID?

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

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

    什么是注意力掩码?

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

    什么是位置 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).

  • 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.
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — Labels for computing the masked language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with 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).

返回

transformers.modeling_outputs.SequenceClassifierOutputWithPasttuple(torch.FloatTensor)

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

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

The GenericForSequenceClassification forward method, overrides the __call__ special method.

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

LlamaForQuestionAnswering

class transformers.LlamaForQuestionAnswering

< >

( config )

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None start_positions: torch.LongTensor | None = None end_positions: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.QuestionAnsweringModelOutput or tuple(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.

    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?

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

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

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

返回

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 (None) 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 GenericForQuestionAnswering forward method, overrides the __call__ special method.

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

LlamaForTokenClassification

class transformers.LlamaForTokenClassification

< >

( config )

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.TokenClassifierOutput or tuple(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.

    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?

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

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

  • 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.
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — Labels for computing the masked language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with 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).

返回

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 (None) 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 GenericForTokenClassification forward method, overrides the __call__ special method.

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

在 GitHub 上更新

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