# Gemma4

## 概述

Gemma 4 是一个多模态模型，提供预训练和指令微调版本，参数规模包括 E2B、E4B、31B 和 26B-A4B（MoE）。Gemma 4 模型提供以下功能：
- 推理：该系列中的所有模型均被设计为具备强大推理能力的模型，并支持可配置的思考模式。
- 扩展多模态：支持处理文本、具有可变宽高比和分辨率的图像（所有模型均支持）、视频以及音频（E2B 和 E4B 模型原生支持）。
- 上下文窗口扩展：小型模型的上下文窗口为 128K，而其他模型支持 256K。
- 增强的编码与智能体能力：在编码基准测试中取得了显著的提升，同时内置了函数调用支持，从而驱动了能力强大的自主智能体。
- 原生系统提示词支持：Gemma 4 引入了对 system 角色的内置支持，从而实现更结构化、更可控的对话。

您可以在 [Gemma 4](https://huggingface.co/collections/google/gemma-4) 发布中找到所有原始的 Gemma 4 检查点。

### Gemma4 视觉模型

与之前发布的 Gemma 视觉模型相比，关键区别在于新设计：使用**固定数量的 token 预算**来处理**不同尺寸的图像**。与许多将每张图像压缩为固定正方形（例如 224×224）的模型不同，Gemma 4 在调整图像至合适尺寸的同时，保留了图像的自然宽高比。需要遵循以下几项约束：
- 总像素数必须控制在补丁预算范围内
- 高度和宽度都必须能被 **48**（= 补丁大小 16 × 池化核 3）整除

> [!IMPORTANT]
> Gemma 4 **不会**应用许多其他视觉模型所使用的标准 ImageNet 均值/标准差归一化。该模型自身的 patch embedding 层会在内部处理最终的缩放（将数值转换到 [-1, 1] 范围内）。

图像处理器可生成的“软标记”（又称视觉标记）数量是可配置的。支持的选项如下所示，默认值为每张图像 **280 个软标记**。

| 软标记 | 补丁（池化前） | 近似图像面积 |
|:-----------:|:------------------------:|:-------------------:|
| 70          | 630                      | ~161K 像素        |
| 140         | 1,260                    | ~323K 像素        |
| **280**     | **2,520**                | **约 645K 像素**    |
| 560         | 5,040                    | 约 130 万像素        |
| 1,120       | 10,080                   | 约 260 万像素        |

为了对图像中每个 patch 编码位置信息，Gemma 4 使用了一个可学习的 2D 位置嵌入表。该位置表在每个轴上最多存储 10,240 个位置，使模型能够处理非常大的图像。每个位置都是一个与 patch 嵌入维度相同的可学习向量。Gemma 4 使用的 2D RoPE 独立地旋转注意力头维度的一半用于 x 轴，另一半用于 y 轴。这使得模型能够理解诸如“上方”、“下方”、“左侧”和“右侧”等空间关系。

### 逐层嵌入（PLE）

Gemma 4 引入了逐层嵌入（Per-Layer Embeddings，PLE）系统，该系统向每个解码器层输入一个辅助残差信号，而不仅仅依赖输入端的单一共享嵌入。

PLE 将两个组件相加，并在输入每个解码器层之前乘以 `1/√2` 进行缩放：

1. Token-identity（`get_per_layer_inputs`）：在 `embed_tokens_per_layer` 中查找 `input_ids`，该层是一个 `Gemma4TextScaledWordEmbedding`，会将结果乘以 `√(hidden_size_per_layer_input)`。打包后的输出会从 `[batch, seq, num_hidden_layers * hidden_size_per_layer_input]` 重塑为 `[batch, seq, num_hidden_layers, hidden_size_per_layer_input]`。
2. 上下文感知（`project_per_layer_inputs`）：将 `inputs_embeds` 通过 `per_layer_model_projection`（一个 Linear 层）进行投影，乘以 `1/√(hidden_size)` 进行缩放，重塑为 `[batch, seq, num_layers, ple_dim]`，并使用 `per_layer_projection_norm`（RMSNorm）进行归一化。

当两个组件均可用时，每层的最终输入为 `(token_identity + context_aware) * (1/√2)`。对于没有 `input_ids` 的多模态输入，仅使用上下文感知投影。

## 使用示例

以下示例演示了如何使用 [Pipeline](/docs/transformers/main/zh/main_classes/pipelines#transformers.Pipeline) 或 [AutoModel](/docs/transformers/main/zh/model_doc/auto#transformers.AutoModel) 类基于图像生成文本。

```python
from transformers import pipeline

pipeline = pipeline(
    task="image-text-to-text",
    model="google/gemma-4-E2B-it",
)
pipeline(
    images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
    text="<|image|>\n\nWhat is shown in this image?"
)
```

```python
from transformers import AutoModelForImageTextToText, AutoProcessor

model = AutoModelForImageTextToText.from_pretrained(
    "google/gemma-4-E2B-it",
    device_map="auto",
    attn_implementation="sdpa"
)
processor = AutoProcessor.from_pretrained(
    "google/gemma-4-E2B-it",
    padding_side="left"
)

messages = [
    {
        "role": "user", "content": [
            {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
            {"type": "text", "text": "What is shown in this image?"},
        ]
    },
]
inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
).to(model.device)
input_len = inputs["input_ids"].shape[-1]

output = model.generate(**inputs, max_new_tokens=50, cache_implementation="static")
print(processor.decode(output[0][input_len:], skip_special_tokens=True))
```

### 函数调用

```python
from transformers import AutoModelForCausalLM, AutoProcessor

WEATHER_TOOL = {
    "type": "function",
    "function": {
        "name": "get_n_day_weather_forecast",
        "description": "Get an N-day weather forecast",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA",
                },
                "format": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "The temperature unit to use",
                },
                "num_days": {
                    "type": "integer",
                    "description": "The number of days to forecast",
                },
            },
            "required": ["location", "format", "num_days"],
        },
    },
}

messages = [
    {
        "role": "user",
        "content": "What's the weather like the next 3 days in San Francisco, CA (using F)?",
    },
]

model = AutoModelForCausalLM.from_pretrained(
    "google/gemma-4-E2B-it",
    device_map="auto",
    attn_implementation="sdpa"
)
processor = AutoProcessor.from_pretrained(
    "google/gemma-4-E2B-it",
    padding_side="left"
)

text = processor.apply_chat_template(
    messages,
    tools=[WEATHER_TOOL],
    tokenize=False,
    add_generation_prompt=True,
)

inputs = processor(text=text, return_tensors="pt").to(model.device)
input_len = inputs["input_ids"].shape[-1]

outputs = model.generate(**inputs, max_new_tokens=200)
print(processor.decode(outputs[0][input_len:], skip_special_tokens=False))
```

### Audio （仅限 E2B 和 E4B）

```python
from transformers import AutoModelForMultimodalLM, AutoProcessor

messages = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "Please transcribe the following audio:"},
            {
                "type": "audio",
                "url": "https://huggingface.co/datasets/eustlb/audio-samples/resolve/main/dude_where_is_my_car.wav",
            },
        ],
    }
]

model = AutoModelForMultimodalLM.from_pretrained(
    "google/gemma-4-E2B-it",
    device_map="auto",
    attn_implementation="sdpa"
)
processor = AutoProcessor.from_pretrained(
    "google/gemma-4-E2B-it",
    padding_side="left"
)

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt"
).to(model.device, dtype=model.dtype)

input_len = inputs["input_ids"].shape[-1]

outputs = model.generate(**inputs, max_new_tokens=200)
print(processor.decode(outputs[0][input_len:], skip_special_tokens=False))
```

## Gemma4AudioConfig[[transformers.Gemma4AudioConfig]]

#### transformers.Gemma4AudioConfig[[transformers.Gemma4AudioConfig]]

```python
transformers.Gemma4AudioConfig(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 = 1024, num_hidden_layers: int = 12, num_attention_heads: int = 8, hidden_act: str = 'silu', subsampling_conv_channels: list[int] | tuple[int, int] = (128, 32), conv_kernel_size: int = 5, residual_weight: float = 0.5, attention_chunk_size: int = 12, attention_context_left: int = 13, attention_context_right: int = 0, attention_logit_cap: float = 50.0, attention_invalid_logits_value: float = -1000000000.0, use_clipped_linears: bool = True, rms_norm_eps: float = 1e-06, gradient_clipping: float = 10000000000.0, output_proj_dims: int = 1536, initializer_range: float = 0.02)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/configuration_gemma4.py#L29)

**参数：**

hidden_size (`int`，*可选*，默认为 `1024`)：隐藏表示的维度。

num_hidden_layers (`int`，*可选*，默认为 `12`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `8`)：Transformer 解码器中每个注意力层的注意力头数量。

hidden_act (`str`，*可选*，默认为 `silu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

subsampling_conv_channels (`list[int]`，默认为 `[128, 32]`)：Sub-sample Convolution Projection 中卷积层的通道大小。

conv_kernel_size (`int`, *可选*, 默认为 `5`) : 卷积核的大小。

residual_weight (`float`，默认为 `0.5`)：在前馈网络中，与残差相加之前应用于 hidden_states 的缩放。

attention_chunk_size (`int`，默认为 `12`)：用于注意力处理的子序列大小。

attention_context_left (`int`，默认为 `13`)：注意力块的左侧上下文大小。

attention_context_right (`int`，默认为 `0`)：注意力块的右侧上下文大小。

attention_logit_cap (`float`，默认为 `50.0`)：应用于注意力权重的上限。

attention_invalid_logits_value (`float`，默认为 `1e-9`)：用于注意力机制中无效 logits 的值。

use_clipped_linears (`bool`，默认为 `True`)：如果为 true，则对 Linear 层应用裁剪，并从模型检查点中获取边界值。

rms_norm_eps (`float`，*可选*，默认为 `1e-06`)：rms 归一化层使用的 epsilon。

gradient_clipping (`float`，默认为 `1e10`)：用于稳定极大梯度值的裁剪值。

output_proj_dims (`int`，默认为 `1536`)：从 `hidden_size` 到模型输出的最终线性投影的维度。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

这是用于存储 Gemma4Model 配置的类。它根据指定的参数实例化 Gemma4 模型，并定义模型架构。使用默认值实例化配置将生成与 [google/gemma-4-e2b-it](https://huggingface.co/google/gemma-4-e2b-it) 类似的配置。

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

## Gemma4VisionConfig[[transformers.Gemma4VisionConfig]]

#### transformers.Gemma4VisionConfig[[transformers.Gemma4VisionConfig]]

```python
transformers.Gemma4VisionConfig(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, intermediate_size: int = 3072, num_hidden_layers: int = 16, num_attention_heads: int = 12, num_key_value_heads: int = 12, head_dim: int = 64, hidden_activation: str = 'gelu_pytorch_tanh', rms_norm_eps: float = 1e-06, max_position_embeddings: int = 131072, attention_bias: bool | None = False, attention_dropout: float | None = 0.0, rope_parameters: dict | None = None, pooling_kernel_size: int = 3, patch_size: int = 16, position_embedding_size: int = 10240, use_clipped_linears: bool = False, standardize: bool = False, initializer_range: float = 0.02)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/configuration_gemma4.py#L269)

**参数：**

hidden_size (`int`，*可选*，默认为 `768`)：隐藏表示的维度。

intermediate_size (`int`，*可选*，默认值为 `3072`)：MLP 表示的维度。

num_hidden_layers (`int`，*可选*，默认为 `16`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `12`)：Transformer 解码器中每个注意力层的注意力头数量。

num_key_value_heads (`int`, *可选*，默认为 `12`) : 这是用于实现 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`, *可选*, 默认为 `64`) : 注意力头维度。如果为 None，则默认为 hidden_size // num_attention_heads

hidden_activation (`str`，*可选*，默认为 `gelu_pytorch_tanh`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

rms_norm_eps (`float`，*可选*，默认为 `1e-06`)：rms 归一化层使用的 epsilon。

max_position_embeddings (`int`，*可选*，默认值为 `131072`)：该模型可能使用的最大序列长度。

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

attention_dropout (`float`, *可选*, 默认为 `0.0`) : 注意力概率的 dropout 比率。

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

pooling_kernel_size (`int`, *可选*) : 在分块（patchification）之后应用的空间池化核大小。

patch_size (`int`，*可选*，默认为 `16`)：每个 patch 的大小（分辨率）。

position_embedding_size (`int`，默认为 10240)：视觉编码器的最大位置嵌入数量。控制补丁嵌入器所使用的已学习二维位置嵌入表的大小。

use_clipped_linears (`bool`，默认为 `False`) : 是否使用权重裁剪线性层。启用后，前向传播期间线性层的权重将被限制在固定范围内，以提升数值稳定性。

standardize (`bool`，默认为 `False`)：如果为 true，则对池化器返回的软标记应用偏置和缩放。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

这是用于存储 Gemma4Model 配置的类。它根据指定的参数实例化 Gemma4 模型，并定义模型架构。使用默认值实例化配置将生成与 [google/gemma-4-e2b-it](https://huggingface.co/google/gemma-4-e2b-it) 类似的配置。

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

## Gemma4TextConfig[[transformers.Gemma4TextConfig]]

#### transformers.Gemma4TextConfig[[transformers.Gemma4TextConfig]]

```python
transformers.Gemma4TextConfig(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 = 262144, hidden_size: int = 2304, intermediate_size: int = 9216, num_hidden_layers: int = 30, num_attention_heads: int = 8, num_key_value_heads: int = 4, head_dim: int = 256, hidden_activation: str = 'gelu_pytorch_tanh', max_position_embeddings: int = 131072, initializer_range: float = 0.02, rms_norm_eps: float = 1e-06, use_cache: bool = True, pad_token_id: int | None = 0, eos_token_id: int | list[int] | None = 1, bos_token_id: int | None = 2, tie_word_embeddings: bool = True, rope_parameters: dict | None = None, attention_bias: bool = False, attention_dropout: int | float | None = 0.0, sliding_window: int = 512, layer_types: list[str] | None = None, final_logit_softcapping: float | None = None, use_bidirectional_attention: typing.Optional[typing.Literal['all', 'vision']] = None, vocab_size_per_layer_input: int = 262144, hidden_size_per_layer_input: int = 256, attention_k_eq_v: bool = False, num_kv_shared_layers: int = 0, enable_moe_block: bool = False, use_double_wide_mlp: bool = False, num_experts: int | None = None, top_k_experts: int | None = None, moe_intermediate_size: int | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/configuration_gemma4.py#L87)

**参数：**

vocab_size (`int`，*可选*，默认值为 `262144`)：模型的词汇表大小。定义了 `input_ids` 可以表示的不同 token 的数量。

hidden_size (`int`，*可选*，默认为 `2304`)：隐藏表示的维度。

intermediate_size (`int`，*可选*，默认为 `9216`)：MLP 表示的维度。

num_hidden_layers (`int`，*可选*，默认为 `30`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `8`)：Transformer 解码器中每个注意力层的注意力头数量。

num_key_value_heads (`int`, *可选*，默认为 `4`) : 这是用于实现 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`, *可选*, 默认为 `256`) : 注意力头维度。如果为 None，则默认为 hidden_size // num_attention_heads

hidden_activation (`str`，*可选*，默认为 `gelu_pytorch_tanh`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

max_position_embeddings (`int`，*可选*，默认值为 `131072`)：该模型可能使用的最大序列长度。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

rms_norm_eps (`float`，*可选*，默认为 `1e-06`)：rms 归一化层使用的 epsilon。

use_cache (`bool`，*可选*，默认为 `True`)：模型是否应返回最后的键/值注意力（并非所有模型都使用）。仅当 `config.is_decoder=True` 或模型为仅解码器生成模型时相关。

pad_token_id (`int`，*可选*，默认为 `0`)：词表中用于填充的 Token ID。

eos_token_id (`Union[int, list[int]]`，*可选*，默认为 `1`)：词汇表中用于表示流结束（end-of-stream）的 Token ID。

bos_token_id (`int`，*可选*，默认为 `2`)：词汇表中用于表示流起始的 Token id。

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

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

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

attention_dropout (`Union[int, float]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

sliding_window (`int`, *可选*，默认为 `512`)：滑动窗口注意力机制的窗口大小。如果为 `None`，则不应用滑动窗口。

layer_types (`list[str]`，*可选*)：一个列表，用于显式地将每个层索引与其层类型进行映射。如果未提供，将根据配置值自动生成。

final_logit_softcapping (`float`, *可选*) : 在计算概率分布之前应用于最终 logits 的软上限值。Logits 会通过 `tanh(logit / cap) * cap` 进行缩放。

use_bidirectional_attention (`str`, *可选*) : 控制双向注意力行为。当设置为 `"vision"` 时，视觉标记使用双向注意力，而文本标记使用因果注意力。当设置为 `"all"` 时，所有标记均使用双向注意力。

vocab_size_per_layer_input (`int`，默认为 262144) : 逐层输入嵌入（PLE）的词汇表大小。用于具有逐层残差流的模型，其中在每个解码器层添加一个较小的嵌入。

hidden_size_per_layer_input (`int`，默认为 256) : PLE 系统中每层的隐藏维度。由于所有层都打包到单个表中，实际的嵌入权重形状为 `[vocab_size_per_layer_input, num_hidden_layers * hidden_size_per_layer_input]`。有关完整 PLE 流水线的说明，请参阅 [Gemma4](https://huggingface.co/docs/transformers/main/en/model_doc/gemma4#per-layer-embeddings-ple) 文档。

attention_k_eq_v (`bool`，默认为 `False`)：键和值是否共享相同的投影权重。当为 `True` 时，键投影的输出将被复用为值投影。

num_kv_shared_layers (`int`，默认为 0)：共享相同键值投影的连续解码器层数。值为 0 表示不共享（每层拥有独立的 KV 投影）。

enable_moe_block (`bool`，默认为 `False`) : 是否在解码器层中启用混合专家（Mixture-of-Experts，MoE）模块。当 `True` 时，符合条件的层将使用稀疏 MoE 前馈网络。

use_double_wide_mlp (`bool`，默认为 `False`) : 是否使用具有融合门控和上投影的双宽度 MLP。

num_experts (`int`, *可选*) : MoE 层中路由专家的数量。

top_k_experts (`int`, *可选*) : MoE 层中每个 token 激活的专家数量。仅在 `enable_moe_block=True` 时使用。

moe_intermediate_size (`int`, *可选*) : MoE 层中每个专家的前馈网络的中间（隐藏）维度。仅在 `enable_moe_block=True` 时使用。

这是用于存储 Gemma4Model 配置的类。它根据指定的参数实例化 Gemma4 模型，并定义模型架构。使用默认值实例化配置将生成与 [google/gemma-4-e2b-it](https://huggingface.co/google/gemma-4-e2b-it) 类似的配置。

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

## Gemma4Config[[transformers.Gemma4Config]]

#### transformers.Gemma4Config[[transformers.Gemma4Config]]

```python
transformers.Gemma4Config(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, text_config: transformers.models.gemma4.configuration_gemma4.Gemma4TextConfig | dict[str, typing.Any] | None = None, vision_config: transformers.models.gemma4.configuration_gemma4.Gemma4VisionConfig | dict[str, typing.Any] | None = None, audio_config: transformers.models.gemma4.configuration_gemma4.Gemma4AudioConfig | dict[str, typing.Any] | None = None, boi_token_id: int | None = 255999, eoi_token_id: int | None = 258882, image_token_id: int | None = 258880, video_token_id: int | None = 258884, boa_token_id: int | None = 256000, eoa_token_index: int | None = 258883, audio_token_id: int | None = 258881, initializer_range: float | None = 0.02, tie_word_embeddings: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/configuration_gemma4.py#L321)

**参数：**

text_config (`Union[~models.gemma4.configuration_gemma4.Gemma4TextConfig, dict[str, Any]]`, *可选*) : 文本骨干网络的配置对象或字典。

vision_config (`Union[~models.gemma4.configuration_gemma4.Gemma4VisionConfig, dict[str, Any]]`, *可选*) : 视觉骨干网络的配置对象或字典。

audio_config (`Union[~models.gemma4.configuration_gemma4.Gemma4AudioConfig, dict[str, Any]]`, *可选*) : 音频骨干网络的配置对象或字典。

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

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

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

video_token_id (`int`，*可选*，默认为 `258884`)：用作输入视频占位符的视频 token 索引。

boa_token_id (`int`, *可选*，默认为 256000)：用于包裹音频提示的音频起始标记索引。

eoa_token_index (`int`, *可选*，默认为 258883)：用于包裹音频提示的音频结束标记索引。

audio_token_id (`int`，*可选*，默认为 `258881`)：用作输入音频占位符的音频 token 索引。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

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

这是用于存储 Gemma4Model 配置的类。它根据指定的参数实例化 Gemma4 模型，并定义模型架构。使用默认值实例化配置将生成与 [google/gemma-4-e2b-it](https://huggingface.co/google/gemma-4-e2b-it) 类似的配置。

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

示例：

```python
>>> from transformers import (
>>>     Gemma4AudioConfig,
>>>     Gemma4Config,
>>>     Gemma4ForConditionalGeneration,
>>>     Gemma4TextConfig,
>>>     Gemma4VisionConfig,
>>> )

>>> # Initializing a Gemma 4 Audio config.
>>> audio_config = Gemma4AudioConfig()

>>> # Initializing a Gemma 4 Text config.
>>> text_config = Gemma4TextConfig()

>>> # Initializing a Gemma 4 vision config.
>>> vision_config = Gemma4VisionConfig()

>>> # Initializing a Gemma 4 config similar to google/gemma-4-e2b-it
>>> configuration = Gemma4Config(text_config, vision_config, audio_config)

>>> # Initializing a model from the google/gemma-4-e2b-it configuration
>>> model = Gemma4ForConditionalGeneration(configuration)

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

## Gemma4AudioFeatureExtractor[[transformers.Gemma4AudioFeatureExtractor]]

#### transformers.Gemma4AudioFeatureExtractor[[transformers.Gemma4AudioFeatureExtractor]]

```python
transformers.Gemma4AudioFeatureExtractor(feature_size: int = 128, sampling_rate: int = 16000, padding_value: float = 0.0, return_attention_mask: bool = True, frame_length_ms: float = 20.0, hop_length_ms: float = 10.0, min_frequency: float = 0.0, max_frequency: float = 8000.0, preemphasis: float = 0.0, preemphasis_htk_flavor: bool = True, fft_overdrive: bool = False, dither: float = 0.0, input_scale_factor: float = 1.0, mel_floor: float = 0.001, per_bin_mean: collections.abc.Sequence[float] | None = None, per_bin_stddev: collections.abc.Sequence[float] | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/feature_extraction_gemma4.py#L49)

**参数：**

feature_size (`int`，*可选*，默认为 128)：提取特征的维度。

sampling_rate (`int`，*可选*，默认值为 16000)：音频文件应被数字化采样的采样率，单位为赫兹（Hz）。

padding_value (`float`, *可选*, 默认值为 0.0) : 用于填充音频的填充值。应对应静音。

return_attention_mask (`bool`, *可选*，默认为 `True`) : 是否返回生成的 MEL 频谱图的注意力掩码。

frame_length_ms (`float`, *可选*，默认为 20.0)：帧的时长（以毫秒为单位）。

hop_length_ms (`float`, *可选*，默认为 10.0)：用于获取梅尔频率系数的 STFT 的重叠窗口长度。

min_frequency (`float`, *可选*，默认为 0.0)：梅尔滤波器组的最小频率（单位：Hz）。

max_frequency (`float`, *可选*，默认为 8000.0)：Mel 滤波器组的最大频率（单位：Hz）。

preemphasis (`float`, *可选*, 默认为 0.0) : 预加重系数。

preemphasis_htk_flavor (`bool`，*可选*，默认为 `True`)：是否使用 HTK 风格的预加重。

fft_overdrive (`bool`，*可选*，默认为 `False`)：是否使用 FFT 过载。

dither (`float`, *可选*，默认为 0.0)：添加抖动。换句话说，为每一帧添加少量高斯噪声。例如，使用 0.0001 可添加以 0.0 为中心、标准差为 0.0001 的正态分布抖动（假设 raw_speech 的范围为 [-1,+1]）。值 0.0 表示不添加抖动。抖动的作用类似于 `spectrogram(mel_floor=...)`。当信号中存在 VAD 截断时，它可以降低具有硬零部分的信号的高 log_mel_fbank 值。

input_scale_factor (`float`, *可选*，默认为 1.0)：应用于输入波形的缩放因子。

mel_floor (`float`, *可选*，默认为 0.001)：梅尔频谱图的最小值，以避免 log(0)。

per_bin_mean (`Optional[Sequence[float]]`, *可选*) : 用于逐 bin 归一化的均值。

per_bin_stddev (`Optional[Sequence[float]]`, *可选*) : 用于按 bin 归一化的标准差值。

音频特征提取器 Universal Speech Models https://huggingface.co/papers/2303.01037。

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

```python
__call__(raw_speech: numpy.ndarray | list[float] | list[numpy.ndarray] | list[list[float]], padding: bool | str | transformers.utils.generic.PaddingStrategy = 'longest', max_length: int | None = 480000, truncation: bool = True, pad_to_multiple_of: int | None = 128, return_tensors: str | transformers.utils.generic.TensorType | None = None, return_attention_mask: bool | None = True, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/feature_extraction_gemma4.py#L226)

**参数：**

raw_speech : 用于创建 MEL 频谱图的音频。

padding (`Union[bool, str, PaddingStrategy]`，*可选*，默认为 `"longest"`)：用于处理长度不同的音频批次的填充策略。

max_length (`int`，*可选*，默认为 480000)：如果提供，则定义允许的最大音频长度。如果 `truncation=True`，则超过此长度的音频将被截断。

truncation (`bool`，*可选*，默认为 `True`)：是否截断超过 `max_length` 的音频。

pad_to_multiple_of (`int`，*可选*，默认为 128)：填充时，将序列填充为该值的倍数。默认值针对 TPU 的最佳支持进行了定义。

return_tensors (`Union[str, TensorType]`，*可选*，默认为 `None`)：要返回的张量类型（例如 NumPy 或 Torch）。

return_attention_mask (`bool`, *可选*，默认为 `True`) : 是否返回生成的 MEL 频谱图的注意力掩码。

根据提供的原始语音创建一批 MEL 频谱图。

此实现在加窗和预加重方面采用了与内置的 `transformers.audio_utils.spectrogram()` 函数不同的算法，_因此_会产生不同的输出。在选择音频特征提取器时，尤其是使用预训练模型时，请仔细考虑这一点。

## Gemma4ImageProcessorPil[[transformers.Gemma4ImageProcessorPil]]

#### transformers.Gemma4ImageProcessorPil[[transformers.Gemma4ImageProcessorPil]]

```python
transformers.Gemma4ImageProcessorPil(**kwargs: *<class 'transformers.models.gemma4.image_processing_pil_gemma4.Gemma4ImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/image_processing_pil_gemma4.py#L137)

**参数：**

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*)：描述模型的最大输入维度。

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*，默认值为 `3`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.00392156862745098`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`, *kwargs*, *可选*, 默认为 `False`) : 是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.0, 0.0, 0.0]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[1.0, 1.0, 1.0]`) : 用于归一化的图像标准差。仅当 `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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

patch_size (`int`, *kwargs*, *可选*) : 每个图像补丁的像素尺寸。

max_soft_tokens (`int`, *kwargs*, *可选*) : 每张图片中软（视觉）令牌的最大数量。必须是 {70, 140, 280, 560, 1120} 之一。

pooling_kernel_size (`int`, *kwargs*, *可选*) : 在分块（patchification）之后应用的空间池化核大小。

构建 Gemma4 图像处理器。

#### preprocess[[transformers.Gemma4ImageProcessorPil.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.gemma4.image_processing_pil_gemma4.Gemma4ImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/image_processing_pil_gemma4.py#L167)

**参数：**

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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

patch_size (`int`, *kwargs*, *可选*) : 每个图像补丁的像素尺寸。

max_soft_tokens (`int`, *kwargs*, *可选*) : 每张图片中软（视觉）令牌的最大数量。必须是 {70, 140, 280, 560, 1120} 之一。

pooling_kernel_size (`int`, *kwargs*, *可选*) : 在分块（patchification）之后应用的空间池化核大小。

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

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

## Gemma4ImageProcessor[[transformers.Gemma4ImageProcessor]]

#### transformers.Gemma4ImageProcessor[[transformers.Gemma4ImageProcessor]]

```python
transformers.Gemma4ImageProcessor(**kwargs: *<class 'transformers.models.gemma4.image_processing_gemma4.Gemma4ImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/image_processing_gemma4.py#L136)

**参数：**

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*，默认为 `None`)：描述模型的最大输入维度。

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*，默认值为 `3`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.00392156862745098`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`, *kwargs*, *可选*, 默认为 `False`) : 是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.0, 0.0, 0.0]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[1.0, 1.0, 1.0]`) : 用于归一化的图像标准差。仅当 `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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

patch_size (`int`, *kwargs*, *可选*) : 每个图像补丁的像素尺寸。

max_soft_tokens (`int`, *kwargs*, *可选*) : 每张图片中软（视觉）令牌的最大数量。必须是 {70, 140, 280, 560, 1120} 之一。

pooling_kernel_size (`int`, *kwargs*, *可选*) : 在分块（patchification）之后应用的空间池化核大小。

构建 Gemma4 图像处理器。

#### preprocess[[transformers.Gemma4ImageProcessor.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.gemma4.image_processing_gemma4.Gemma4ImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/image_processing_gemma4.py#L193)

## Gemma4VideoProcessor[[transformers.Gemma4VideoProcessor]]

#### transformers.Gemma4VideoProcessor[[transformers.Gemma4VideoProcessor]]

```python
transformers.Gemma4VideoProcessor(**kwargs: *<class 'transformers.models.gemma4.video_processing_gemma4.Gemma4VideoProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/video_processing_gemma4.py#L155)

**参数：**

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*，默认为 `None`)：描述模型的最大输入维度。

default_to_square (`bool`，*kwargs*，*可选*，默认为 `True`)：当 size 为整数时，是否在调整大小时默认使用正方形图像。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认值为 `3`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `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.0, 0.0, 0.0]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[1.0, 1.0, 1.0]`) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

do_pad (`bool`, *kwargs*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

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*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

do_sample_frames (`bool`, *kwargs*, *可选*，默认为 `True`)：是否在处理前从视频中采样帧，还是处理整个视频。

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : 视频的元数据，包含总时长、帧率（fps）和总帧数等信息。该元数据将用于从视频中采样帧或计算时间戳。除非您打算在预处理之前手动解码视频，否则请勿传入任何元数据。

fps (`Annotated[int | float | None, None]`, *kwargs*) : 当 `do_sample_frames=True` 时，每秒采样的目标帧数。

num_frames (`Annotated[int | None, None]`, *kwargs*，默认为 `32`)：当 `do_sample_frames=True` 时，采样的最大帧数。

return_metadata (`bool`, *kwargs*, *可选*，默认为 `False`) : 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

patch_size (`int`, *kwargs*, *可选*) : 每个图像补丁的像素尺寸。

max_soft_tokens (`int`, *kwargs*, *可选*) : 每个视频帧中软（视觉）令牌的最大数量。必须是 {70, 140, 280, 560, 1120} 之一。

pooling_kernel_size (`int`, *kwargs*, *可选*) : 在分块（patchification）之后应用的空间池化核大小。

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

构造一个 Gemma4VideoProcessor 视频处理器。

#### preprocess[[transformers.Gemma4VideoProcessor.preprocess]]

```python
preprocess(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]]], **kwargs: *<class 'transformers.models.gemma4.video_processing_gemma4.Gemma4VideoProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/video_processing_gemma4.py#L214)

**参数：**

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

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

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_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

do_pad (`bool`, *kwargs*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

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*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

do_sample_frames (`bool`, *kwargs*, *可选*) : 是否在处理前从视频中采样帧，还是处理整个视频。

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : 视频的元数据，包含总时长、帧率（fps）和总帧数等信息。该元数据将用于从视频中采样帧或计算时间戳。除非您打算在预处理之前手动解码视频，否则请勿传入任何元数据。

fps (`Annotated[int | float | None, None]`, *kwargs*) : 当 `do_sample_frames=True` 时，每秒采样的目标帧数。

num_frames (`Annotated[int | None, None]`, *kwargs*) : 当 `do_sample_frames=True` 时，要采样的最大帧数。

return_metadata (`bool`, *kwargs*, *可选*) : 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

patch_size (`int`, *kwargs*, *可选*) : 每个图像补丁的像素尺寸。

max_soft_tokens (`int`, *kwargs*, *可选*) : 每个视频帧中软（视觉）令牌的最大数量。必须是 {70, 140, 280, 560, 1120} 之一。

pooling_kernel_size (`int`, *kwargs*, *可选*) : 在分块（patchification）之后应用的空间池化核大小。

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

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

## Gemma4Processor[[transformers.Gemma4Processor]]

#### transformers.Gemma4Processor[[transformers.Gemma4Processor]]

```python
transformers.Gemma4Processor(feature_extractor, image_processor, tokenizer, video_processor, chat_template = None, image_seq_length: int = 280, audio_seq_length: int = 750, audio_ms_per_token: int = 40, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/processing_gemma4.py#L87)

**参数：**

feature_extractor (*Gemma4AudioFeatureExtractor*)：特征提取器是必需的输入。

image_processor (*Gemma4ImageProcessor*)：图像处理器是必需的输入。

tokenizer (*tokenizer_class*)：分词器是必需的输入。

video_processor (*Gemma4VideoProcessor*)：视频处理器是必需的输入。

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

image_seq_length (*int*，*optional*，默认为 280)：用于占位符扩展的每张图像的软标记数量。

audio_seq_length (*int*, *optional*, 默认值为 750) : 每个音频片段中音频软令牌的最大数量。在计算动态音频令牌数量时，作为上限约束。

audio_ms_per_token (*int*, *optional*, 默认值为 40) : 每个输出软令牌对应的音频毫秒数。用于动态计算音频占位令牌的数量，公式为 `ceil(duration_ms / audio_ms_per_token)`。默认值 40 源自 SSCP 卷积在 10ms 帧上实现的 4 倍时间缩减。

构造一个 Gemma4Processor，它将特征提取器、图像处理器、分词器和视频处理器封装为单一处理器。

[*Gemma4Processor*] 提供了 [*Gemma4AudioFeatureExtractor*]、[*Gemma4ImageProcessor*]、[*tokenizer_class*] 和 [*Gemma4VideoProcessor*] 的所有功能。有关更多信息，请参阅 [*~Gemma4AudioFeatureExtractor*]、[*~Gemma4ImageProcessor*]、[*~tokenizer_class*] 和 [*~Gemma4VideoProcessor*]。

#### __调用__[[transformers.Gemma4Processor.__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/main/src/transformers/processing_utils.py#L671)

**参数：**

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/main/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

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

## Gemma4PreTrainedModel[[transformers.Gemma4PreTrainedModel]]

#### transformers.Gemma4PreTrainedModel[[transformers.Gemma4PreTrainedModel]]

```python
transformers.Gemma4PreTrainedModel(config: PreTrainedConfig, *inputs, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/modeling_gemma4.py#L1436)

**参数：**

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

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.Gemma4PreTrainedModel.forward]]

```python
forward(*args, **kwargs)
```

点分路径（例如 `torch.float32`）的模拟值：属性访问链和调用行为如同透传装饰器，`repr` 为点分路径，将其用作基类时会替换为普通的 `type` 基类（PEP 560 `__mro_entries__`），因此真实的子类保留正常的元类，且 `inspect.signature` 读取的是它们真实的 `__init__`，而非模拟对象的。

## Gemma4AudioModel[[transformers.Gemma4AudioModel]]

#### transformers.Gemma4AudioModel[[transformers.Gemma4AudioModel]]

```python
transformers.Gemma4AudioModel(config: Gemma4AudioConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/modeling_gemma4.py#L1956)

基于 [Universal Speech Model](https://huggingface.co/papers/2303.01037) 架构的音频编码器。

#### forward[[transformers.Gemma4AudioModel.forward]]

```python
forward(input_features: Tensor, attention_mask: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/modeling_gemma4.py#L2013)

**参数：**

input_features (`torch.Tensor`，形状为 `(batch_size, sequence_length, feature_dim)`)：与输入音频特征对应的张量。可以使用 [Gemma4AudioFeatureExtractor](/docs/transformers/main/zh/model_doc/gemma4#transformers.Gemma4AudioFeatureExtractor) 获取音频特征。有关详细信息，请参阅 [Gemma4AudioFeatureExtractor.__call__()](/docs/transformers/main/zh/model_doc/gemma4#transformers.Gemma4AudioFeatureExtractor.__call__)（[Gemma4Processor](/docs/transformers/main/zh/model_doc/gemma4#transformers.Gemma4Processor) 使用 [Gemma4AudioFeatureExtractor](/docs/transformers/main/zh/model_doc/gemma4#transformers.Gemma4AudioFeatureExtractor) 处理音频）。

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

**返回值：**

`tuple[torch.Tensor, torch.BoolTensor]`

将音频特征编码为软标记。

## Gemma4VisionModel[[transformers.Gemma4VisionModel]]

#### transformers.Gemma4VisionModel[[transformers.Gemma4VisionModel]]

```python
transformers.Gemma4VisionModel(config: Gemma4VisionConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/modeling_gemma4.py#L2048)

Gemma 4 视觉编码器。

#### forward[[transformers.Gemma4VisionModel.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/modeling_gemma4.py#L2069)

**参数：**

pixel_values (`torch.Tensor` 或 `list[torch.Tensor]`)：要编码的图像。可以是单个 `[batch, channels, height, width]` 张量（所有图像尺寸相同），也可以是 `[1, channels, height, width]` 张量的列表（尺寸不同）。

pixel_position_ids (`torch.LongTensor`，形状为 `(batch_size, max_patches, 2)`)：图像中每个 patch 的位置，以 (x, y) 坐标表示。填充的 patch 用 (-1, -1) 表示。

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

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

将图像像素编码为来自图像块的软标记。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。

  如果使用了`cache`，则仅输出形状为`(batch_size, 1, hidden_size)`的序列的最后一个隐藏状态。
- **cache**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

## Gemma4TextModel[[transformers.Gemma4TextModel]]

#### transformers.Gemma4TextModel[[transformers.Gemma4TextModel]]

```python
transformers.Gemma4TextModel(config: Gemma4TextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/modeling_gemma4.py#L1535)

**参数：**

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

不带语言建模头的 Gemma 4 基础语言模型。

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.Gemma4TextModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, per_layer_inputs: typing.Optional[torch.Tensor] = 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/main/src/transformers/models/gemma4/modeling_gemma4.py#L1593)

**参数：**

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

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `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` 索引转换为对应的向量，这将非常有用。

per_layer_inputs (`torch.Tensor`, *可选*) : 形状为 `(batch_size, sequence_length, num_hidden_layers, hidden_size_per_layer_input)` 的预计算逐层输入文本嵌入。如果提供，这些嵌入将直接用于替代在文本模型中通过 `get_per_layer_inputs()` 从 `input_ids` 计算得到的结果。如果调用 `forward` 时使用 `inputs_embeds` 而非 `input_ids`，建议预先计算它们并随 `inputs_embeds` 一起传入，否则重新计算它们需要反转主嵌入，开销较大。

use_cache (`bool`, *可选*) : 如果设置为 `True`，则会返回 `cache` 键值状态，可用于加速解码（参见 `cache`）。

logits_to_keep (`Union[int, torch.Tensor]`，*可选*，默认为 `0`)：如果为 `int`，则计算最后 `logits_to_keep` 个 token 的 logits。如果为 `0`，则计算所有 `input_ids` 的 logits（特殊情况）。生成过程只需要最后一个 token 的 logits，仅针对该 token 进行计算可以节省内存，对于长序列或大词汇量而言，这种节省相当可观。如果为 `torch.Tensor`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

**返回：** `Gemma4TextModelOutputWithPast` 或 `tuple(torch.Tensor)`

`Gemma4TextModelOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[Gemma4TextModel](/docs/transformers/main/zh/model_doc/gemma4#transformers.Gemma4TextModel) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。

  如果使用了`cache`，则仅输出形状为`(batch_size, 1, hidden_size)`的序列的最后一个隐藏状态。
- **cache**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **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 后的注意力权重，用于在自注意力头中计算加权平均值。
- **shared_kv_states** (`KVSharingDict`，*可选*) -- 一个类似字典的容器，将层类型字符串映射到 (key_states, value_states) 张量元组。用于在 KV 共享期间在层之间传递共享的 KV 状态。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，在传入 `output_router_logits=True` 时返回) -- 一个 `torch.Tensor` 元组（每个 MoE 层对应一个），形状为 `(batch_size * sequence_length, num_experts)`。

## Gemma4ForCausalLM[[transformers.Gemma4ForCausalLM]]

#### transformers.Gemma4ForCausalLM[[transformers.Gemma4ForCausalLM]]

```python
transformers.Gemma4ForCausalLM(config: Gemma4TextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/modeling_gemma4.py#L1845)

**参数：**

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

带有语言建模头的基础 Gemma 4 语言模型。

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.Gemma4ForCausalLM.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: 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, per_layer_inputs: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/modeling_gemma4.py#L1862)

**参数：**

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

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `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`，则会返回 `cache` 键值状态，可用于加速解码（参见 `cache`）。

logits_to_keep (`Union[int, torch.Tensor]`，*可选*，默认为 `0`)：如果为 `int`，则计算最后 `logits_to_keep` 个 token 的 logits。如果为 `0`，则计算所有 `input_ids` 的 logits（特殊情况）。生成过程只需要最后一个 token 的 logits，仅针对该 token 进行计算可以节省内存，对于长序列或大词汇量而言，这种节省相当可观。如果为 `torch.Tensor`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

per_layer_inputs (`torch.Tensor`, *可选*) : 形状为 `(batch_size, sequence_length, num_hidden_layers, hidden_size_per_layer_input)` 的预计算逐层输入文本嵌入。如果提供，这些嵌入将直接用于替代在文本模型中通过 `get_per_layer_inputs()` 从 `input_ids` 计算得到的结果。如果调用 `forward` 时使用 `inputs_embeds` 而非 `input_ids`，建议预先计算它们并随 `inputs_embeds` 一起传入，否则重新计算它们需要反转主嵌入，开销较大。

**返回：** `Gemma4CausalLMOutputWithPast` 或 `tuple(torch.Tensor)`

`Gemma4CausalLMOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[Gemma4ForCausalLM](/docs/transformers/main/zh/model_doc/gemma4#transformers.Gemma4ForCausalLM) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.FloatTensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.FloatTensor`）—— 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **cache** (`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回) -- 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。其中包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.FloatTensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每个层的输出各一个），形状为 `(batch_size, sequence_length, hidden_size)`。语言模型主干在每个层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。语言模型主干的注意力权重，位于注意力 softmax 之后。
- **image_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 图像编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何图像，则为 `None`。
- **video_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 视频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何视频，则为 `None`。
- **audio_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 音频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理音频，则为 `None`。
- **shared_kv_states** (`dict`, *可选*) -- 一个字典，将层类型字符串映射到 (key_states, value_states) 张量元组。用于在 KV 共享期间在层之间传递共享的 KV 状态。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，在传入 `output_router_logits=True` 时返回) -- 一个 `torch.Tensor` 元组（每个 MoE 层对应一个），形状为 `(batch_size * sequence_length, num_experts)`。

示例：

```python
>>> from transformers import AutoTokenizer, Gemma4ForCausalLM

>>> model = Gemma4ForCausalLM.from_pretrained("google/gemma-4-E2B-it")
>>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-4-E2B-it")

>>> prompt = "What is your favorite condiment?"
>>> 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]
"What is your favorite condiment?"
```

## Gemma4Model[[transformers.Gemma4Model]]

#### transformers.Gemma4Model[[transformers.Gemma4Model]]

```python
transformers.Gemma4Model(config: Gemma4Config)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/modeling_gemma4.py#L2224)

**参数：**

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

基础 Gemma 4 模型，包含视觉骨干网络、音频骨干网络以及不带语言建模头的语言模型。

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.Gemma4Model.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, pixel_values_videos: typing.Optional[torch.Tensor] = None, input_features: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, input_features_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, mm_token_type_ids: typing.Optional[torch.LongTensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, image_position_ids: typing.Optional[torch.LongTensor] = None, video_position_ids: typing.Optional[torch.LongTensor] = None, num_frames_per_video: typing.Optional[torch.LongTensor] = None, per_layer_inputs: typing.Optional[torch.Tensor] = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/modeling_gemma4.py#L2320)

**参数：**

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

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

pixel_values_videos (`torch.Tensor`，形状为 `(batch_size, num_frames, num_channels, frame_size, frame_size)`，*可选*)：与输入视频对应的张量。可以使用 `video_processor_class` 获取视频的像素值。有关详细信息，请参阅 `video_processor_class.__call__`（`processor_class` 使用 `video_processor_class` 来处理视频）。

input_features (`torch.Tensor`，形状为 `(batch_size, sequence_length, feature_dim)`，*可选*) : 与输入音频特征对应的张量。可以使用 `feature_extractor_class` 获取音频特征。有关详细信息，请参阅 `feature_extractor_class.__call__`（`processor_class` 使用 `feature_extractor_class` 处理音频）。

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

input_features_mask (`torch.Tensor`，形状为 `(num_images, seq_length)`)：输入音频的注意力掩码。

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

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

mm_token_type_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：与每种模态匹配的输入序列 token 的索引。例如文本 (0)、图像 (1)、视频 (2)。可以使用 [AutoProcessor](/docs/transformers/main/zh/model_doc/auto#transformers.AutoProcessor) 获取多模态 token 类型 ID。有关详细信息，请参阅 [ProcessorMixin.__call__()](/docs/transformers/main/zh/main_classes/processors#transformers.ProcessorMixin.__call__)。

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

use_cache (`bool`, *可选*) : 如果设置为 `True`，则会返回 `cache` 键值状态，可用于加速解码（参见 `cache`）。

image_position_ids (`torch.LongTensor`，形状为 `(batch_size, max_patches, 2)`，*可选*)：来自图像处理器（image processor）的 2D patch 位置坐标，其中 `(-1, -1)` 表示填充（padding）。该参数会传递给视觉编码器（vision encoder），用于计算位置嵌入（positional embedding）。

video_position_ids (`torch.LongTensor`，形状为 `(total_num_frames, max_patches, 2)`，*可选*)：来自视频处理器的 2D patch 位置坐标，其中 `(-1, -1)` 表示填充。该参数会传递给视觉编码器，用于计算位置嵌入。

num_frames_per_video (`torch.LongTensor`，形状为 `(num_videos,)`，*可选*)：每个视频包含的帧数。只要传递了 `pixel_values_videos`，此参数就是必需的，因为所有视频的帧都沿单一轴拼接在一起。

per_layer_inputs (`torch.Tensor`, *可选*) : 形状为 `(batch_size, sequence_length, num_hidden_layers, hidden_size_per_layer_input)` 的预计算逐层输入文本嵌入。如果提供，这些嵌入将直接用于替代在文本模型中通过 `get_per_layer_inputs()` 从 `input_ids` 计算得到的结果。如果调用 `forward` 时使用 `inputs_embeds` 而非 `input_ids`，建议预先计算它们并随 `inputs_embeds` 一起传入，否则重新计算它们需要反转主嵌入，开销较大。

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *可选*) : 一个字典，其中键为支持的模态，值为该模态的编码输出。每个编码输出是一个元组，由 (`pooler_output`, *可选*: `last_hidden_states`, *可选*: `hidden_states`, *可选*: `attentions`) 组成，其中 `pooler_output` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

**返回：** `Gemma4ModelOutputWithPast` 或 `tuple(torch.Tensor)`

`Gemma4ModelOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[Gemma4Model](/docs/transformers/main/zh/model_doc/gemma4#transformers.Gemma4Model) 的 forward 方法会重写 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.FloatTensor`）-- 语言模型主干最后一层输出的隐藏状态序列。如果使用 `cache`，则仅输出形状为 `(batch_size, 1, hidden_size)` 的序列最后一个隐藏状态。
- **cache** (`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回) -- 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。其中包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.FloatTensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每个层的输出各一个），形状为 `(batch_size, sequence_length, hidden_size)`。语言模型主干在每个层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。语言模型主干的注意力权重，位于注意力 softmax 之后。
- **image_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 图像编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何图像，则为 `None`。
- **video_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 视频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何视频，则为 `None`。
- **audio_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 音频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理音频，则为 `None`。
- **shared_kv_states** (`dict`, *可选*) -- 一个字典，将层类型字符串映射到 (key_states, value_states) 张量元组。用于在 KV 共享期间在层之间传递共享的 KV 状态。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，在传入 `output_router_logits=True` 时返回) -- 一个 `torch.Tensor` 元组（每个 MoE 层对应一个），形状为 `(batch_size * sequence_length, num_experts)`。

## Gemma4ForConditionalGeneration[[transformers.Gemma4ForConditionalGeneration]]

#### transformers.Gemma4ForConditionalGeneration[[transformers.Gemma4ForConditionalGeneration]]

```python
transformers.Gemma4ForConditionalGeneration(config: Gemma4Config)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/modeling_gemma4.py#L2587)

**参数：**

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

基础 Gemma 4 模型，包含视觉骨干网络、音频骨干网络、语言模型以及语言建模头。

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.Gemma4ForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, pixel_values_videos: typing.Optional[torch.Tensor] = None, input_features: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, input_features_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, image_position_ids: typing.Optional[torch.LongTensor] = None, video_position_ids: typing.Optional[torch.LongTensor] = None, num_frames_per_video: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, mm_token_type_ids: typing.Optional[torch.LongTensor] = 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, per_layer_inputs: typing.Optional[torch.Tensor] = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma4/modeling_gemma4.py#L2615)

**参数：**

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

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

pixel_values_videos (`torch.Tensor`，形状为 `(batch_size, num_frames, num_channels, frame_size, frame_size)`，*可选*)：与输入视频对应的张量。可以使用 `video_processor_class` 获取视频的像素值。有关详细信息，请参阅 `video_processor_class.__call__`（`processor_class` 使用 `video_processor_class` 来处理视频）。

input_features (`torch.Tensor`，形状为 `(batch_size, sequence_length, feature_dim)`，*可选*) : 与输入音频特征对应的张量。可以使用 `feature_extractor_class` 获取音频特征。有关详细信息，请参阅 `feature_extractor_class.__call__`（`processor_class` 使用 `feature_extractor_class` 处理音频）。

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

input_features_mask (`torch.Tensor`，形状为 `(num_images, seq_length)`)：输入音频的注意力掩码。

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

image_position_ids (`torch.LongTensor`，形状为 `(batch_size, max_patches, 2)`，*可选*)：来自图像处理器（image processor）的 2D patch 位置坐标，其中 `(-1, -1)` 表示填充（padding）。该参数会传递给视觉编码器（vision encoder），用于计算位置嵌入（positional embedding）。

video_position_ids (`torch.LongTensor`，形状为 `(total_num_frames, max_patches, 2)`，*可选*)：来自视频处理器的 2D patch 位置坐标，其中 `(-1, -1)` 表示填充。该参数会传递给视觉编码器，用于计算位置嵌入。

num_frames_per_video (`torch.LongTensor`，形状为 `(num_videos,)`，*可选*)：每个视频包含的帧数。只要传递了 `pixel_values_videos`，此参数就是必需的，因为所有视频的帧都沿单一轴拼接在一起。

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

mm_token_type_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：与每种模态匹配的输入序列 token 的索引。例如文本 (0)、图像 (1)、视频 (2)。可以使用 [AutoProcessor](/docs/transformers/main/zh/model_doc/auto#transformers.AutoProcessor) 获取多模态 token 类型 ID。有关详细信息，请参阅 [ProcessorMixin.__call__()](/docs/transformers/main/zh/main_classes/processors#transformers.ProcessorMixin.__call__)。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `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`，则会返回 `cache` 键值状态，可用于加速解码（参见 `cache`）。

logits_to_keep (`Union[int, torch.Tensor]`，*可选*，默认为 `0`)：如果为 `int`，则计算最后 `logits_to_keep` 个 token 的 logits。如果为 `0`，则计算所有 `input_ids` 的 logits（特殊情况）。生成过程只需要最后一个 token 的 logits，仅针对该 token 进行计算可以节省内存，对于长序列或大词汇量而言，这种节省相当可观。如果为 `torch.Tensor`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

per_layer_inputs (`torch.Tensor`, *可选*) : 形状为 `(batch_size, sequence_length, num_hidden_layers, hidden_size_per_layer_input)` 的预计算逐层输入文本嵌入。如果提供，这些嵌入将直接用于替代在文本模型中通过 `get_per_layer_inputs()` 从 `input_ids` 计算得到的结果。如果调用 `forward` 时使用 `inputs_embeds` 而非 `input_ids`，建议预先计算它们并随 `inputs_embeds` 一起传入，否则重新计算它们需要反转主嵌入，开销较大。

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *可选*) : 一个字典，其中键为支持的模态，值为该模态的编码输出。每个编码输出是一个元组，由 (`pooler_output`, *可选*: `last_hidden_states`, *可选*: `hidden_states`, *可选*: `attentions`) 组成，其中 `pooler_output` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

**返回：** `Gemma4CausalLMOutputWithPast` 或 `tuple(torch.Tensor)`

`Gemma4CausalLMOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[Gemma4ForConditionalGeneration](/docs/transformers/main/zh/model_doc/gemma4#transformers.Gemma4ForConditionalGeneration) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.FloatTensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.FloatTensor`）—— 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **cache** (`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回) -- 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。其中包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.FloatTensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每个层的输出各一个），形状为 `(batch_size, sequence_length, hidden_size)`。语言模型主干在每个层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。语言模型主干的注意力权重，位于注意力 softmax 之后。
- **image_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 图像编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何图像，则为 `None`。
- **video_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 视频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何视频，则为 `None`。
- **audio_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 音频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理音频，则为 `None`。
- **shared_kv_states** (`dict`, *可选*) -- 一个字典，将层类型字符串映射到 (key_states, value_states) 张量元组。用于在 KV 共享期间在层之间传递共享的 KV 状态。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，在传入 `output_router_logits=True` 时返回) -- 一个 `torch.Tensor` 元组（每个 MoE 层对应一个），形状为 `(batch_size * sequence_length, num_experts)`。

