# Llama4

    
        
        
    

[Llama 4](https://ai.meta.com/blog/llama-4-multimodal-intelligence/), 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 个专家。
-

这两个模型均采用早期融合技术以实现原生多模态能力，使其能够处理文本和图像输入。Maverick 和 Scout 均在涵盖 200 种语言的数据上进行了训练，训练数据量最高可达 40 万亿个 token（其中针对包括阿拉伯语、西班牙语、德语和印地语在内的 12 种语言提供了特定的微调支持）。

在部署方面，Llama 4 Scout 专为易用性而设计，可通过即时 4 位或 8 位 int4 量化，适配单张服务器级 GPU；而 Maverick 则提供 BF16 和 FP8 格式。这些模型基于自定义的 Llama 4 Community License Agreement 发布，该协议可在模型仓库中获取。

您可以在 [meta-llama](https://huggingface.co/meta-llama) 组织下找到所有原始的 Llama 检查点。

> [!TIP]
> Llama 4 系列模型有两种规格：109B 和 402B 参数。这两种规格都极其庞大，无法在普通设备上运行。请参阅下文，了解一些用于降低模型内存用量的示例。
>
> 为了让下载更快且更具容错性，我们建议按照以下方式安装 `hf_xet` 依赖项：`pip install transformers[hf_xet]`

以下示例演示了如何使用 [Pipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.Pipeline) 或 [AutoModel](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoModel) 进行生成。此外，我们还提供了一个示例，展示如何切换相关属性以启用超长上下文生成，因为某些 Llama 4 变体的上下文长度可达 1000 万 token。

```python

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"])
```

```python

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])
```

```python

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

```python

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 运行，且无需使用张量并行。

```python
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](../attention_interface)概述。

截至发布时，Llama 4 模型支持以下注意力机制：`eager`、`flex_attention`、`sdpa`。我们建议使用 `flex_attention` 以获得最佳效果。在模型初始化步骤中切换注意力机制：

设置 Flex Attention 可确保模型在处理超长上下文时获得最佳效果。

> [!TIP] 注意：以下示例同时使用了 `device_map="auto"` 和 flex-attention。请使用 `torchrun` 以张量并行模式运行此示例。
>
> 我们将致力于在未来实现使用 `device_map="auto"` 和 flex-attention 运行，且无需使用张量并行。

```python

from transformers import Llama4ForConditionalGeneration

model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    attn_implementation="flex_attention",
    device_map="auto",
)
```

`sdpa` 注意力方法通常比 `eager` 方法在计算效率上更高。

```python

from transformers import Llama4ForConditionalGeneration

model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    attn_implementation="sdpa",
    device_map="auto",
)
```

`eager` 注意力方法为默认设置，因此加载模型时无需进行任何更改：

```python

from transformers import Llama4ForConditionalGeneration

model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    device_map="auto",
)
```

### 量化

量化通过以较低精度表示权重来降低大模型的内存负担。有关可用的量化后端，请参阅[量化](../quantization/overview)概述。在发布时，FBGEMM 和 LLM-Compressor 均受支持；在发布后的几天内，还将支持更多的量化方法。

以下示例同时使用了两者：

以下是一个使用 FBGEMM 方法以 FP8 格式加载 BF16 模型的示例：

```python

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 检查点：

```python

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`：

```python

from transformers import Llama4ForConditionalGeneration

model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    device_map="auto",
)
```

## Llama4Config[[transformers.Llama4Config]]

#### transformers.Llama4Config[[transformers.Llama4Config]]

