Transformers documentation

Gemma4

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2026-04-02 贡献至 Hugging Face Transformers。

Gemma4

概述

Gemma 4 是一个多模态模型,提供预训练和指令微调版本,参数规模包括 E2B、E4B、31B 和 26B-A4B(MoE)。Gemma 4 模型提供以下功能:

  • 推理:该系列中的所有模型均被设计为具备强大推理能力的模型,并支持可配置的思考模式。
  • 扩展多模态:支持处理文本、具有可变宽高比和分辨率的图像(所有模型均支持)、视频以及音频(E2B 和 E4B 模型原生支持)。
  • 上下文窗口扩展:小型模型的上下文窗口为 128K,而其他模型支持 256K。
  • 增强的编码与智能体能力:在编码基准测试中取得了显著的提升,同时内置了函数调用支持,从而驱动了能力强大的自主智能体。
  • 原生系统提示词支持:Gemma 4 引入了对 system 角色的内置支持,从而实现更结构化、更可控的对话。

您可以在 Gemma 4 发布中找到所有原始的 Gemma 4 检查点。

Gemma4 视觉模型

与之前发布的 Gemma 视觉模型相比,关键区别在于采用了新的设计,使用固定数量的 token 预算来处理不同尺寸的图像。与许多将每张图像压缩为固定正方形(例如 224×224)的模型不同,Gemma 4 在调整图像至合适尺寸的同时,保留了图像的自然宽高比。需要遵循以下几项约束:

  • 总像素数必须控制在补丁预算范围内
  • 高度和宽度都必须能被 48(= 补丁大小 16 × 池化核 3)整除

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

图像处理器可生成的“软标记”(即视觉标记)数量是可配置的。下方列出了支持的选项,默认值为每张图像 280 个软标记。

软标记补丁(池化前)近似图像面积
70630~161K 像素
1401,260~323K 像素
2802,520约 645K 像素
5605,040约 130 万像素
1,12010,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 或 AutoModel 类基于图像生成文本。

<hfoptions id="usage"> <hfoption id="Pipeline">
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?"
)
</hfoption> <hfoption id="AutoModel">
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))

函数调用

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

音频(仅限 E2B 和 E4B)

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

class transformers.Gemma4AudioConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 1024num_hidden_layers: int = 12num_attention_heads: int = 8hidden_act: str = 'silu'subsampling_conv_channels: list[int] | tuple[int, int] = (128, 32)conv_kernel_size: int = 5residual_weight: float = 0.5attention_chunk_size: int = 12attention_context_left: int = 13attention_context_right: int = 0attention_logit_cap: float = 50.0attention_invalid_logits_value: float = -1000000000.0use_clipped_linears: bool = Truerms_norm_eps: float = 1e-06gradient_clipping: float = 10000000000.0output_proj_dims: int = 1536initializer_range: float = 0.02 )

参数

  • 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) — 用于 attention 中无效 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 类似的配置。

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

Gemma4VisionConfig

class transformers.Gemma4VisionConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 768intermediate_size: int = 3072num_hidden_layers: int = 16num_attention_heads: int = 12num_key_value_heads: int = 12head_dim: int = 64hidden_activation: str = 'gelu_pytorch_tanh'rms_norm_eps: float = 1e-06max_position_embeddings: int = 131072attention_bias: bool | None = Falseattention_dropout: float | None = 0.0rope_parameters: dict | None = Nonepooling_kernel_size: int = 3patch_size: int = 16position_embedding_size: int = 10240use_clipped_linears: bool = Falsestandardize: bool = Falseinitializer_range: float = 0.02 )

