# GLM-5.3-Flash

## 概述

**GLM-5.3-Flash** 模型使用此类。transformers 中的实现不包含 MTP 层。

### GLM-5.3-Flash

GLM-5.3-Flash 是 GLM-5 系列中首个**原生多模态模型**。该模型总参数量为 320B，激活参数仅为 18B，在各项基准测试和实际工作负载中均优于 GLM-5.2，且成本仅为后者的十分之一，同时在编码和智能体基准测试中已接近 Claude Opus 4.8 的水平。

GLM-5.3-Flash 基于全新训练的基座模型，其架构与训练方案围绕能力与效率进行了重新设计。在 GLM 系列中，我们首次引入了结合稀疏注意力与线性注意力的混合架构，在保留精确长上下文能力的同时，大幅降低了长上下文的推理成本。该模型还采用了 Manifold-Constrained Hyper-Connections (mHC)，以进一步提升扩展效率。结合我们最新的 **30T-token** 多模态预训练语料库，这些改进使 GLM-5.3-Flash 能够以更少的计算资源提供更强的智能表现。

![bench_53](https://raw.githubusercontent.com/zai-org/GLM-5/refs/heads/main/resources/bench_53.png)

## 备注

- 在批量生成时使用左侧填充。请参阅 [填充侧](../llm_tutorial#padding-side)。

## Glm5NextConfig[[transformers.Glm5NextConfig]]

#### transformers.Glm5NextConfig[[transformers.Glm5NextConfig]]

```python
transformers.Glm5NextConfig(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: dict | transformers.configuration_utils.PreTrainedConfig | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, image_token_id: int = 154854, video_token_id: int = 154855, image_start_token_id: int = 154830, image_end_token_id: int = 154831, video_start_token_id: int = 154832, video_end_token_id: int = 154833, tie_word_embeddings: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/configuration_glm5_next.py#L268)

**参数：**

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

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

image_token_id (`int`, *可选*, 默认值为 154854) : 用于编码图像提示的图像标记索引。

video_token_id (`int`, *可选*, 默认为 154855) : 用于编码视频提示的视频标记索引。

image_start_token_id (`int`, *可选*, 默认为 154830) : 用于编码图像起始位置的图像起始标记索引。

image_end_token_id (`int`, *可选*，默认为 154831)：用于编码图像结束位置的图像结束标记索引。

video_start_token_id (`int`, *可选*, 默认为 154832) : 用于编码视频起始的视频起始标记索引。

video_end_token_id (`int`, *可选*, 默认为 154833) : 用于编码视频结束的视频结束标记索引。

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

这是用于存储 Glm5NextModel 配置的类。它根据指定的参数实例化 Glm5 Next 模型，并定义模型架构。使用默认值实例化配置将生成与 [zai-org/GLM-5.3-Flash](https://huggingface.co/zai-org/GLM-5.3-Flash) 类似的配置。

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

```python
>>> from transformers import Glm5NextConfig

>>> # Initializing a GLM-5.3-Flash style configuration
>>> configuration = Glm5NextConfig()
```

## Glm5NextTextConfig[[transformers.Glm5NextTextConfig]]

#### transformers.Glm5NextTextConfig[[transformers.Glm5NextTextConfig]]

```python
transformers.Glm5NextTextConfig(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 = 154880, hidden_size: int = 4096, intermediate_size: int = 12288, moe_intermediate_size: int = 2048, num_hidden_layers: int = 45, num_attention_heads: int = 64, num_key_value_heads: int = 64, n_shared_experts: int = 1, n_routed_experts: int = 288, output_router_logits: bool = False, routed_scaling_factor: float = 2.5, kv_lora_rank: int = 512, q_lora_rank: int = 1536, qk_rope_head_dim: int = 0, v_head_dim: int = 256, qk_nope_head_dim: int = 256, n_group: int = 1, topk_group: int = 1, num_experts_per_tok: int = 8, norm_topk_prob: bool = True, hidden_act: str = 'silu', max_position_embeddings: int = 1048576, initializer_range: float = 0.02, rms_norm_eps: float = 1e-05, use_cache: bool = True, pad_token_id: int | None = 154820, bos_token_id: int | None = None, eos_token_id: int | list[int] | None = None, tie_word_embeddings: bool = False, mlp_layer_types: list[str] | None = None, attention_bias: bool = False, attention_dropout: float | int = 0.0, index_topk: int = 2048, index_head_dim: int = 128, index_n_heads: int = 32, head_dim: int = 0, layer_types: list[str] | None = None, indexer_types: list[str] | None = None, swiglu_limit: float = 10.0, linear_head_dim: int = 128, linear_num_heads: int = 64, linear_conv_kernel_dim: int = 4, linear_lower_bound: float | None = -5.0, hc_mult: int = 4, hc_eps: float = 1e-06, hc_sinkhorn_iters: int = 20, router_aux_loss_coef: float = 0.001, index_kpool: int = 16, index_kpool_always_select_tail: bool = True)
```

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

**参数：**

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

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

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

moe_intermediate_size (`int`，*可选*，默认为 `2048`)：路由专家 MLP 的中间层大小。

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

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

num_key_value_heads (`int`, *可选*，默认为 `64`)：这是用于实现 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`。

n_shared_experts (`int`，*可选*，默认为 `1`)：共享专家的数量。

n_routed_experts (`int`，*可选*，默认为 `288`)：路由专家的数量。

output_router_logits (`bool`，*可选*，默认为 `False`)：是否由模型返回路由器 logits。启用此选项后，模型还将输出辅助损失，包括负载均衡损失和路由器 z-loss。

routed_scaling_factor (`float`，*可选*，默认为 `2.5`)：缩放因子或路由专家。

kv_lora_rank (`int`, *可选*, 默认为 `512`) : 用于键和值投影的 LoRA 矩阵的秩。

q_lora_rank (`int`，*可选*，默认为 `1536`)：查询投影的 LoRA 矩阵秩。

qk_rope_head_dim (`int`，*可选*，默认为 `0`)：使用旋转位置嵌入的查询/键头的维度。

v_head_dim (`int`，*可选*，默认为 `256`)：值头的维度。

qk_nope_head_dim (`int`，*可选*，默认为 `256`)：未使用旋转位置嵌入的查询/键头的维度。

n_group (`int`，*可选*，默认为 1)：路由专家组的数量。

topk_group (`int`, *可选*, 默认为 `1`) : 每个 token 选中的组数（对于每个 token，确保所选专家仅位于 `topk_group` 个组内）。

num_experts_per_tok (`int`，*可选*，默认为 `8`)：每个 token 路由到的专家数量。这是 token 选择路由的 top-k 值。

norm_topk_prob (`bool`, *可选*, 默认为 `True`) : 是否对路由专家的权重进行归一化。

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

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

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

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

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

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

bos_token_id (`int`, *可选*) : 词表中用于表示流开始的 Token id。

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

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

mlp_layer_types (`list[str]`, *可选*) : 逐层前馈调度。取值为 `"dense"` 或 `"sparse"`。

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

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

index_topk (`int`, *可选*，默认为 2048)：DSA 索引器选择的稀疏注意力位置数量。

index_head_dim (`int`，*可选*，默认为 128)：DSA 索引器投影头维度。

index_n_heads (`int`，*可选*，默认为 32)：DSA 索引器头数。

head_dim (`int`, *可选*, 默认为 `0`) : 注意力头维度。如果为 None，则默认为 hidden_size // num_attention_heads

layer_types (`list[str]`, *可选*) : 每层注意力缓存调度。KDA 层的值为 `"linear_attention"`，MLA (DSA) 层的值为 `"indexed_attention"`。

indexer_types (`list[str]`, *可选*) : 每层 DSA 索引器模式。取值为 `"full"`（运行索引器）或 `"shared"`（复用上一层完整层的 top-k 选择）。

swiglu_limit (`float`, *可选*，默认为 10.0)：应用于 SwiGLU 门控/上投影的截断限制。

linear_head_dim (`int`，*可选*，默认为 128)：线性注意力中每个头的维度。

linear_num_heads (`int`，*可选*，默认为 64)：线性注意力层中使用的头数。

linear_conv_kernel_dim (`int`，*可选*，默认为 4)：线性注意力层中使用的卷积的核大小。

linear_lower_bound (`float`, *可选*，默认为 -5.0)：遗忘门是否对衰减应用下界。

hc_mult (`int`，*可选*，默认为 4)：MHC 残差流的数量。

hc_eps (`float`, *可选*, 默认值为 1e-6) : MHC Sinkhorn 归一化所使用的数值下限。

hc_sinkhorn_iters (`int`，*可选*，默认为 20)：MHC 路由所使用的 Sinkhorn 迭代次数。

router_aux_loss_coef (`float`, *可选*，默认为 `0.001`)：辅助负载均衡损失系数。用于惩罚 MoE 模型中专家路由的不均衡。

index_kpool (`int`，*可选*，默认为 16)：DSA 索引器所选压缩 token 组的池大小。

index_kpool_always_select_tail (`bool`, *可选*, 默认为 `True`) : 是否始终将不完整的 KPool 尾部包含在稀疏注意力中。

这是用于存储 Glm5NextModel 配置的类。它根据指定的参数实例化 Glm5 Next 模型，并定义模型架构。使用默认值实例化配置将生成与 [zai-org/GLM-5.3-Flash](https://huggingface.co/zai-org/GLM-5.3-Flash) 类似的配置。

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

## Glm5NextVisionConfig[[transformers.Glm5NextVisionConfig]]

#### transformers.Glm5NextVisionConfig[[transformers.Glm5NextVisionConfig]]

```python
transformers.Glm5NextVisionConfig(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, depth: int = 24, hidden_size: int = 1024, hidden_act: str = 'silu', attention_bias: bool = True, attention_dropout: float | int = 0.0, num_heads: int = 16, in_channels: int = 3, image_size: int | list[int] | tuple[int, int] = 336, patch_size: int | list[int] | tuple[int, int] = 14, rms_norm_eps: float = 1e-05, spatial_merge_size: int = 2, temporal_patch_size: int | list[int] | tuple[int, int] = 2, out_hidden_size: int = 1536, intermediate_size: int = 4096, initializer_range: float = 0.02, rope_parameters: dict | None = None, projection_intermediate_size: int = 10240, swiglu_limit: float = 10.0)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/configuration_glm5_next.py#L231)

**参数：**

depth (`int`，*可选*，默认为 `24`)：视觉编码器中 Transformer 层的数量。

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

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

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

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

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

in_channels (`int`，*可选*，默认为 `3`)：输入通道数。

image_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `336`)：每张图片的尺寸（分辨率）。

patch_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `14`)：每个 patch 的大小（分辨率）。

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

spatial_merge_size (`int`, *可选*，默认为 `2`)：用于通过合并相邻 patch 来减少视觉 token 数量的空间合并窗口大小。

temporal_patch_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `2`)：用于视频输入的 3D 补丁嵌入中的时间补丁大小。

out_hidden_size (`int`，*可选*，默认为 1536)：视觉模型的输出隐藏层大小。

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

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

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

projection_intermediate_size (`int`, *可选*，默认为 10240)：视觉 patch merger 的 projection_intermediate_size 大小。

swiglu_limit (`float`, *可选*，默认为 10.0) : 应用于视觉 SwiGLU 门控/上投影的截断限制。

这是用于存储 Glm5NextModel 配置的类。它根据指定的参数实例化 Glm5 Next 模型，并定义模型架构。使用默认值实例化配置将生成与 [zai-org/GLM-5.3-Flash](https://huggingface.co/zai-org/GLM-5.3-Flash) 类似的配置。

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

## Glm5NextPreTrainedModel[[transformers.Glm5NextPreTrainedModel]]

#### transformers.Glm5NextPreTrainedModel[[transformers.Glm5NextPreTrainedModel]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/modeling_glm5_next.py#L1353)

**参数：**

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.Glm5NextPreTrainedModel.forward]]

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

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

## Glm5NextTextModel[[transformers.Glm5NextTextModel]]

#### transformers.Glm5NextTextModel[[transformers.Glm5NextTextModel]]

```python
transformers.Glm5NextTextModel(config: Glm5NextTextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/modeling_glm5_next.py#L1426)

**参数：**

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

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

该模型继承自 [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.Glm5NextTextModel.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/modeling_glm5_next.py#L1445)

**参数：**

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)

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

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

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

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

`MoeModelOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Glm5NextConfig](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextConfig)）和输入。

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

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，当传入 `output_router_probs=True` 且 `config.add_router_probs=True`，或当 `config.output_router_probs=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, sequence_length, num_experts)`。

  由 MoE 路由器计算的原始路由器 logits（softmax 之后），这些术语用于计算混合专家模型的辅助损失。

## Glm5NextModel
## Glm5NextVisionModel[[transformers.Glm5NextVisionModel]]

#### transformers.Glm5NextVisionModel[[transformers.Glm5NextVisionModel]]

```python
transformers.Glm5NextVisionModel(config: Glm5NextVisionConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/modeling_glm5_next.py#L1799)

**参数：**

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

未添加任何特定头部的裸 Glm5 Next 模型，直接输出原始隐藏状态。

该模型继承自 [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.Glm5NextVisionModel.forward]]

```python
forward(hidden_states: Tensor, grid_thw: Tensor, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/modeling_glm5_next.py#L1833)

**参数：**

hidden_states (`torch.Tensor`，形状为 `(seq_len, hidden_size)`)：模型的最终隐藏状态。

grid_thw (`torch.Tensor`，形状为 `(num_images_or_videos, 3)`)：LLM 中每张图片的特征形状的时间、高度和宽度。

**返回：** `torch.Tensor`

hidden_states.

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

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

#### transformers.Glm5NextModel[[transformers.Glm5NextModel]]

```python
transformers.Glm5NextModel(config: Glm5NextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/modeling_glm5_next.py#L1881)

**参数：**

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

未添加任何特定头部的裸 Glm5 Next 模型，直接输出原始隐藏状态。

该模型继承自 [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.Glm5NextModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, pixel_values: typing.Optional[torch.Tensor] = None, pixel_values_videos: typing.Optional[torch.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, video_grid_thw: typing.Optional[torch.LongTensor] = 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/glm5_next/modeling_glm5_next.py#L1988)

**参数：**

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)

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

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

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

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

pixel_values_videos (`torch.Tensor`，形状为 `(batch_size, num_frames, num_channels, frame_size, frame_size)`，*可选*)：与输入视频对应的张量。可以使用 [Glm5NextVideoProcessor](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextVideoProcessor) 获取视频的像素值。有关详细信息，请参阅 [Glm5NextVideoProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2VideoProcessor.__call__)（[Glm5NextProcessor](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextProcessor) 使用 [Glm5NextVideoProcessor](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextVideoProcessor) 来处理视频）。

image_grid_thw (`torch.LongTensor`，形状为 `(num_images, 3)`，*可选*)：LLM 中每张图片特征形状的时间、高度和宽度。

video_grid_thw (`torch.LongTensor`，形状为 `(num_videos, 3)`，*可选*)：LLM 中每个视频的特征形状的时间、高度和宽度。

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

**返回：** [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`），其包含的元素取决于配置（[Glm5NextConfig](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextConfig)）和输入。

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

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

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

## Glm5NextForConditionalGeneration[[transformers.Glm5NextForConditionalGeneration]]

#### transformers.Glm5NextForConditionalGeneration[[transformers.Glm5NextForConditionalGeneration]]

```python
transformers.Glm5NextForConditionalGeneration(config: Glm5NextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/modeling_glm5_next.py#L2135)

**参数：**

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

Glm5 Next 模型用于基于其他模态（例如图像-文本到文本生成）的 token 生成。

该模型继承自 [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.Glm5NextForConditionalGeneration.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/modeling_glm5_next.py#L2183)

**参数：**

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)

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

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

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算掩码语言建模损失的标签。索引值应在 `[0, ..., config.vocab_size]` 范围内，或为 -100（参见 `input_ids` 的文档字符串）。索引值设为 `-100` 的 token 将被忽略（即被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。

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

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

pixel_values_videos (`torch.Tensor`，形状为 `(batch_size, num_frames, num_channels, frame_size, frame_size)`，*可选*)：与输入视频对应的张量。可以使用 [Glm5NextVideoProcessor](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextVideoProcessor) 获取视频的像素值。有关详细信息，请参阅 [Glm5NextVideoProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2VideoProcessor.__call__)（[Glm5NextProcessor](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextProcessor) 使用 [Glm5NextVideoProcessor](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextVideoProcessor) 来处理视频）。

image_grid_thw (`torch.LongTensor`，形状为 `(num_images, 3)`，*可选*)：LLM 中每张图片特征形状的时间、高度和宽度。

video_grid_thw (`torch.LongTensor`，形状为 `(num_videos, 3)`，*可选*)：LLM 中每个视频的特征形状的时间、高度和宽度。

output_router_logits (`bool`, *可选*) : 是否返回所有路由器的 logits。它们对于计算路由器损失很有用，在推理期间不应返回。

mm_token_type_ids (`torch.IntTensor`，形状为 `(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__)。

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

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

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

`MoeCausalLMOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Glm5NextConfig](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextConfig)）和输入。

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

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **aux_loss** (`torch.Tensor`，*可选*，当传入 `output_router_logits=True` 或 `config.output_router_logits=True`，且模型使用负载均衡损失训练其路由器时返回) -- 稀疏模块的负载均衡辅助损失。使用路由器偏差来平衡其专家的模型（DeepSeek-V3 及由其衍生的架构）在此处返回 `None`，但仍会返回 `router_logits`。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，在传入 `output_router_logits=True` 或 `config.output_router_logits=True` 时返回) -- 一个 `torch.Tensor` 元组（每个稀疏层对应一个），形状为 `(batch_size * sequence_length, num_experts)`。

  由 MoE 路由器计算的原始路由器 logits。可用于计算负载均衡损失，或检查 token 如何被分发到各个专家。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

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

示例：

```python
>>> from transformers import AutoProcessor, Glm5NextForConditionalGeneration
>>> import torch

>>> model = Glm5NextForConditionalGeneration.from_pretrained("zai-org/GLM-5.3-Flash")
>>> processor = AutoProcessor.from_pretrained("zai-org/GLM-5.3-Flash")

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {"type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Describe the image."},
...         ],
...     }
... ]
>>> inputs = processor.apply_chat_template(
...     messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt"
... )
>>> inputs = {k: v.to(model.device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()}
>>> generated_ids = model.generate(**inputs, max_new_tokens=64)
```

## Glm5NextProcessor[[transformers.Glm5NextProcessor]]

#### transformers.Glm5NextProcessor[[transformers.Glm5NextProcessor]]

```python
transformers.Glm5NextProcessor(image_processor = None, tokenizer = None, video_processor = None, chat_template = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/processing_glm5_next.py#L43)

**参数：**

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

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

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

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

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

[Glm5NextProcessor](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextProcessor) 提供了 [Glm5NextImageProcessor](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextImageProcessor)、`tokenizer_class` 和 [Glm5NextVideoProcessor](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextVideoProcessor) 的所有功能。有关更多信息，请参阅 [~Glm5NextImageProcessor](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextImageProcessor)、`~tokenizer_class` 和 [~Glm5NextVideoProcessor](/docs/transformers/main/zh/model_doc/glm5_next#transformers.Glm5NextVideoProcessor)。

#### post_process_image_text_to_text[[transformers.Glm5NextProcessor.post_process_image_text_to_text]]

```python
post_process_image_text_to_text(generated_outputs, skip_special_tokens = True, clean_up_tokenization_spaces = False, **kwargs)
```

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

**参数：**

generated_outputs (`torch.Tensor` 或 `np.ndarray`)：模型 `generate` 函数的输出。预期输出是一个形状为 `(batch_size, sequence_length)` 或 `(sequence_length,)` 的张量。

skip_special_tokens (`bool`，*可选*，默认为 `True`)：是否从输出中移除特殊标记。该参数会传递给分词器的 `batch_decode` 方法。

clean_up_tokenization_spaces (`bool`，*可选*，默认为 `False`)：是否清理分词空格。该参数会传递给分词器的 `batch_decode` 方法。

- ****kwargs** : 传递给分词器 `batch_decode method` 的额外参数。

**返回：** `list[str]`

解码后的文本。

对模型的输出进行后处理以解码文本。

## Glm5NextImageProcessor[[transformers.Glm5NextImageProcessor]]

#### transformers.Glm5NextImageProcessor[[transformers.Glm5NextImageProcessor]]

```python
transformers.Glm5NextImageProcessor(**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/image_processing_glm5_next.py#L124)

**参数：**

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*，默认为 `{'longest_edge' : 1}`)：描述输入到模型的最大维度。

default_to_square (`bool`, *kwargs*, *可选*，默认为 `False`) : 当 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*，*可选*，默认为 `True`)：是否对图像进行归一化。

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

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.26862954, 0.26130258, 0.27577711]`) : 用于归一化的图像标准差。仅当 `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*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。 --

构建一个 Glm5NextImageProcessor 图像处理器。

disable_grouping (`bool`, *kwargs*, *可选*)：是否禁用按大小对图像进行分组，以便单独处理图像而不是批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详情见此处：https://github.com/huggingface/transformers/pull/38157 image_seq_length (`int`, *kwargs*, *可选*)：输入中每张图像要使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器的属性。

#### get_number_of_image_patches[[transformers.Glm5NextImageProcessor.get_number_of_image_patches]]

```python
get_number_of_image_patches(height: int, width: int, images_kwargs: dict | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/image_processing_glm5_next.py#L286)

**参数：**

height (`int`) : 输入图像的高度。

width (`int`) : 输入图像的宽度。

images_kwargs (`dict`, *可选*) : 用于覆盖图像处理器默认值的任意关键字参数。

**返回：** `int`

每张图像中的图像块数量。

一个实用工具，用于返回给定图像尺寸对应的图像块数量。

#### patchify[[transformers.Glm5NextImageProcessor.patchify]]

```python
patchify(images: torch.Tensor, patch_size: int, merge_size: int, temporal_patch_size: int)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/image_processing_glm5_next.py#L185)

将每张图片转换为形状为 (`seq_len`, `patch_dim`) 的扁平布局，以便我们可以拼接动态形状的像素。

#### preprocess[[transformers.Glm5NextImageProcessor.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.glm5_next.image_processing_glm5_next.Glm5NextImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/image_processing_glm5_next.py#L144)

**参数：**

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*, *可选*，默认为 14)：视觉编码器的空间补丁大小。

temporal_patch_size (`int`, *kwargs*, *可选*，默认为 2)：视觉编码器的时间补丁大小。

merge_size (`int`, *kwargs*, *可选*，默认为 2)：视觉编码器到 LLM 编码器的合并大小。

patch_expand_factor (`int`, *kwargs*, *可选*，默认为 1)：视觉编码器到 LLM 编码器的 patch_expand_factor。

min_image_tokens (`int`, *kwargs*) : 每张图像的最小 token 数。

max_image_tokens (`int`, *kwargs*) : 每张图片的最大 token 数。

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

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

#### resize[[transformers.Glm5NextImageProcessor.resize]]

```python
resize(images: torch.Tensor, resample: PILImageResampling | tvF.InterpolationMode | int | None, factor: int, temporal_factor: int, min_image_tokens: int, max_image_tokens: int, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/image_processing_glm5_next.py#L148)

根据输入图像的宽高比动态调整大小。

## Glm5NextImageProcessorPil[[transformers.Glm5NextImageProcessorPil]]

#### transformers.Glm5NextImageProcessorPil[[transformers.Glm5NextImageProcessorPil]]

```python
transformers.Glm5NextImageProcessorPil(**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/image_processing_pil_glm5_next.py#L122)

**参数：**

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*，默认为 `{'longest_edge' : 1}`)：描述输入到模型的最大维度。

default_to_square (`bool`, *kwargs*, *可选*，默认为 `False`) : 当 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*，*可选*，默认为 `True`)：是否对图像进行归一化。

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

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.26862954, 0.26130258, 0.27577711]`) : 用于归一化的图像标准差。仅当 `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*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。 --

构建一个 Glm5NextImageProcessor 图像处理器。

disable_grouping (`bool`, *kwargs*, *可选*)：是否禁用按大小对图像进行分组，以便单独处理图像而不是批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详情见此处：https://github.com/huggingface/transformers/pull/38157 image_seq_length (`int`, *kwargs*, *可选*)：输入中每张图像要使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器的属性。

#### get_number_of_image_patches[[transformers.Glm5NextImageProcessorPil.get_number_of_image_patches]]

```python
get_number_of_image_patches(height: int, width: int, images_kwargs: dict | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/image_processing_pil_glm5_next.py#L286)

**参数：**

height (`int`) : 输入图像的高度。

width (`int`) : 输入图像的宽度。

images_kwargs (`dict`, *可选*) : 用于覆盖图像处理器默认值的任意关键字参数。

**返回：** `int`

每张图像中的图像块数量。

一个实用工具，用于返回给定图像尺寸对应的图像块数量。

#### patchify[[transformers.Glm5NextImageProcessorPil.patchify]]

```python
patchify(image: ndarray, patch_size: int, merge_size: int, temporal_patch_size: int)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/image_processing_pil_glm5_next.py#L187)

将每张图片转换为形状为 (`seq_len`, `patch_dim`) 的扁平布局，以便我们可以拼接动态形状的像素。

#### preprocess[[transformers.Glm5NextImageProcessorPil.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.glm5_next.image_processing_pil_glm5_next.Glm5NextImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/image_processing_pil_glm5_next.py#L142)

**参数：**

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*, *可选*，默认为 14)：视觉编码器的空间补丁大小。

