Transformers documentation
Llama4
该模型于 2025-04-05 贡献至 Hugging Face Transformers。
Llama4
Llama 4, developed by Meta, introduces a new auto-regressive Mixture-of-Experts (MoE) architecture. This generation includes two models:
- 能力出众的 Llama 4 Maverick,总参数量约 400B,其中 17B 为激活参数,包含 128 个专家。
- 高效的 Llama 4 Scout 同样拥有 17B 的激活参数,总参数量约为 109B,仅使用了 16 个专家。
两个模型均采用早期融合(early fusion)技术以实现原生多模态能力,使其能够处理文本和图像输入。 Maverick 和 Scout 均在涵盖 200 种语言的数据上进行了训练,训练数据量最高可达 40 万亿个 token(其中针对包括阿拉伯语、西班牙语、德语和印地语在内的 12 种语言提供了特定的微调支持)。
在部署方面,Llama 4 Scout 专为易用性而设计,可通过即时 4 位或 8 位 int4 量化,适配单张服务器级 GPU,而 Maverick 则提供 BF16 和 FP8 格式。这些模型基于自定义的 Llama 4 Community License Agreement 发布,该协议可在模型仓库中获取。
您可以在 meta-llama 组织下找到所有原始的 Llama 检查点。
Llama 4 系列模型提供两种规格:109B 和 402B 参数。这两种规格都极其庞大,无法在普通设备上运行。请参阅下文,了解一些降低模型内存用量的示例。
为了让下载更快且更具容错性,我们建议按照以下方式安装
hf_xet依赖项:pip install transformers[hf_xet]
以下示例演示了如何使用 Pipeline 或 AutoModel 进行生成。此外,我们还提供了一个示例,展示如何切换相关属性以启用超长上下文生成,因为某些 Llama 4 变体的上下文长度可达 1000 万 token。
from transformers import pipeline
model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"
messages = [
{"role": "user", "content": "what is the recipe of mayonnaise?"},
]
pipe = pipeline(
"text-generation",
model=model_id,
device_map="auto",
)
output = pipe(messages, do_sample=False, max_new_tokens=200)
print(output[0]["generated_text"][-1]["content"])
from transformers import AutoTokenizer, Llama4ForConditionalGeneration
model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
device_map="auto",
)
messages = [
{"role": "user", "content": "Who are you?"},
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=100)
outputs = tokenizer.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:])
print(outputs[0])
from transformers import AutoProcessor, Llama4ForConditionalGeneration
model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"
processor = AutoProcessor.from_pretrained(model_id)
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
device_map="auto",
)
img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg"
messages = [
{
"role": "user",
"content": [
{"type": "image", "url": img_url},
{"type": "text", "text": "Describe this image in two sentences."},
]
},
]
inputs = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt",
).to(model.device)
outputs = model.generate(
**inputs,
max_new_tokens=256,
)
response = processor.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:])[0]
print(response)
from transformers import AutoProcessor, Llama4ForConditionalGeneration
model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"
processor = AutoProcessor.from_pretrained(model_id)
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
device_map="auto",
)
url1 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg"
url2 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/cat_style_layout.png"
messages = [
{
"role": "user",
"content": [
{"type": "image", "url": url1},
{"type": "image", "url": url2},
{"type": "text", "text": "Can you describe how these two images are similar, and how they differ?"},
]
},
]
inputs = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt",
).to(model.device)
outputs = model.generate(
**inputs,
max_new_tokens=256,
)
response = processor.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:])[0]
print(response)注意:以下示例同时使用了 device_map="auto" 和 flex-attention。
请使用 torchrun 以张量并行模式运行此示例。
未来,我们将致力于实现在不使用张量并行的情况下,使用 device_map="auto" 和 flex-attention 进行运行。
import time
import torch
from transformers import AutoTokenizer, Llama4ForConditionalGeneration
file = "very_long_context_prompt.txt"
model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"
with open(file, "r") as f:
very_long_text = "\n".join(f.readlines())
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
device_map="auto",
attn_implementation="flex_attention",
)
messages = [
{"role": "user", "content": f"Look at the following texts: [{very_long_text}]\n\n\n\nWhat are the books, and who wrote them? Make me a nice list."},
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)
torch_device_module = getattr(torch, model.device.type, torch.cuda)
torch_device_module.synchronize()
start = time.time()
out = model.generate(
**inputs,
prefill_chunk_size=2048*8,
max_new_tokens=300,
cache_implementation="hybrid",
)
print(time.time()-start)
print(tokenizer.batch_decode(out[:, inputs["input_ids"].shape[-1]:]))
print(f"{torch_device_module.max_memory_allocated(model.device) / 1024**3:.2f} GiB")效率;如何充分发挥 llama 4 的性能
Attention 方法
更新默认注意力函数可以显著提升计算性能和内存使用效率。有关我们接口的详细说明,请参阅Attention Interface概述。
在发布时,Llama 4 模型支持以下注意力机制:eager、flex_attention、sdpa。我们建议使用 flex_attention 以获得最佳效果。
在模型初始化步骤中切换注意力机制:
设置 Flex Attention 可确保模型在处理超长上下文时获得最佳效果。
注意:以下示例同时使用了
device_map="auto"和 flex-attention。 请使用torchrun以张量并行模式运行此示例。未来,我们将致力于实现在不使用张量并行的情况下,使用
device_map="auto"和 flex-attention 进行运行。
from transformers import Llama4ForConditionalGeneration
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
attn_implementation="flex_attention",
device_map="auto",
)sdpa 注意力方法通常比 eager 方法在计算效率上更高。
from transformers import Llama4ForConditionalGeneration
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
attn_implementation="sdpa",
device_map="auto",
)eager 注意力方法为默认设置,因此加载模型时无需进行任何更改:
from transformers import Llama4ForConditionalGeneration
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
device_map="auto",
)量化
量化通过以较低精度表示权重来降低大模型的内存负担。有关可用的量化后端,请参阅量化概述。 在发布时,FBGEMM 和 LLM-Compressor 均受支持;在发布后的几天内,还将支持更多的量化方法。
以下示例同时使用了两者:
以下是一个使用 FBGEMM 方法以 FP8 格式加载 BF16 模型的示例:
from transformers import AutoTokenizer, FbgemmFp8Config, Llama4ForConditionalGeneration
model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id)
messages = [
{"role": "user", "content": "Who are you?"},
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
device_map="auto",
quantization_config=FbgemmFp8Config()
)
outputs = model.generate(**inputs.to(model.device), max_new_tokens=100)
outputs = tokenizer.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:])
print(outputs[0])要使用 LLM-Compressor 技术,我们建议利用随发布版本提供的预量化 FP8 检查点:
from transformers import AutoTokenizer, Llama4ForConditionalGeneration
model_id = "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8"
tokenizer = AutoTokenizer.from_pretrained(model_id)
messages = [
{"role": "user", "content": "Who are you?"},
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
tp_plan="auto",
device_map="auto",
)
outputs = model.generate(**inputs.to(model.device), max_new_tokens=100)
outputs = tokenizer.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:])
print(outputs[0])Offloading
启用 CPU 卸载意味着,当可用的 GPU 显存不足以加载整个模型时,模型的部分组件可能会被移至 CPU 而非 GPU。 在推理阶段,不同的组件会动态地从 GPU 加载或卸载。这确保了只要 CPU 内存足够,模型就可以加载到较小的机器上。 然而,这也会因增加通信开销而降低推理速度。
要启用 CPU 卸载,只需在加载模型时将 device_map 指定为 auto:
from transformers import Llama4ForConditionalGeneration
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
device_map="auto",
)Llama4Config
class transformers.Llama4Config
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneboi_token_index: int = 200080eoi_token_index: int = 200081image_token_index: int = 200092tie_word_embeddings: bool = False )
参数
- vision_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。 - text_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。 - boi_token_index (
int,可选,默认为 200080) — 用于包裹图像提示的图像起始(begin-of-image)标记索引。 - eoi_token_index (
int,可选,默认为 200081) — 用于包裹图像提示的图像结束标记索引。 - image_token_index (
int,可选,默认为200092) — 用作输入图像占位符的图像 token 索引。 - tie_word_embeddings (
bool,可选,默认为False) — 是否根据模型的tied_weights_keys映射来绑定权重嵌入。
这是用于存储 Llama4ForConditionalGeneration 配置的类。它根据指定的参数实例化 Llama4 模型,并定义模型架构。使用默认值实例化配置将得到与 meta-llama/Llama-4-Scout-17B-16E 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
>>> from transformers import Llama4Model, Llama4Config
>>> # Initializing a Llama4 7B style configuration
>>> configuration = Llama4Config()
>>> # Initializing a model from the Llama4 7B style configuration
>>> model = Llama4Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configLlama4TextConfig
class transformers.Llama4TextConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 202048hidden_size: int = 5120intermediate_size: int = 8192intermediate_size_mlp: int = 16384num_hidden_layers: int = 48num_attention_heads: int = 40num_key_value_heads: int = 8head_dim: int = 128hidden_act: str = 'silu'max_position_embeddings: int = 131072initializer_range: float = 0.02rms_norm_eps: float = 1e-05use_cache: bool = Truepad_token_id: int | None = Nonebos_token_id: int | None = 1eos_token_id: int | list[int] | None = 2tie_word_embeddings: bool = Falseattention_dropout: float | int = 0.0num_experts_per_tok: int = 1num_local_experts: int = 16moe_layers: list[int] | None = Noneinterleave_moe_layer_step: int = 1use_qk_norm: bool = Trueoutput_router_logits: bool = Falserouter_aux_loss_coef: float = 0.001router_jitter_noise: float = 0.0rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneno_rope_layers: list[int] | None = Noneno_rope_layer_interval: int = 4attention_chunk_size: int | None = 8192layer_types: list[str] | None = Noneattn_temperature_tuning: bool = Truefloor_scale: int = 8192attn_scale: float = 0.1attention_bias: bool = False )
参数
- vocab_size (
int,可选,默认为202048) — 模型的词汇表大小。定义了input_ids可以表示的不同 token 数量。 - hidden_size (
int,可选,默认为5120) — 隐藏表示的维度。 - intermediate_size (
int,可选,默认为8192) — MLP 表示的维度。 - intermediate_size_mlp (
int,可选,默认值为 16384) — 稠密 MLP 层的中间维度。较大的值会增加 FFN 的容量和计算量。 - num_hidden_layers (
int,可选,默认为48) — Transformer 解码器中的隐藏层数量。 - num_attention_heads (
int,可选,默认为40) — Transformer 解码器中每个注意力层的注意力头数量。 - num_key_value_heads (
int, 可选,默认为8) — 这是用于实现 Grouped Query Attention 的 key_value 头数。如果num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行 meanpooling 来构建。更多详情请参阅 这篇论文。如果未指定,则默认为num_attention_heads。 - head_dim (
int,可选,默认为128) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads - hidden_act (
str,可选,默认为silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - max_position_embeddings (
int,可选,默认为131072) — 该模型可能使用的最大序列长度。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - rms_norm_eps (
float,可选,默认为1e-05) — RMS 归一化层使用的 epsilon 值。 - use_cache (
bool,可选,默认为True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当config.is_decoder=True或模型为仅解码器生成式模型时相关。 - pad_token_id (
int, 可选) — 词表中用于填充的 token id。 - bos_token_id (
int,可选,默认为1) — 词汇表中用于表示流起始的 token id。 - eos_token_id (
Union[int, list[int]],可选,默认为2) — 词汇表中用于表示流结束(end-of-stream)的 token id。 - tie_word_embeddings (
bool,可选,默认为False) — 是否根据模型的tied_weights_keys映射来绑定权重嵌入。 - attention_dropout (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - num_experts_per_tok (
int,可选,默认为1) — 每个 token 路由到的专家数量。这是 token 选择路由中的 top-k 值。 - num_local_experts (
int,可选,默认为16) — 每个设备上的本地专家数量。num_experts应能被num_local_experts整除。 - moe_layers (
list[int], 可选) — 使用 MoE 的层索引列表。设置时会覆盖interleave_moe_layer_step。 - interleave_moe_layer_step (
int,可选,默认为 1) — 当moe_layers为None时,MoE 层之间的间隔。值越大,MoE 层数越少。 - use_qk_norm (
bool,可选,默认为True) — 是否在 RoPE 层对查询/键进行 L2 归一化。启用后可稳定注意力机制。 - output_router_logits (
bool,可选,默认为False) — 是否由模型返回路由器 logits。启用此选项后,模型还将输出辅助损失,包括负载均衡损失和路由器 z-loss。 - router_aux_loss_coef (
float,可选,默认值为0.001) — 辅助负载均衡损失系数。用于惩罚 MoE 模型中专家路由的不均衡。 - router_jitter_noise (
float,可选,默认值为0.0) — 在训练期间为 router logits 添加的噪声量,以实现更好的负载均衡。 - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含rope_theta的值,并且如果希望使用 RoPE 处理更长的max_position_embeddings,则可选地包含用于缩放的参数。 - no_rope_layers (
list[int], 可选) — 一个列表,其长度至少与模型中的层数相同。 索引位置处的1表示对应的层将使用 RoPE, 而0则表示该层为 NoPE 层。 - no_rope_layer_interval (
int,可选,默认值为 4) — 如果no_rope_layers为None,则会每隔no_rope_layer_interval层创建一个 NoPE 层。 - attention_chunk_size (
int,可选,默认值为 8192) — 注意力计算的块大小。较小的值会强制使用更局部的注意力机制,并降低内存占用。 - layer_types (
list[str], 可选) — 一个列表,用于显式地将每个层索引映射到其层类型。如果未提供,将根据 config 值自动生成。 - attn_temperature_tuning (
bool,可选,默认为True) — 是否根据序列长度动态缩放每个查询 token 的注意力温度。 推荐用于长序列(例如 >32k tokens),以保持输出结果的稳定性。 - floor_scale (
int,可选,默认为 8192) — 用于注意力温度调节的基础缩放(以 token 为单位)。值越大,缩放作用延迟到越长的位置。 - attn_scale (
float,可选,默认值为 0.1) — 注意力温度调节的强度。值越大,在长位置处的缩放程度越高。 - attention_bias (
bool,可选,默认为False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
这是用于存储 Llama4ForConditionalGeneration 配置的类。它根据指定的参数实例化 Llama4 模型,并定义模型架构。使用默认值实例化配置将得到与 meta-llama/Llama-4-Scout-17B-16E 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
Llama4VisionConfig
类 transformers.Llama4VisionConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 768hidden_act: str = 'gelu'num_hidden_layers: int = 34num_attention_heads: int = 16num_channels: int = 3intermediate_size: int = 5632vision_output_dim: int = 7680image_size: int | list[int] | tuple[int, int] = 448patch_size: int | list[int] | tuple[int, int] = 14norm_eps: float = 1e-05vision_feature_select_strategy: str = 'default'initializer_range: float = 0.02pixel_shuffle_ratio: float = 0.5projector_input_dim: int = 4096projector_output_dim: int = 4096multi_modal_projector_bias: bool = Falseprojector_dropout: float | int = 0.0attention_dropout: float | int = 0.0rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None )
参数
- hidden_size (
int,可选,默认为768) — 隐藏表示的维度。 - hidden_act (
str,可选,默认为gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - num_hidden_layers (
int,可选,默认为34) — Transformer 解码器中的隐藏层数量。 - num_attention_heads (
int,可选,默认为16) — Transformer 解码器中每个注意力层的注意力头数量。 - num_channels (
int,可选,默认为3) — 输入通道的数量。 - intermediate_size (
int,可选,默认为5632) — MLP 表示的维度。 - vision_output_dim (
int,可选,默认值为 7680) — 视觉模型输出的维度。包含带有中间层的 Transformer 编码器以及全局 Transformer 编码器的输出。 - image_size (
Union[int, list[int], tuple[int, int]],可选,默认为448) — 每张图片的尺寸(分辨率)。 - patch_size (
Union[int, list[int], tuple[int, int]],可选,默认为14) — 每个 patch 的大小(分辨率)。 - norm_eps (
float,可选,默认为1e-05) — 层归一化层所使用的 epsilon 值。 - vision_feature_select_strategy (
str,可选,默认为default) — 用于从视觉主干网络中选择视觉特征的特征选择策略。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - pixel_shuffle_ratio (
float,可选,默认为 0.5) — 用于对 patch token 进行下采样的 pixel-shuffle 比例。值越小,生成的 token 数量越少(下采样程度越高)。 - projector_input_dim (
int,可选,默认值为 4096) — 像素混洗之前视觉适配器 MLP 的宽度。较大的值会增加容量和计算量。 - projector_output_dim (
int,可选,默认为 4096) — 视觉适配器的输出宽度。值越大,生成的图像特征维度越高。 - multi_modal_projector_bias (
bool,可选,默认为False) — 是否在多模态投影器中使用偏置。 - projector_dropout (
float,可选,默认值为 0.0) — 视觉适配器 MLP 内部的 Dropout 比率。较高的值会增加更多的正则化。 - attention_dropout (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含rope_theta的值,并且如果希望使用 RoPE 处理更长的max_position_embeddings,则可选地包含用于缩放的参数。
这是用于存储 Llama4ForConditionalGeneration 配置的类。它根据指定的参数实例化 Llama4 模型,并定义模型架构。使用默认值实例化配置将得到与 meta-llama/Llama-4-Scout-17B-16E 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
Llama4Processor
类 transformers.Llama4Processor
< source >( image_processor = Nonetokenizer = Nonepatch_size: int = 14pixel_shuffle_ratio: float = 0.5fake_image_token = '<|image|>'image_token = '<|image|>'start_of_image_token = '<|image_start|>'end_of_image_token = '<|image_end|>'patch_token = '<|patch|>'tile_x_separator_token = '<|tile_x_separator|>'tile_y_separator_token = '<|tile_y_separator|>'chat_template = '{{- bos_token }}\n{%- if custom_tools is defined %}\n {%- set tools = custom_tools %}\n{%- endif %}\n{%- if not tools_in_user_message is defined %}\n {%- set tools_in_user_message = true %}\n{%- endif %}\n{%- if not date_string is defined %}\n {%- if strftime_now is defined %}\n {%- set date_string = strftime_now("%d %b %Y") %}\n {%- else %}\n {%- set date_string = "26 Jul 2024" %}\n {%- endif %}\n{%- endif %}\n{%- if not tools is defined %}\n {%- set tools = none %}\n{%- endif %}\n\n{#- This block extracts the system message, so we can slot it into the right place. #}\n{%- if messages[0][\'role\'] == \'system\' %} \n {%- if messages[0][\'content\'] is string %}\n {%- set system_message = messages[0][\'content\']|trim %}\n {%- else %}\n {#- FIXME: The processor requires an array, always. #}\n {%- set system_message = messages[0][\'content\'][0][\'text\']|trim %}\n {%- endif %}\n {%- set messages = messages[1:] %}\n {%- set user_supplied_system_message = true %}\n{%- else %}\n {%- set system_message = "" %}\n {%- set user_supplied_system_message = false %}\n{%- endif %}\n\n{#- System message if the user supplied one #}\n{%- if user_supplied_system_message %}\n {{- "<|header_start|>system<|header_end|>\n\n" }}\n {%- if tools is not none %}\n {{- "Environment: ipython\n" }}\n {%- endif %}\n {%- if tools is not none and not tools_in_user_message %}\n {{- "You have access to the following functions. To call a function, please respond with JSON for a function call." }}\n {{- \'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.\' }}\n {{- "Do not use variables.\n\n" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- "\n\n" }}\n {%- endfor %}\n {%- endif %}\n {{- system_message }}\n {{- "<|eot|>" }}\n{%- endif %}\n\n{#- Custom tools are passed in a user message with some extra guidance #}\n{%- if tools_in_user_message and not tools is none %}\n {#- Extract the first user message so we can plug it in here #}\n {%- if messages | length != 0 %}\n {%- set first_user_message = messages[0][\'content\']|trim %}\n {%- set messages = messages[1:] %}\n {%- else %}\n {{- raise_exception("Cannot put tools in the first user message when there\'s no first user message!") }}\n{%- endif %}\n {{- \'<|header_start|>user<|header_end|>\n\n\' -}}\n {{- "Given the following functions, please respond with a JSON for a function call " }}\n {{- "with its proper arguments that best answers the given prompt.\n\n" }}\n {{- \'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.\' }}\n {{- "Do not use variables.\n\n" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- "\n\n" }}\n {%- endfor %}\n {{- first_user_message + "<|eot|>"}}\n{%- endif %}\n\n{%- for message in messages %}\n {%- if not (message.role == \'ipython\' or message.role == \'tool\' or \'tool_calls\' in message) %}\n {{- \'<|header_start|>\' + message[\'role\'] + \'<|header_end|>\n\n\' }}\n {%- if message[\'content\'] is string %}\n {{- message[\'content\'] }}\n {%- else %}\n {%- for content in message[\'content\'] %}\n {%- if content[\'type\'] == \'image\' %}\n {{- \'<|image|>\' }}\n {%- elif content[\'type\'] == \'text\' %}\n {{- content[\'text\'] }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- "<|eot|>" }}\n {%- elif \'tool_calls\' in message and message.tool_calls|length > 0 %}\n {{- \'<|header_start|>assistant<|header_end|>\n\n\' -}}\n {{- \'<|python_start|>\' }}\n {%- if message[\'content\'] is string %}\n {{- message[\'content\'] }}\n {%- else %}\n {%- for content in message[\'content\'] %}\n {%- if content[\'type\'] == \'image\' %}\n {{- \'<|image|>\' }}\n {%- elif content[\'type\'] == \'text\' %}\n {{- content[\'text\'] }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- \'<|python_end|>\' }}\n {%- for tool_call in message.tool_calls %}\n {{- \'{"name": "\' + tool_call.function.name + \'", \' }}\n {{- \'"parameters": \' }}\n {{- tool_call.function.arguments | tojson }}\n {{- "}" }}\n {%- endfor %}\n {{- "<|eot|>" }}\n {%- elif message.role == "tool" or message.role == "ipython" %}\n {{- "<|header_start|>ipython<|header_end|>\n\n" }}\n {%- if message.content is mapping or message.content is iterable %}\n {{- message.content | tojson }}\n {%- else %}\n {{- message.content }}\n {%- endif %}\n {{- "<|eot|>" }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- \'<|header_start|>assistant<|header_end|>\n\n\' }}\n{%- endif %}\n'**kwargs )
参数
- image_processor (
Llama4ImageProcessor) — 图像处理器是必需的输入。 - tokenizer (
tokenizer_class) — 分词器是必需的输入。 - patch_size (
int, 可选,默认为 28) — 用于分词化的图像块大小。 - pixel_shuffle_ratio (
float,可选,默认为0.5) — 处理图像时用于像素混洗的比例。它控制应用于图像块的降采样因子。实际的降采样比例计算为1 / (pixel_shuffle_ratio^2)。 - fake_image_token (
str,可选,默认为"<|image|>") — 文本中用于占位的标记,将被替换为实际的图像 token。该 token 作为标记,指示在文本序列中何处应插入图像。 - image_token (
str, 可选,默认为"<|image|>") — 用于在文本中表示图像的 token。 - start_of_image_token (
str,可选,默认为"<|image_start|>") — 用于标记文本中图像序列起始位置的特殊标记。该标记会前置到图像标记序列之前,以界定图像的边界。 - end_of_image_token (
str,可选,默认为"<|image_end|>") — 用于标记文本中图像序列结束的特殊标记。该标记会附加在图像标记序列的末尾,以界定图像的边界。 - patch_token (
str,可选,默认为"<|patch|>") — 用于表示单个图像 patch 的 token。使用多个 patch token 来表示完整图像,其数量取决于图像大小和 patch 配置。 - tile_x_separator_token (
str, 可选,默认为"<|tile_x_separator|>") — 用于在图像内水平分隔 tile(patch)的 token。当图像被拆分为多个 tile 时,该 token 会插入到同一行中相邻 patch 之间。 - tile_y_separator_token (
str,可选,默认为"<|tile_y_separator|>") — 用于在图像中垂直分隔 tile(patch)的 token。当图像被拆分为多个 tile 时,该 token 会插入在 patch 行之间。 - chat_template (
str,默认值为 `{{- bos_token }} — - {%- if custom_tools is defined %} — {%- set tools = custom_tools %}
- {%- 结束
- {%- 如果未定义 tools_in_user_message %} — {%- 设置 tools_in_user_message = true %}
- {%- 结束
- {%- if not date_string is defined %} — {%- if strftime_now is defined %} {%- set date_string = strftime_now(“%d %b %Y”) %} {%- else %} {%- set date_string = “26 Jul 2024” %} {%- endif %}
- {%- 结束
- {%- if not tools is defined %} — {%- set tools = none %}
- {%- 结束
- {#- 此代码块用于提取系统消息,以便将其放置在正确的位置。 #} —
- {%- if messages[0]['role'] == ‘system’ %} — {%- if messages[0]['content'] is string %} {%- set system_message = messages[0]['content']|trim %} {%- else %} {#- FIXME: The processor requires an array, always. #} {%- set system_message = messages[0]['content'][0]['text']|trim %} {%- endif %} {%- set messages = messages[1:] %} {%- set user_supplied_system_message = true %}
- {%- else %} — {%- set system_message = "" %} {%- set user_supplied_system_message = false %}
- {%- 结束
- {#- 如果用户提供了系统消息 #} —
- {%- if user_supplied_system_message %} — {{- ”<|header_start|>system<|header_end|>
- ” }} — {%- if tools is not none %} {{- “Environment: ipython
- ” }} — {%- endif %} {%- if tools is not none and not tools_in_user_message %} {{- “你可以访问以下函数。若要调用函数,请以函数调用的 JSON 格式进行响应。” }} {{- ‘请以 {“name”: 函数名称, “parameters”: 参数名称及其值的字典} 的格式进行响应。’ }} {{- “不要使用变量。
- ” }} — {%- for t in tools %} {{- t | tojson(indent=4) }} {{- ”
- ” }} — {%- endfor %} {%- endif %} {{- system_message }} {{- ”<|eot|>” }}
- {%- 结束
- {#- 自定义工具通过用户消息传入,并附带一些额外的指导 #} —
- {%- if tools_in_user_message and not tools is none %} — {#- 提取第一条用户消息,以便在此处插入 #} {%- if messages | length != 0 %} {%- set first_user_message = messages[0]['content']|trim %} {%- set messages = messages[1:] %} {%- else %} {{- raise_exception(“当不存在第一条用户消息时,无法将工具放入第一条用户消息中!”) }}
- {%- endif %} — {{- ’<|header_start|>user<|header_end|>
- ’ -}} — {{- “给定以下函数,请以 JSON 格式回复一个函数调用 ” }} {{- “及其适当的参数,以最佳地回答给定的提示。
- ” }} — {{- ‘请以 {“name”: 函数名, “parameters”: 参数字典,包含参数名及其值} 的格式进行回复。’ }} {{- “不要使用变量。
- ” }} — {%- for t in tools %} {{- t | tojson(indent=4) }} {{- ”
- ” }} — {%- endfor %} {{- first_user_message + ”<|eot|>“}}
- {%- 结束
- {%- for message in messages %} — {%- if not (message.role == ‘ipython’ or message.role == ‘tool’ or ‘tool_calls’ in message) %} {{- ’<|header_start|>’ + message[‘role’] + ’<|header_end|>
- ’ }} — {%- if message[‘content’] is string %} {{- message[‘content’] }} {%- else %} {%- for content in message[‘content’] %} {%- if content[‘type’] == ‘image’ %} {{- ’<|image|>’ }} {%- elif content[‘type’] == ‘text’ %} {{- content[‘text’] }} {%- endif %} {%- endfor %} {%- endif %} {{- ”<|eot|>” }} {%- elif ‘tool_calls’ in message and message.tool_calls|length > 0 %} {{- ’<|header_start|>assistant<|header_end|>
- ’ -}} — {{- ’<|python_start|>’ }} {%- if message[‘content’] is string %} {{- message[‘content’] }} {%- else %} {%- for content in message[‘content’] %} {%- if content[‘type’] == ‘image’ %} {{- ’<|image|>’ }} {%- elif content[‘type’] == ‘text’ %} {{- content[‘text’] }} {%- endif %} {%- endfor %} {%- endif %} {{- ’<|python_end|>’ }} {%- for tool_call in message.tool_calls %} {{- ’{“name”: ”’ + tool_call.function.name + ’”, ’ }} {{- ‘“parameters”: ’ }} {{- tool_call.function.arguments | tojson }} {{- ”}” }} {%- endfor %} {{- ”<|eot|>” }} {%- elif message.role == “tool” or message.role == “ipython” %} {{- ”<|header_start|>ipython<|header_end|>
- ” }} — {%- if message.content is mapping or message.content is iterable %} {{- message.content | tojson }} {%- else %} {{- message.content }} {%- endif %} {{- ”<|eot|>” }} {%- endif %}
- {%- endfor %} —
- {%- if add_generation_prompt %} — {{- ’<|header_start|>assistant<|header_end|>
- ’ }} —
- {%- 结束
- `) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。
构建一个 Llama4Processor,它将图像处理器和分词器封装为单个处理器。
Llama4Processor 提供了 Llama4ImageProcessor 和 tokenizer_class 的所有功能。有关更多信息,请参阅 ~Llama4ImageProcessor 和 ~tokenizer_class。
__call__
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = Nonevideos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneaudio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> )
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 可选) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - text (
Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置is_split_into_words=True,以避免与批量输入产生歧义。 - videos (
Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]], 可选) — 要预处理的视频。期望输入单个视频或一批视频,其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间,请设置do_rescale=False。 - audio (
Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]], 可选) — 要准备处理的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。 如果为 NumPy 数组/PyTorch 张量,每个音频的形状应为 (C, T),其中 C 为通道数,T 为音频的采样长度。 - return_tensors (
str或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
- **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。
Llama4ImageProcessor
class transformers.Llama4ImageProcessor
< source >( **kwargs: *<class 'transformers.models.llama4.image_processing_llama4.Llama4ImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选,默认为True) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None],kwargs,默认为{'height' -- 336, 'width': 336}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - max_patches (
int, kwargs, 可选,默认为 16) — 从图像中提取的最大 patch 数量。 可通过preprocess方法中的max_patches参数进行覆盖。 - resize_to_max_canvas (
bool,kwargs,可选,默认为 False) — 是否将图像调整到最大画布尺寸。 如果为 True,则选择允许在不失真的情况下进行最大缩放的画布。 如果为 False,则尽可能少地缩小采样,包括完全不进行缩放,但绝不放大,除非图像小于 patch 尺寸。
构建一个 Llama4ImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.llama4.image_processing_llama4.Llama4ImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - max_patches (
int, kwargs, 可选,默认为 16) — 从图像中提取的最大 patch 数量。 可通过preprocess方法中的max_patches参数进行覆盖。 - resize_to_max_canvas (
bool,kwargs,可选,默认为 False) — 是否将图像调整到最大画布尺寸。 如果为 True,则选择允许在不失真的情况下进行最大缩放的画布。 如果为 False,则尽可能少地缩小采样,包括完全不进行缩放,但绝不放大,除非图像小于 patch 尺寸。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
Llama4ForConditionalGeneration
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonevision_feature_select_strategy: str | None = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Llama4CausalLMOutputWithPast or tuple(torch.Tensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 Llama4ImageProcessor 获取像素值。有关详细信息,请参阅 Llama4ImageProcessor.call()(Llama4Processor 使用 Llama4ImageProcessor 来处理图像)。 - attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- position_ids (
torch.LongTensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由past_key_values在解码的先前阶段返回,当use_cache=True或config.use_cache=True.仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入
past_key_values,则默认会初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用了
past_key_values,用户应仅输入未处理的input_ids(即未向该模型提供其过去键值状态的那些),其形状为(batch_size, unprocessed_length),而不是形状为(batch_size, sequence_length)的全部input_ids。 - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - vision_feature_select_strategy (
str, 可选) — 用于从视觉主干网络中选择视觉特征的特征选择策略。 可以是"default"或"full"之一。 - labels (
torch.LongTensor,形状为(batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在[0, ..., config.vocab_size]范围内,或为 -100(参见input_ids的文档字符串)。索引值设为-100的 token 将被忽略(即被掩码),损失仅针对标签位于[0, ..., config.vocab_size]范围内的 token 进行计算。 - use_cache (
bool,可选) — 如果设置为True,则会返回past_key_values键值状态,可用于加速解码(参见past_key_values)。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。 - logits_to_keep (
Union[int, torch.Tensor], 可选,默认为0) — 如果为int,则计算最后logits_to_keep个 token 的 logits。如果为0,则计算所有input_ids的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。 - mm_encoder_outputs (
dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions)pooler_output,形状为(batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。
返回值
Llama4CausalLMOutputWithPast 或 tuple(torch.Tensor)
Llama4CausalLMOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Llama4Config)和输入。
Llama4ForConditionalGeneration 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,当提供labels时返回) — 语言建模损失(用于下一个 token 预测)。logits(形状为
(batch_size, sequence_length, config.vocab_size)的torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。past_key_values(
Cache,可选,在传入use_cache=True或config.use_cache=True时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。hidden_states (
tuple[torch.Tensor],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple[torch.Tensor],可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
image_hidden_states (
torch.Tensor,可选) — 大小为 (batch_size, num_images, sequence_length, hidden_size) 的torch.Tensor`。 由视觉编码器生成并在投影最后一个隐藏状态后得到的模型的 image_hidden_states。router_logits (
tuple(torch.Tensor),可选,在传入output_router_logits=True时返回) — 一个torch.Tensor元组(每个 MoE 层对应一个),形状为(batch_size * sequence_length, num_experts)。
示例:
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, LlavaForConditionalGeneration
>>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
>>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> inputs = processor(images=image, text=prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(**inputs, max_new_tokens=15)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"USER: \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"get_image_features
< source >( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 Llama4ImageProcessor 获取像素值。有关详细信息,请参阅 Llama4ImageProcessor.call()(Llama4Processor 使用 Llama4ImageProcessor 来处理图像)。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Llama4Config)和输入。
从视觉塔获取图像的最终隐藏状态,并应用 al 投影。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output (
torch.Tensor,形状为(batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> from PIL import Image
>>> from transformers import AutoProcessor, Llama4ForConditionalGeneration
>>> model = Llama4ForConditionalGeneration.from_pretrained("meta-llama/Llama-4-Scout-17B-16E")
>>> processor = AutoProcessor.from_pretrained("meta-llama/Llama-4-Scout-17B-16E")
>>> messages = [
... {
... "role": "user", "content": [
... {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
... {"type": "text", "text": "Where is the cat standing?"},
... ]
... },
... ]
>>> inputs = processor.apply_chat_template(
... messages,
... tokenize=True,
... return_dict=True,
... return_tensors="pt",
... add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]Llama4ForCausalLM
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeCausalLMOutputWithPast or tuple(torch.Tensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- position_ids (
torch.LongTensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由past_key_values在解码的先前阶段返回,当use_cache=True或config.use_cache=True.仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入
past_key_values,则默认会初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用了
past_key_values,用户应仅输入未处理的input_ids(即未向该模型提供其过去键值状态的那些),其形状为(batch_size, unprocessed_length),而不是形状为(batch_size, sequence_length)的全部input_ids。 - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - labels (
torch.LongTensor,形状为(batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在[0, ..., config.vocab_size]范围内,或为 -100(参见input_ids的文档字符串)。索引值设为-100的 token 将被忽略(即被掩码),损失仅针对标签位于[0, ..., config.vocab_size]范围内的 token 进行计算。 - use_cache (
bool,可选) — 如果设置为True,则会返回past_key_values键值状态,可用于加速解码(参见past_key_values)。 - logits_to_keep (
Union[int, torch.Tensor], 可选,默认为0) — 如果为int,则计算最后logits_to_keep个 token 的 logits。如果为0,则计算所有input_ids的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。
返回值
MoeCausalLMOutputWithPast 或 tuple(torch.Tensor)
MoeCausalLMOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Llama4Config)和输入。
Llama4ForCausalLM 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,当提供labels时返回) — 语言建模损失(用于下一个 token 预测)。logits(形状为
(batch_size, sequence_length, config.vocab_size)的torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。aux_loss (
torch.Tensor,可选,当传入output_router_logits=True或config.output_router_logits=True,且模型使用负载均衡损失训练其路由器时返回) — 稀疏模块的负载均衡辅助损失。那些改用路由器偏差来平衡其专家(DeepSeek-V3 及由其衍生的架构)的模型,此处返回None,但仍会返回router_logits。router_logits (
tuple(torch.Tensor),可选,在传入output_router_logits=True或config.output_router_logits=True时返回) — 一个torch.Tensor元组(每个稀疏层对应一个),形状为(batch_size * sequence_length, num_experts)。由 MoE 路由器计算的原始路由器 logits。可用于计算负载均衡损失,或检查 token 如何被分发到各个专家。
past_key_values(
Cache,可选,在传入use_cache=True或config.use_cache=True时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> from transformers import AutoTokenizer, Llama4ForCausalLM
>>> model = Llama4ForCausalLM.from_pretrained("meta-llama4/Llama4-2-7b-hf")
>>> tokenizer = AutoTokenizer.from_pretrained("meta-llama4/Llama4-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."Llama4TextModel
类 transformers.Llama4TextModel
< source >( config: Llama4TextConfig )
参数
- config (Llama4TextConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未添加任何特定头部的裸 Llama4 Text Model,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeModelOutputWithPast or tuple(torch.Tensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- position_ids (
torch.LongTensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由past_key_values在解码的先前阶段返回,当use_cache=True或config.use_cache=True.仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入
past_key_values,则默认会初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用了
past_key_values,用户应仅输入未处理的input_ids(即未向该模型提供其过去键值状态的那些),其形状为(batch_size, unprocessed_length),而不是形状为(batch_size, sequence_length)的全部input_ids。 - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - use_cache (
bool,可选) — 如果设置为True,则会返回past_key_values键值状态,可用于加速解码(参见past_key_values)。
返回值
MoeModelOutputWithPast 或 tuple(torch.Tensor)
MoeModelOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Llama4Config)和输入。
Llama4TextModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。past_key_values(
Cache,可选,在传入use_cache=True或config.use_cache=True时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。包含预计算的隐藏状态(自注意力块中的键和值,以及如果
config.is_encoder_decoder=True则还包括交叉注意力块中的键和值),可用于(参见past_key_values输入)加速顺序解码。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
router_logits (
tuple(torch.Tensor),可选,当传入output_router_probs=True且config.add_router_probs=True,或当config.output_router_probs=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, sequence_length, num_experts)。由 MoE 路由器计算的原始路由器 logits(softmax 之后),这些术语用于计算混合专家模型的辅助损失。
Llama4VisionModel
forward
< source >( pixel_values: Tensorattention_mask: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs )
示例:
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, MllamaVisionModel
>>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
>>> model = MllamaVisionModel.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> inputs = processor(images=image, return_tensors="pt")
>>> output = model(**inputs)
>>> print(output.last_hidden_state.shape)
torch.Size([1, 1, 4, 1025, 7680])