```python
transformers.Llama4Config(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, boi_token_index: int = 200080, eoi_token_index: int = 200081, image_token_index: int = 200092, tie_word_embeddings: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/configuration_llama4.py#L198)

**参数：**

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：视觉骨干网络的配置对象或字典。

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：文本骨干网络的配置对象或字典。

boi_token_index (`int`, *可选*，默认为 200080)：用于包裹图像提示的图像起始标记索引。

eoi_token_index (`int`, *可选*，默认为 200081)：用于包裹图像提示的图像结束标记索引。

image_token_index (`int`, *可选*, 默认为 `200092`) : 用作输入图像占位符的图像标记索引。

tie_word_embeddings (`bool`，*可选*，默认为 `False`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

这是用于存储 Llama4ForConditionalGeneration 配置的类。它根据指定的参数实例化 Llama4 模型，并定义模型架构。使用默认值实例化配置将生成与 [meta-llama/Llama-4-Scout-17B-16E](https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

```python
>>> 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.config
```

## Llama4TextConfig[[transformers.Llama4TextConfig]]

#### transformers.Llama4TextConfig[[transformers.Llama4TextConfig]]

```python
transformers.Llama4TextConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vocab_size: int = 202048, hidden_size: int = 5120, intermediate_size: int = 8192, intermediate_size_mlp: int = 16384, num_hidden_layers: int = 48, num_attention_heads: int = 40, num_key_value_heads: int = 8, head_dim: int = 128, hidden_act: str = 'silu', max_position_embeddings: int = 131072, initializer_range: float = 0.02, rms_norm_eps: float = 1e-05, use_cache: bool = True, pad_token_id: int | None = None, bos_token_id: int | None = 1, eos_token_id: int | list[int] | None = 2, tie_word_embeddings: bool = False, attention_dropout: float | int = 0.0, num_experts_per_tok: int = 1, num_local_experts: int = 16, moe_layers: list[int] | None = None, interleave_moe_layer_step: int = 1, use_qk_norm: bool = True, output_router_logits: bool = False, router_aux_loss_coef: float = 0.001, router_jitter_noise: float = 0.0, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, no_rope_layers: list[int] | None = None, no_rope_layer_interval: int = 4, attention_chunk_size: int | None = 8192, layer_types: list[str] | None = None, attn_temperature_tuning: bool = True, floor_scale: int = 8192, attn_scale: float = 0.1, attention_bias: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/configuration_llama4.py#L79)

**参数：**

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 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 [这篇论文](https://huggingface.co/papers/2305.13245)。如果未指定，则默认为 `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-choice 路由的 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`) : 在训练期间为路由器 logits 添加的噪声量，以实现更好的负载均衡。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *可选*) : 包含 RoPE 嵌入配置参数的字典。该字典应包含 `rope_theta` 的值，并且如果希望使用更长的 `max_position_embeddings` 配合 RoPE，则可选地包含用于缩放的参数。

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]`，*可选*)：一个列表，用于显式地将每个层索引与其层类型进行映射。如果未提供，将根据配置值自动生成。

attn_temperature_tuning (`bool`, *可选*, 默认为 `True`) : 是否根据序列长度动态缩放每个查询 token 的注意力温度。推荐用于长序列（例如 >32k tokens），以保持输出结果的稳定性。

floor_scale (`int`, *可选*，默认为 8192) : 注意力温度调节的基础缩放值（以 token 为单位）。值越大，缩放作用延迟到越远的位置。

attn_scale (`float`, *可选*，默认为 0.1)：注意力温度调节的强度。值越大，在长位置处的缩放比例越高。

attention_bias (`bool`，*可选*，默认为 `False`)：在自注意力机制中，是否在查询、键、值和输出投影层中使用偏置。

这是用于存储 Llama4ForConditionalGeneration 配置的类。它根据指定的参数实例化 Llama4 模型，并定义模型架构。使用默认值实例化配置将生成与 [meta-llama/Llama-4-Scout-17B-16E](https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

## Llama4VisionConfig[[transformers.Llama4VisionConfig]]

#### transformers.Llama4VisionConfig[[transformers.Llama4VisionConfig]]

```python
transformers.Llama4VisionConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 768, hidden_act: str = 'gelu', num_hidden_layers: int = 34, num_attention_heads: int = 16, num_channels: int = 3, intermediate_size: int = 5632, vision_output_dim: int = 7680, image_size: int | list[int] | tuple[int, int] = 448, patch_size: int | list[int] | tuple[int, int] = 14, norm_eps: float = 1e-05, vision_feature_select_strategy: str = 'default', initializer_range: float = 0.02, pixel_shuffle_ratio: float = 0.5, projector_input_dim: int = 4096, projector_output_dim: int = 4096, multi_modal_projector_bias: bool = False, projector_dropout: float | int = 0.0, attention_dropout: float | int = 0.0, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/configuration_llama4.py#L29)

**参数：**

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 进行下采样的像素混洗比例。值越小，生成的 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` 的值，并且如果希望使用更长的 `max_position_embeddings` 配合 RoPE，则可选地包含用于缩放的参数。

这是用于存储 Llama4ForConditionalGeneration 配置的类。它根据指定的参数实例化 Llama4 模型，并定义模型架构。使用默认值实例化配置将生成与 [meta-llama/Llama-4-Scout-17B-16E](https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

## Llama4Processor[[transformers.Llama4Processor]]

#### transformers.Llama4Processor[[transformers.Llama4Processor]]

```python
transformers.Llama4Processor(image_processor = None, tokenizer = None, patch_size: int = 14, pixel_shuffle_ratio: float = 0.5, fake_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)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/processing_llama4.py#L27)