参数

  • 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 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 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) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • attention_dropout (float,可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • rope_parameters (dict, 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • pooling_kernel_size (int, 可选) — 在分块(patchification)之后应用的空间池化核大小。
  • patch_size (int,可选,默认为 16) — 每个 patch 的大小(分辨率)。
  • position_embedding_size (int,默认为 10240) — 视觉编码器位置嵌入的最大数量。控制 patch embedder 所使用的可学习 2D 位置嵌入表的大小。
  • use_clipped_linears (bool,默认为 False) — 是否使用权重裁剪的线性层。启用后,线性层的权重在前向传播过程中会被限制在固定范围内,以提升数值稳定性。
  • standardize (bool,默认为 False) — 如果为 true,则对池化器返回的软标记应用偏置和缩放。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

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

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

Gemma4TextConfig

class transformers.Gemma4TextConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 262144hidden_size: int = 2304intermediate_size: int = 9216num_hidden_layers: int = 30num_attention_heads: int = 8num_key_value_heads: int = 4head_dim: int = 256hidden_activation: str = 'gelu_pytorch_tanh'max_position_embeddings: int = 131072initializer_range: float = 0.02rms_norm_eps: float = 1e-06use_cache: bool = Truepad_token_id: int | None = 0eos_token_id: int | list[int] | None = 1bos_token_id: int | None = 2tie_word_embeddings: bool = Truerope_parameters: dict | None = Noneattention_bias: bool = Falseattention_dropout: int | float | None = 0.0sliding_window: int = 512layer_types: list[str] | None = Nonefinal_logit_softcapping: float | None = Noneuse_bidirectional_attention: typing.Optional[typing.Literal['all', 'vision']] = Nonevocab_size_per_layer_input: int = 262144hidden_size_per_layer_input: int = 256attention_k_eq_v: bool = Falsenum_kv_shared_layers: int = 0enable_moe_block: bool = Falseuse_double_wide_mlp: bool = Falsenum_experts: int | None = Nonetop_k_experts: int | None = Nonemoe_intermediate_size: int | None = None )

参数

  • 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 头应通过对该组内所有原始头进行 meanpooling 来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 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 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • attention_bias (bool,可选,默认为 False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • attention_dropout (Union[int, float],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • sliding_window (int,可选,默认为 512) — 滑动窗口注意力的窗口大小。如果为 None,则不应用滑动窗口。
  • layer_types (list[str], 可选) — 一个列表,用于显式地将每个层索引映射到其层类型。如果未提供,将根据 config 值自动生成。
  • 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 文档。
  • 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) — 是否使用具有融合 gate 和 up 投影的双宽度 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 类似的配置。

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

Gemma4Config

class transformers.Gemma4Config

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonetext_config: transformers.models.gemma4.configuration_gemma4.Gemma4TextConfig | dict[str, typing.Any] | None = Nonevision_config: transformers.models.gemma4.configuration_gemma4.Gemma4VisionConfig | dict[str, typing.Any] | None = Noneaudio_config: transformers.models.gemma4.configuration_gemma4.Gemma4AudioConfig | dict[str, typing.Any] | None = Noneboi_token_id: int | None = 255999eoi_token_id: int | None = 258882image_token_id: int | None = 258880video_token_id: int | None = 258884boa_token_id: int | None = 256000eoa_token_index: int | None = 258883audio_token_id: int | None = 258881initializer_range: float | None = 0.02tie_word_embeddings: bool = True )

参数

  • 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) — 用于包裹图像提示的图像起始(begin-of-image)标记索引。
  • eoi_token_id (int, 可选,默认为 258882) — 用于包裹图像提示的图像结束标记索引。
  • image_token_id (int,可选,默认为 258880) — 用作输入图像占位符的图像 token 索引。
  • video_token_id (int,可选,默认为 258884) — 用作输入视频占位符的视频 token 索引。
  • boa_token_id (int,可选,默认为 256000) — 用于包裹音频提示的音频起始(begin-of-audio)标记索引。
  • 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 类似的配置。

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

示例:

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

class transformers.Gemma4AudioFeatureExtractor

< >

( feature_size: int = 128sampling_rate: int = 16000padding_value: float = 0.0return_attention_mask: bool = Trueframe_length_ms: float = 20.0hop_length_ms: float = 10.0min_frequency: float = 0.0max_frequency: float = 8000.0preemphasis: float = 0.0preemphasis_htk_flavor: bool = Truefft_overdrive: bool = Falsedither: float = 0.0input_scale_factor: float = 1.0mel_floor: float = 0.001per_bin_mean: collections.abc.Sequence[float] | None = Noneper_bin_stddev: collections.abc.Sequence[float] | None = None**kwargs )

参数

  • 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) — Mel 滤波器组的最小频率(单位:Hz)。
  • max_frequency (float,可选,默认值为 8000.0) — Mel 滤波器组的最大频率(单位:Hz)。
  • preemphasis (float,可选,默认为 0.0) — 预加重系数。
  • preemphasis_htk_flavor (bool,可选,默认为 True) — 是否使用 HTK 风格的预加重。
  • fft_overdrive (bool,可选,默认为 False) — 是否使用 FFT overdrive。
  • 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]],可选) — 用于分箱归一化的均值。
  • per_bin_stddev (Optional[Sequence[float]], 可选) — 用于按 bin 归一化的标准差值。

用于通用语音模型的音频特征提取器 https://huggingface.co/papers/2303.01037。

__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 = 480000truncation: bool = Truepad_to_multiple_of: int | None = 128return_tensors: str | transformers.utils.generic.TensorType | None = Nonereturn_attention_mask: bool | None = True**kwargs )