temporal_patch_size (`int`, *kwargs*, *可选*，默认为 2)：视觉编码器的时间补丁大小。

merge_size (`int`, *kwargs*, *可选*，默认为 2)：视觉编码器到 LLM 编码器的合并大小。

patch_expand_factor (`int`, *kwargs*, *可选*，默认为 1)：视觉编码器到 LLM 编码器的 patch_expand_factor。

min_image_tokens (`int`, *kwargs*) : 每张图像的最小 token 数。

max_image_tokens (`int`, *kwargs*) : 每张图片的最大 token 数。

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

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

#### resize[[transformers.Glm5NextImageProcessorPil.resize]]

```python
resize(image: ndarray, resample: PILImageResampling | int | None, factor: int, temporal_factor: int, min_image_tokens: int, max_image_tokens: int, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/image_processing_pil_glm5_next.py#L146)

根据输入图像的宽高比动态调整大小。

## Glm5NextVideoProcessor[[transformers.Glm5NextVideoProcessor]]

#### transformers.Glm5NextVideoProcessor[[transformers.Glm5NextVideoProcessor]]

```python
transformers.Glm5NextVideoProcessor(**kwargs: *<class 'transformers.models.glm5_next.video_processing_glm5_next.Glm5NextVideoProcessorInitKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/video_processing_glm5_next.py#L139)

**参数：**

- ****kwargs** (`Glm5NextVideoProcessorInitKwargs`, *可选*) : 每种模态（文本、图像、视频、音频）的额外处理选项。模型特定参数已在上方列出；有关支持的完整参数列表，请参阅 TypedDict 类。

构建一个 Glm5NextVideoProcessor 视频处理器。

#### get_num_of_video_patches[[transformers.Glm5NextVideoProcessor.get_num_of_video_patches]]

```python
get_num_of_video_patches(num_frames: int, height: int, width: int, videos_kwargs = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/video_processing_glm5_next.py#L277)

**参数：**

num_frames (`int`) : 输入视频中的帧数。

height (`int`) : 输入视频的高度。

width (`int`) : 输入视频的宽度。

videos_kwargs (`dict`, *可选*) : 用于覆盖视频处理器默认值的任意关键字参数。

**返回：** `int`

每个视频的视频块数量。

一个实用工具，用于返回给定视频尺寸对应的视频块数量。

#### patchify[[transformers.Glm5NextVideoProcessor.patchify]]

```python
patchify(videos: torch.Tensor, patch_size: int, merge_size: int, temporal_patch_size: int)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/video_processing_glm5_next.py#L314)

将每个视频转换为形状为 (`seq_len`, `patch_dim`) 的扁平布局，以便我们可以拼接动态形状的像素。

#### resize[[transformers.Glm5NextVideoProcessor.resize]]

```python
resize(videos: torch.Tensor, resample: PILImageResampling | tvF.InterpolationMode | int | None, factor: int, temporal_factor: int, min_image_tokens: int, max_image_tokens: int, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm5_next/video_processing_glm5_next.py#L238)

根据输入视频的宽高比动态调整大小。

#### sample_frames[[transformers.Glm5NextVideoProcessor.sample_frames]]

```python
sample_frames(metadata: VideoMetadata, fps: int | float | None = None, **kwargs)
```

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

**参数：**

metadata (`VideoMetadata`)：视频的元数据，包含总时长、帧率（fps）和总帧数等信息。

fps (`int` 或 `float`，*可选*)：每秒采样的目标帧数。默认为 `self.fps`。

**返回：** `np.ndarray`

用于采样视频帧的索引。