**参数：**

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。该 token 作为标记，指示应在文本序列的何处插入图像。

image_token (`str`，*可选*，默认为 `"<|image|>"`)：用于在文本中表示图像的标记。

start_of_image_token (`str`，*可选*，默认为 `"<|image_start|>"`)：用于标记文本中图像序列起始位置的特殊标记。该标记会前置到图像标记序列之前，以界定图像边界。

end_of_image_token (`str`，*可选*，默认为 `"<|image_end|>"`)：用于标记文本中图像序列结束的特殊标记。该标记会附加在图像标记序列之后，以界定图像边界。

patch_token (`str`, *可选*, 默认为 `"<|patch|>"`) : 用于表示单个图像块的标记。使用多个块标记来表示完整图像，具体数量取决于图像大小和块配置。

tile_x_separator_token (`str`, *可选*, 默认为 `"<|tile_x_separator|>"`) : 用于在图像内水平分隔图块（patches）的标记。当图像被拆分为多个图块时，该标记会插入在同一行的图块之间。

tile_y_separator_token (`str`, *可选*, 默认为 `"<|tile_y_separator|>"`) : 用于在图像内垂直分隔图块（patches）的标记。当图像被拆分为多个图块时，该标记会插入在图块行之间。

chat_template (`str`，默认为 `{{- bos_token }} --

{%- if custom_tools is defined %} : {%- set tools = custom_tools %}

{%- endif %} --

{%- if not tools_in_user_message is defined %} : {%- set tools_in_user_message = true %}

{%- endif %} --

{%- 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 %}

{%- endif %} --

{%- if not tools is defined %} : {%- set tools = none %}

{%- endif %} :

{#- 此块用于提取系统消息，以便将其插入到正确的位置。 #} --

{%- if messages[0]['role'] == 'system' %} : {%- if messages[0]['content'] is string %} {%- set system_message = messages[0]['content']|trim %} {%- else %} {#- FIXME: 处理器始终需要一个数组。 #} {%- 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 %}

{%- endif %} :

{#- 如果用户提供了系统消息 #} --

{%- if user_supplied_system_message %} : {{- "<|header_start|>system<|header_end|>

" }} : {%- if tools is not none %} {{- "环境：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|>" }}

{%- endif %} :

{#- 自定义工具通过用户消息传入，并附带一些额外的指导 #} --

{%- 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|>"}}

{%- endif %} :

{%- 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|>

' }} --

{%- endif %} --

`) : 一个 Jinja 模板，用于将聊天中的消息列表转换为可分词的字符串。

构建一个 Llama4Processor，它将图像处理器和分词器封装为单个处理器。

[Llama4Processor](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4Processor) 提供了 [Llama4ImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4ImageProcessor) 和 `tokenizer_class` 的所有功能。有关更多信息，请参阅 [~Llama4ImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4ImageProcessor) 和 `~tokenizer_class`。

#### __调用__[[transformers.Llama4Processor.__call__]]

```python
__call__(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, text: str | list[str] | list[list[str]] | None = None, videos: 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] = None, audio: 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'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/processing_utils.py#L670)

**参数：**

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_mm_token_type_ids (`bool`, *kwargs*) : 是否返回多模态 token 类型 ID，以指示多模态占位符 token 的位置。

return_text_replacement_offsets (`bool`, *kwargs*) : 是否返回每个多模态占位符及其替换项的字符偏移量。

return_tensors (`str` 或 [TensorType](/docs/transformers/v5.23.0/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessingKwargs), *可选*) : 针对每种模态（文本、图像、视频、音频）的额外处理选项。模型特定参数已在上方列出；有关支持参数的完整列表，请参阅 TypedDict 类。

## Llama4ImageProcessor[[transformers.Llama4ImageProcessor]]

#### transformers.Llama4ImageProcessor[[transformers.Llama4ImageProcessor]]

```python
transformers.Llama4ImageProcessor(**kwargs: *<class 'transformers.models.llama4.image_processing_llama4.Llama4ImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/image_processing_llama4.py#L296)

**参数：**

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 为整数时，是否在调整大小时默认使用正方形图像。

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*, *optional*, 默认为 False) : 是否将图像调整到最大画布尺寸。如果为 True，则选择允许在不失真的情况下进行最大缩放的画布。如果为 False，则尽可能少地降采样，包括完全不调整大小，但绝不进行上采样，除非图像小于 patch 尺寸。