参数

  • 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

class transformers.Gemma4ImageProcessorPil

< >

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

参数

  • 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 为 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,默认为 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,可选) — 每张图片的最大软(视觉)token 数量。 必须是 {70, 140, 280, 560, 1120} 之一。
  • pooling_kernel_size (int, kwargs, 可选) — 在分块(patchification)之后应用的空间池化核大小。

构建 Gemma4 图像处理器。

预处理

< >

( 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'> ) → ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • default_to_square (bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float, kwargs, 可选) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • patch_size (int, kwargs, 可选) — 每个图像补丁的像素尺寸。
  • max_soft_tokens (int,kwargs,可选) — 每张图片的最大软(视觉)token 数量。 必须是 {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

class transformers.Gemma4ImageProcessor

< >

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

参数

  • 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 为 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,默认为 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,可选) — 每张图片的最大软(视觉)token 数量。 必须是 {70, 140, 280, 560, 1120} 之一。
  • pooling_kernel_size (int, kwargs, 可选) — 在分块(patchification)之后应用的空间池化核大小。

构建 Gemma4 图像处理器。

预处理

< >

( 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'> )

Gemma4VideoProcessor

class transformers.Gemma4VideoProcessor

< >

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

参数

  • 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 为 int 时,是否在调整大小时默认使用正方形图像。
  • 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,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

构造一个 Gemma4VideoProcessor 视频处理器。

预处理

< >

( 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'> ) → ~image_processing_base.BatchFeature

参数

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

class transformers.Gemma4Processor

< >

( feature_extractorimage_processortokenizervideo_processorchat_template = Noneimage_seq_length: int = 280audio_seq_length: int = 750audio_ms_per_token: int = 40**kwargs )

参数

  • feature_extractor (Gemma4AudioFeatureExtractor) — 特征提取器是必需的输入。
  • image_processor (Gemma4ImageProcessor) — 图像处理器是必需的输入。
  • tokenizer (tokenizer_class) — 分词器是必需的输入。
  • video_processor (Gemma4VideoProcessor) — 视频处理器是必需的输入。
  • chat_template (str) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。
  • image_seq_length (int,可选,默认为 280) — 用于占位符扩展的每张图像的软标记数量。
  • audio_seq_length (int,可选,默认为 750) — 每个音频片段中音频软令牌的最大数量。在计算动态音频令牌数量时,作为上限约束。
  • audio_ms_per_token (int,可选,默认为 40) — 每个输出软 token 对应的音频毫秒数。用于动态计算音频占位 token 的数量,公式为 ceil(duration_ms / audio_ms_per_token)。 默认值 40 源自 SSCP 卷积在 10ms 帧上实现的 4 倍时间缩减。

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

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

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = Nonevideos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneaudio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> )

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 可选) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • text (Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置 is_split_into_words=True,以避免与批量输入产生歧义。
  • videos (Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]], 可选) — 要预处理的视频。期望输入单个视频或一批视频,其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间,请设置 do_rescale=False。
  • audio (Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]], 可选) — 要准备处理的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。 如果为 NumPy 数组/PyTorch 张量,每个音频的形状应为 (C, T),其中 C 为通道数,T 为音频的采样长度。
  • return_mm_token_type_ids (bool, kwargs) — 是否返回多模态 token 类型 id,用于指示多模态占位符 token 的位置。
  • return_text_replacement_offsets (bool, kwargs) — 是否返回每个多模态占位符及其替换内容的字符偏移量。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

Gemma4PreTrainedModel

class transformers.Gemma4PreTrainedModel

< >

( config: PreTrainedConfig*inputs**kwargs )

参数

  • config (PreTrainedConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

( *args**kwargs )

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

Gemma4AudioModel

class transformers.Gemma4AudioModel

< >

( config: Gemma4AudioConfig )

基于 Universal Speech Model 架构的音频编码器。

forward

< >

( input_features: Tensorattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> )

参数

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

Gemma4VisionModel

class transformers.Gemma4VisionModel

< >

( config: Gemma4VisionConfig )

Gemma 4 视觉编码器。

forward

< >

( pixel_values: Tensorpixel_position_ids: LongTensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPast or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor 或 list[torch.Tensor]) — 要编码的图像。可以是单个 [batch, channels, height, width] 张量(所有图像尺寸相同),也可以是 [1, channels, height, width] 张量的列表(尺寸不同)。
  • pixel_position_ids(形状为 (batch_size, max_patches, 2) 的 torch.LongTensor)— 图像中每个 patch 的位置,以 (x, y) 坐标表示。填充 patch 用 (-1, -1) 表示。

返回值

BaseModelOutputWithPast 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Gemma4Config)和输入。

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

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

    如果使用了 past_key_values,则仅输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

