Transformers 文档
Llama
并获得增强的文档体验
开始使用
该模型于 2023-02-27 发布,并于 2023-03-16 添加到 Hugging Face Transformers。
Llama
Llama 是一系列大型语言模型,参数范围从 7B 到 65B。这些模型专注于高效推理(对服务语言模型很重要),方法是使用更多 token 训练更小的模型,而不是使用更少 token 训练更大的模型。Llama 模型基于 GPT 架构,但它使用预归一化来提高训练稳定性,将 ReLU 替换为 SwiGLU 来提高性能,并用旋转位置嵌入 (RoPE) 替换绝对位置嵌入以更好地处理更长的序列长度。
您可以在 Huggy Llama 组织下找到所有原始 Llama 检查点。
单击右侧边栏中的 Llama 模型,了解如何将 Llama 应用于不同语言任务的更多示例。
下面的示例演示了如何使用 Pipeline 或 AutoModel,以及从命令行生成文本。
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
< source >( 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 (
strorfunction, 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 toTrue) — 模型是否应返回最后一个 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 toFalse) — 是否绑定词嵌入权重。 - rope_parameters (
RopeParameters, optional) — 包含 RoPE 嵌入配置参数的字典。该字典应包含rope_theta的值,以及在您希望将 RoPE 与更长的max_position_embeddings一起使用时用于缩放的可选参数。 - attention_bias (
bool, optional, defaults toFalse) — 在自注意力中是否使用偏置项(query、key、value 和 output projection 层)。 - attention_dropout (
float, optional, defaults to 0.0) — 注意力概率的 dropout 率。 - mlp_bias (
bool, optional, defaults toFalse) — 在 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.configLlamaTokenizer
class transformers.LlamaTokenizer
< source >( 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,dictorlist, optional) — 词汇表文件的路径、字典或token列表。 - merges (
strorlist, optional) — 合并文件(merges file)的路径或合并列表。 - clean_up_tokenization_spaces (
bool, optional, defaults toFalse) — 解码后是否清理空格,清理操作包括去除多余空格等潜在的“伪影”。 - unk_token (
strortokenizers.AddedToken, optional, defaults to"<unk>") — 未知token。词汇表中没有的token将无法转换为ID,并被设置为此token。 - bos_token (
strortokenizers.AddedToken, optional, defaults to"<s>") — 预训练期间使用的序列开始token。可用作序列分类器token。 - eos_token (
strortokenizers.AddedToken, optional, defaults to"</s>") — 序列结束token。 - add_bos_token (
bool, optional, defaults toTrue) — 是否在序列开始时添加bos_token。 - add_eos_token (
bool, optional, defaults toFalse) — 是否在序列结束时添加eos_token。 - use_default_system_prompt (
bool, optional, defaults toFalse) — 是否使用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_token 或 eos_token,请确保在初始化模型时指定它们,或调用 tokenizer.update_post_processor() 以确保后处理正确完成(否则编码序列的第一个token和最后一个token的值将不正确)。有关更多详细信息,请查看 [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) 文档。
此分词器继承自 PreTrainedTokenizerFast,其中包含了大部分主要方法。用户应参考此父类以获取有关这些方法的更多信息。
get_special_tokens_mask
< source >( token_ids_0: list[int] token_ids_1: list[int] | None = None already_has_special_tokens: bool = False ) → 一个介于 0 和 1 之间的整数列表
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.
LlamaTokenizerFast
class transformers.LlamaTokenizer
< source >( 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,dictorlist, optional) — 词汇表文件的路径、字典或token列表。 - merges (
strorlist, optional) — 合并文件(merges file)的路径或合并列表。 - clean_up_tokenization_spaces (
bool, optional, defaults toFalse) — 解码后是否清理空格,清理操作包括去除多余空格等潜在的“伪影”。 - unk_token (
strortokenizers.AddedToken, optional, defaults to"<unk>") — 未知token。词汇表中没有的token将无法转换为ID,并被设置为此token。 - bos_token (
strortokenizers.AddedToken, optional, defaults to"<s>") — 预训练期间使用的序列开始token。可用作序列分类器token。 - eos_token (
strortokenizers.AddedToken, optional, defaults to"</s>") — 序列结束token。 - add_bos_token (
bool, optional, defaults toTrue) — 是否在序列开始时添加bos_token。 - add_eos_token (
bool, optional, defaults toFalse) — 是否在序列结束时添加eos_token。 - use_default_system_prompt (
bool, optional, defaults toFalse) — 是否使用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_token 或 eos_token,请确保在初始化模型时指定它们,或调用 tokenizer.update_post_processor() 以确保后处理正确完成(否则编码序列的第一个token和最后一个token的值将不正确)。有关更多详细信息,请查看 [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) 文档。
此分词器继承自 PreTrainedTokenizerFast,其中包含了大部分主要方法。用户应参考此父类以获取有关这些方法的更多信息。
get_special_tokens_mask
< source >( token_ids_0: list[int] token_ids_1: list[int] | None = None already_has_special_tokens: bool = False ) → 一个介于 0 和 1 之间的整数列表
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.
使用当前的 bos_token 和 eos_token 更新底层后处理器。
LlamaModel
class transformers.LlamaModel
< source >( config: LlamaConfig )
参数
- config (LlamaConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化模型不会加载与模型相关的权重,只会加载配置。要加载模型权重,请查看 from_pretrained() 方法。
输出原始隐藏状态且顶部没有特定头的Llama模型。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( 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.LongTensorof shape(batch_size, sequence_length), optional) — 输入序列token在词汇表中的索引。默认情况下将忽略填充(padding)。可以使用 AutoTokenizer 获取索引。有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — 用于避免对填充token索引执行注意力操作的掩码。掩码值选择在[0, 1]中:- 1 表示**未被掩码**的token,
- 0 表示**被掩码**的token。
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 输入序列中每个token在位置嵌入中的位置索引。选择范围为[0, config.n_positions - 1]。 - past_key_values (
~cache_utils.Cache, optional) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。当use_cache=True或config.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.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传入嵌入表示而不是input_ids。如果您希望对如何将input_ids索引转换为关联向量有比模型内部嵌入查找矩阵更多的控制,这将非常有用。 - cache_position (
torch.LongTensorof 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=False 或 config.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=Truein the cross-attention blocks) that can be used (seepast_key_valuesinput) 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
< source >( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )
参数
- config (LlamaForCausalLM) — 模型配置类,包含模型的所有参数。使用配置文件初始化模型不会加载与模型相关的权重,只会加载配置。要加载模型权重,请查看 from_pretrained() 方法。
用于因果语言建模的 Llama 模型。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( 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.LongTensorof shape(batch_size, sequence_length), optional) — 输入序列token在词汇表中的索引。默认情况下将忽略填充(padding)。可以使用 AutoTokenizer 获取索引。有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — 用于避免对填充token索引执行注意力操作的掩码。掩码值选择在[0, 1]中:- 1 表示**未被掩码**的token,
- 0 表示**被掩码**的token。
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 输入序列中每个token在位置嵌入中的位置索引。选择范围为[0, config.n_positions - 1]。 - past_key_values (
~cache_utils.Cache, optional) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。当use_cache=True或config.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.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传入嵌入表示而不是input_ids。如果您希望对如何将input_ids索引转换为关联向量有比模型内部嵌入查找矩阵更多的控制,这将非常有用。 - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 用于计算掩码语言建模损失的标签。索引应在[0, ..., config.vocab_size]或 -100 之间(请参阅input_idsdocstring)。索引设置为-100的token将被忽略(被掩码),损失仅针对标签在[0, ..., config.vocab_size]中的token计算。 - use_cache (
bool, optional) — 如果设置为True,将返回past_key_values键值状态,可用于加速解码(参见past_key_values)。 - cache_position (
torch.LongTensorof shape(sequence_length), optional) — 描述输入序列token在序列中位置的索引。与position_ids不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。 - logits_to_keep (
Union[int, torch.Tensor], optional, defaults to0) — 如果是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=False 或 config.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
forward
< source >( 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.LongTensorof shape(batch_size, sequence_length), optional) — 输入序列token在词汇表中的索引。默认情况下将忽略填充(padding)。可以使用 AutoTokenizer 获取索引。有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — 用于避免对填充token索引执行注意力操作的掩码。掩码值选择在[0, 1]中:- 1 表示**未被掩码**的token,
- 0 表示**被掩码**的token。
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 输入序列中每个token在位置嵌入中的位置索引。选择范围为[0, config.n_positions - 1]。 - 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 thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size]or -100 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]. - use_cache (
bool, optional) — If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values).
返回
transformers.modeling_outputs.SequenceClassifierOutputWithPast 或 tuple(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
forward
< source >( 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.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof 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]. - 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 thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - start_positions (
torch.LongTensorof 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.LongTensorof 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.QuestionAnsweringModelOutput 或 tuple(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.FloatTensorof shape(1,), 可选, 当提供labels时返回) — 总范围提取损失是起始位置和结束位置的交叉熵之和。 -
start_logits (
torch.FloatTensorof shape(batch_size, sequence_length)) — 范围起始分数(SoftMax 之前)。 -
end_logits (
torch.FloatTensorof shape(batch_size, sequence_length)) — 范围结束分数(SoftMax 之前)。 -
hidden_states (
tuple(torch.FloatTensor), optional, 当传递output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor), optional, 当传递output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
The GenericForQuestionAnswering forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
LlamaForTokenClassification
forward
< source >( 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.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof 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]. - 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 thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size]or -100 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]. - use_cache (
bool, optional) — If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values).
返回
transformers.modeling_outputs.TokenClassifierOutput 或 tuple(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实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。