构建一个 Llama4ImageProcessor 图像处理器。

#### preprocess[[transformers.Llama4ImageProcessor.preprocess]]

```python
preprocess(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'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/image_processing_llama4.py#L312)

**参数：**

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 为 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*) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `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*, *optional*, 默认为 False) : 是否将图像调整到最大画布尺寸。如果为 True，则选择允许在不失真的情况下进行最大缩放的画布。如果为 False，则尽可能少地降采样，包括完全不调整大小，但绝不进行上采样，除非图像小于 patch 尺寸。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

## Llama4ForConditionalGeneration[[transformers.Llama4ForConditionalGeneration]]

#### transformers.Llama4ForConditionalGeneration[[transformers.Llama4ForConditionalGeneration]]

```python
transformers.Llama4ForConditionalGeneration(config: Llama4Config)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/modeling_llama4.py#L1149)

#### forward[[transformers.Llama4ForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, vision_feature_select_strategy: str | None = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/modeling_llama4.py#L1213)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [Llama4ImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4ImageProcessor) 获取像素值。有关详细信息，请参阅 [Llama4ImageProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[Llama4Processor](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4Processor) 使用 [Llama4ImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4ImageProcessor) 处理图像）。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `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](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.utils.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](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4Config)）和输入。

[Llama4ForConditionalGeneration](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.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](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/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)`。

示例：

```python
>>> 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[[transformers.Llama4ForConditionalGeneration.get_image_features]]

```python
get_image_features(pixel_values: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/modeling_llama4.py#L1181)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 [Llama4ImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4ImageProcessor) 获取像素值。有关详细信息，请参阅 [Llama4ImageProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[Llama4Processor](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4Processor) 使用 [Llama4ImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4ImageProcessor) 处理图像）。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Llama4Config](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4Config)）和输入。

从视觉塔获取图像的最终隐藏状态，并应用 al 投影。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 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 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> 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[[transformers.Llama4ForCausalLM]]

#### transformers.Llama4ForCausalLM[[transformers.Llama4ForCausalLM]]

```python
transformers.Llama4ForCausalLM(config: Llama4TextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/modeling_llama4.py#L568)

#### forward[[transformers.Llama4ForCausalLM.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/modeling_llama4.py#L585)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*) : 用于计算因果语言建模损失的标签。索引应在 `[-100, 0, ..., config.vocab_size]` 范围内（参见 `input_ids` 的文档字符串）。索引设置为 `-100` 的 token 将被忽略（被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。 标签会在**内部进行移位**，因此使用 `labels[..., 1:]` 来预测 `logits[..., :-1, :]`。请传入与 `input_ids` 匹配的未移位标签（即 `labels = input_ids`）。在传入之前，请**不要**自行对标签进行移位。 如果标签已经移位（例如在使用序列并行时），请将其作为 `shift_labels` 关键字参数传入，系统将按原样使用它们。 为了计算损失，仍然必须传入 `labels`。

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](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4Config)）和输入。

[Llama4ForCausalLM](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.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](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/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 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> 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]]

#### transformers.Llama4TextModel[[transformers.Llama4TextModel]]

```python
transformers.Llama4TextModel(config: Llama4TextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/modeling_llama4.py#L475)

**参数：**

config ([Llama4TextConfig](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4TextConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

未添加任何特定头部的裸 Llama4 Text Model，直接输出原始隐藏状态。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.Llama4TextModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/modeling_llama4.py#L502)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `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](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.Llama4Config)）和输入。

[Llama4TextModel](/docs/transformers/v5.23.0/zh/model_doc/llama4#transformers.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](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/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[[transformers.Llama4VisionModel]]

#### transformers.Llama4VisionModel[[transformers.Llama4VisionModel]]

```python
transformers.Llama4VisionModel(config: Llama4VisionConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/modeling_llama4.py#L1011)

#### forward[[transformers.Llama4VisionModel.forward]]

```python
forward(pixel_values: Tensor, attention_mask: typing.Optional[torch.Tensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/llama4/modeling_llama4.py#L1048)

示例：

```python
>>> 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])
```