Gemma4TextModel

class transformers.Gemma4TextModel

< >

( config: Gemma4TextConfig )

参数

  • config (Gemma4TextConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneper_layer_inputs: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Gemma4TextModelOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

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

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • 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,则会返回 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,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。

返回值

Gemma4TextModelOutputWithPast 或 tuple(torch.Tensor)

Gemma4TextModelOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Gemma4Config)和输入。

Gemma4TextModel 的 forward 方法重写了 __call__ 特殊方法。

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

  • 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

class transformers.Gemma4ForCausalLM

< >

( config: Gemma4TextConfig )

参数

  • config (Gemma4TextConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0per_layer_inputs: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Gemma4CausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

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

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 用于计算因果语言建模损失的标签。索引应在 [-100, 0, ..., config.vocab_size] (参见 input_ids 文档字符串)。索引设置为 -100 的 token 将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size].

    标签在内部会进行移位,因此使用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,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。
  • 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 时),其包含的元素取决于配置(Gemma4Config)和输入。

Gemma4ForCausalLM 的 forward 方法重写了 __call__ 特殊方法。

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

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits(形状为 (batch_size, sequence_length, config.text_config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple[torch.Tensor],可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

  • image_hidden_states (torch.Tensor,可选) — 大小为 (batch_size, num_images, sequence_length, hidden_size) 的 torch.Tensor。 由视觉编码器生成的模型 image_hidden_states,即对最后一个隐藏状态进行投影后的结果。

  • audio_hidden_states (torch.Tensor, 可选) — 大小为 (batch_size, num_images, sequence_length, hidden_size) 的 torch.Tensor。 由音频编码器生成并在投影最后一个隐藏状态后得到的模型的 audio_hidden_states。

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

示例:

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

class transformers.Gemma4Model

< >

( config: Gemma4Config )

参数

  • config (Gemma4Config) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_values_videos: typing.Optional[torch.Tensor] = Noneinput_features: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneinput_features_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Nonemm_token_type_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Noneimage_position_ids: typing.Optional[torch.LongTensor] = Nonevideo_position_ids: typing.Optional[torch.LongTensor] = Nonenum_frames_per_video: typing.Optional[torch.LongTensor] = Noneper_layer_inputs: typing.Optional[torch.Tensor] = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Gemma4ModelOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 Gemma4ImageProcessor 获取像素值。有关详细信息,请参阅 Gemma4ImageProcessor.call()(Gemma4Processor 使用 Gemma4ImageProcessor 处理图像)。
  • pixel_values_videos (torch.Tensor,形状为 (batch_size, num_frames, num_channels, frame_size, frame_size),可选) — 对应输入视频的张量。可以使用 Gemma4VideoProcessor 获取视频的像素值。有关详细信息,请参阅 Gemma4VideoProcessor.call()(Gemma4Processor 使用 Gemma4VideoProcessor 来处理视频)。
  • input_features (torch.Tensor,形状为 (batch_size, sequence_length, feature_dim),可选) — 与输入音频特征对应的张量。可以使用 Gemma4AudioFeatureExtractor 获取音频特征。有关详细信息,请参阅 Gemma4AudioFeatureExtractor.call()(Gemma4Processor 使用 Gemma4AudioFeatureExtractor 来处理音频)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • input_features_mask (torch.Tensor,形状为 (num_images, seq_length)) — 输入音频的注意力掩码。
  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • mm_token_type_ids (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 输入序列中匹配每种模态的 token 索引。例如文本 (0)、图像 (1)、视频 (2)。 可通过 AutoProcessor 获取多模态 token 类型 id。详情请参见 ProcessorMixin.call()。
  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • image_position_ids(形状为 (batch_size, max_patches, 2) 的 torch.LongTensor,可选)— 来自图像处理器(image processor)的 2D patch 位置坐标,其中 (-1, -1) 表示填充(padding)。 该参数会传递给视觉编码器,用于计算位置嵌入(positional embedding)。
  • video_position_ids(形状为 (total_num_frames, max_patches, 2) 的 torch.LongTensor,可选) — 来自视频处理器的 2D patch 位置坐标,其中 (-1, -1) 表示填充。 该参数会传递给视觉编码器,用于计算位置嵌入。
  • num_frames_per_video(形状为 (num_videos,) 的 torch.LongTensor,可选) — 每个视频包含的帧数。只要传入了 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 时),其包含的元素取决于配置(Gemma4Config)和输入。

Gemma4Model 的 forward 方法会重写 __call__ 特殊方法。

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

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

    如果使用了 past_key_values,则仅输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

  • image_hidden_states (torch.Tensor,可选) — 一个尺寸为 (batch_size, num_images, sequence_length, hidden_size) 的 torch.Tensor。 由视觉编码器生成的模型 image_hidden_states,并在投影最后一个隐藏状态之后得到。

  • audio_hidden_states (torch.Tensor, 可选) — 大小为 (batch_size, num_images, sequence_length, hidden_size) 的 torch.Tensor。 由音频编码器生成并在投影最后一个隐藏状态后得到的模型的 audio_hidden_states。

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

Gemma4ForConditionalGeneration

类 transformers.Gemma4ForConditionalGeneration

< >

( config: Gemma4Config )

参数

  • config (Gemma4Config) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_values_videos: typing.Optional[torch.Tensor] = Noneinput_features: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneinput_features_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneimage_position_ids: typing.Optional[torch.LongTensor] = Nonevideo_position_ids: typing.Optional[torch.LongTensor] = Nonenum_frames_per_video: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Nonemm_token_type_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0per_layer_inputs: typing.Optional[torch.Tensor] = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Gemma4CausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 Gemma4ImageProcessor 获取像素值。有关详细信息,请参阅 Gemma4ImageProcessor.call()(Gemma4Processor 使用 Gemma4ImageProcessor 处理图像)。
  • pixel_values_videos (torch.Tensor,形状为 (batch_size, num_frames, num_channels, frame_size, frame_size),可选) — 对应输入视频的张量。可以使用 Gemma4VideoProcessor 获取视频的像素值。有关详细信息,请参阅 Gemma4VideoProcessor.call()(Gemma4Processor 使用 Gemma4VideoProcessor 来处理视频)。
  • input_features (torch.Tensor,形状为 (batch_size, sequence_length, feature_dim),可选) — 与输入音频特征对应的张量。可以使用 Gemma4AudioFeatureExtractor 获取音频特征。有关详细信息,请参阅 Gemma4AudioFeatureExtractor.call()(Gemma4Processor 使用 Gemma4AudioFeatureExtractor 来处理音频)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • input_features_mask (torch.Tensor,形状为 (num_images, seq_length)) — 输入音频的注意力掩码。
  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • image_position_ids(形状为 (batch_size, max_patches, 2) 的 torch.LongTensor,可选)— 来自图像处理器(image processor)的 2D patch 位置坐标,其中 (-1, -1) 表示填充(padding)。 该参数会传递给视觉编码器,用于计算位置嵌入(positional embedding)。
  • video_position_ids(形状为 (total_num_frames, max_patches, 2) 的 torch.LongTensor,可选) — 来自视频处理器的 2D patch 位置坐标,其中 (-1, -1) 表示填充。 该参数会传递给视觉编码器,用于计算位置嵌入。
  • num_frames_per_video(形状为 (num_videos,) 的 torch.LongTensor,可选) — 每个视频包含的帧数。只要传入了 pixel_values_videos,就必须提供此参数,因为所有视频的帧都沿单一轴拼接在一起。
  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • mm_token_type_ids (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 输入序列中匹配每种模态的 token 索引。例如文本 (0)、图像 (1)、视频 (2)。 可通过 AutoProcessor 获取多模态 token 类型 id。详情请参见 ProcessorMixin.call()。
  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • logits_to_keep (Union[int, torch.Tensor], 可选,默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。
  • 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 时),其包含的元素取决于配置(Gemma4Config)和输入。

Gemma4ForConditionalGeneration 的 forward 方法重写了 __call__ 特殊方法。

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

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits(形状为 (batch_size, sequence_length, config.text_config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple[torch.Tensor],可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

  • image_hidden_states (torch.Tensor,可选) — 大小为 (batch_size, num_images, sequence_length, hidden_size) 的 torch.Tensor。 由视觉编码器生成的模型 image_hidden_states,即对最后一个隐藏状态进行投影后的结果。

  • audio_hidden_states (torch.Tensor, 可选) — 大小为 (batch_size, num_images, sequence_length, hidden_size) 的 torch.Tensor。 由音频编码器生成并在投影最后一个隐藏状态后得到的模型的 audio_hidden_states。

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

示例:

>>> from PIL import Image
>>> from transformers import AutoProcessor, Gemma4ForConditionalGeneration

>>> model = Gemma4ForConditionalGeneration.from_pretrained("google/gemma-4-e2b-it")
>>> processor = AutoProcessor.from_pretrained("google/gemma-4-e2b-it")

>>> 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]
Update on GitHub