# HunYuanVL

## 概述

HunYuanVL 是一种用于图像文本理解与生成的视觉语言模型，提出于 [HunyuanOCR Technical Report ](https://huggingface.co/papers/2511.19575)。Transformers 中开源的 `hunyuan_vl` 集成是一个仅包含稠密模型的图像文本变体，专为 [`tencent/HunyuanOCR`](https://huggingface.co/tencent/HunyuanOCR) 等 OCR 和文档理解类工作负载而设计。

该论文的摘要如下：

*本文介绍了 HunyuanOCR，这是一款商用级、开源且轻量级（10 亿参数）的视觉语言模型（VLM），专为 OCR 任务设计。其架构由原生视觉 Transformer（ViT）和一个轻量级 LLM 组成，两者通过 MLP 适配器连接。HunyuanOCR 展现出卓越的性能，超越了商用 API、传统流水线以及更大的模型（例如 Qwen3-VL-4B）。具体而言，它在感知任务（文本检测、解析）上超越了当前的公开解决方案，并在语义任务（信息抽取、文本图像翻译）上表现出色，在 ICDAR 2025 DIMT 挑战赛（小模型赛道）中荣获第一名。此外，在参数量少于 30 亿的 VLM 中，它在 OCRBench 上取得了最先进的（SOTA）结果。*

*HunyuanOCR 在三个关键方面取得了突破：1) 统一通用性与效率：我们在轻量级框架中实现了对核心能力的全面支持，包括定位、解析、信息抽取（IE）、视觉问答（VQA）和翻译。这解决了狭窄的“OCR 专家模型”和低效的“通用 VLM”的局限性。2) 简化的端到端架构：采用纯端到端范式，消除了对预处理模块（例如布局分析）的依赖。这从根本上解决了传统流水线中常见的错误传播问题，并简化了系统部署。3) 数据驱动与强化学习策略：我们确认了高质量数据的关键作用，并在业内首次证明，强化学习（RL）策略在 OCR 任务中能带来显著的性能提升。*

*HunyuanOCR 已在 HuggingFace 上正式开源。我们还提供基于 vLLM 的高性能部署方案，使其生产级效率处于第一梯队。我们希望该模型能够推动前沿研究，并为工业应用奠定坚实基础。*

## 推荐的检查点

- 用于 OCR 和文档提取工作负载的 [tencent/HunyuanOCR](https://huggingface.co/tencent/HunyuanOCR)。

## 使用技巧

此 Transformers 集成有意公开了公共 OCR 风格检查点所使用的图像-文本路径。

- 支持：仅密集文本骨干网络、图文提示、OCR/文档理解风格的生成。
- 此开源版本不支持：视频输入和运行时 MoE 执行路径。
- 兼容性说明：为了能够加载现有的检查点，仍然接受一些旧的腾讯导出配置字段，但这些字段并不意味着开源实现启用了额外的运行时功能。
- 对于当前已验证的 OCR 路径，`attn_implementation="eager"` 是推荐的起点。
- 加载当前公开的 OCR 检查点时，建议使用 `backend="pil"`。
- 在对变长提示词进行批处理时，如果需要从处理器获取张量输出，请传入 `padding=True`。

## 用法

```python
import torch
from transformers import AutoModelForImageTextToText, AutoProcessor

model_name_or_path = "tencent/HunyuanOCR"
processor = AutoProcessor.from_pretrained(model_name_or_path, backend="pil")
model = AutoModelForImageTextToText.from_pretrained(
    model_name_or_path,
    device_map="auto",
)

messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"},
            {"type": "text", "text": "What animal is on the candy?"}
        ]
    },
]
inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_tensors="pt",
).to(model.device)

generated_ids = model.generate(**inputs, max_new_tokens=1024)

generated_ids_trimmed = generated_ids[0][len(inputs["input_ids"][0]) :]
output = processor.decode(generated_ids_trimmed, skip_special_tokens=True)
print(output)
```

## HunYuanVLProcessor[[transformers.HunYuanVLProcessor]]

#### transformers.HunYuanVLProcessor[[transformers.HunYuanVLProcessor]]

```python
transformers.HunYuanVLProcessor(image_processor = None, tokenizer = None, chat_template = None, cat_extra_token: bool = True, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/processing_hunyuan_vl.py#L36)

**参数：**

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

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

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

cat_extra_token (`bool`, *可选*, 默认为 `True`) : 在计算扩展后的图像标记序列时，是否考虑 HunYuanVL 在每个图像片段周围插入的两个额外标记。

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

[HunYuanVLProcessor](/docs/transformers/main/zh/model_doc/hunyuan_vl#transformers.HunYuanVLProcessor) 提供了 [HunYuanVLImageProcessor](/docs/transformers/main/zh/model_doc/hunyuan_vl#transformers.HunYuanVLImageProcessor) 和 [Qwen2Tokenizer](/docs/transformers/main/zh/model_doc/qwen2#transformers.Qwen2Tokenizer) 的所有功能。有关更多信息，请参阅 [~HunYuanVLImageProcessor](/docs/transformers/main/zh/model_doc/hunyuan_vl#transformers.HunYuanVLImageProcessor) 和 [~Qwen2Tokenizer](/docs/transformers/main/zh/model_doc/qwen2#transformers.Qwen2Tokenizer)。

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

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L659)

**参数：**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`, *可选*) : 要预处理的图像。期望输入单张图像或一批图像，其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间，请设置 `do_rescale=False`。

text (`Union[str, list[str], list[list[str]]]`，*可选*)：要编码的序列或序列批次。每个序列可以是字符串或字符串列表（预分词字符串）。如果传入预分词输入，请设置 `is_split_into_words=True` 以避免与批量输入产生歧义。

videos (`Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]`，*可选*)：要预处理的视频。期望输入单个视频或一批视频，其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间，请设置 `do_rescale=False`。

audio (`Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]]`，*可选*)：要准备处理的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。对于 NumPy 数组/PyTorch 张量，每个音频的形状应为 (C, T)，其中 C 是通道数，T 是音频的采样长度。

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

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

## HunYuanVLImageProcessor[[transformers.HunYuanVLImageProcessor]]

#### transformers.HunYuanVLImageProcessor[[transformers.HunYuanVLImageProcessor]]

```python
transformers.HunYuanVLImageProcessor(**kwargs: *<class 'transformers.models.hunyuan_vl.image_processing_hunyuan_vl.HunYuanVLImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py#L88)

**参数：**

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

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*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

min_pixels (`int`, *kwargs*, *可选*，默认为 `512 * 512`) : 用于调整图像大小的最小像素数。

max_pixels (`int`, *kwargs*, *可选*，默认为 `2048 * 2048`) : 用于调整图像尺寸的最大像素数。

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

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

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

构建一个 HunYuanVLImageProcessor 图像处理器。

#### get_number_of_image_patches[[transformers.HunYuanVLImageProcessor.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/hunyuan_vl/image_processing_hunyuan_vl.py#L268)

**参数：**

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

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

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

**返回：** `tuple[int, int]`

每张图像中图像块的数量，以 `(height, width)` 网格形式表示。

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

注意：请勿删除此方法！vLLM 使用该方法在缺少图像输入的情况下推断 patch 和占位符的数量。

#### patchify[[transformers.HunYuanVLImageProcessor.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/hunyuan_vl/image_processing_hunyuan_vl.py#L176)

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

#### preprocess[[transformers.HunYuanVLImageProcessor.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.hunyuan_vl.image_processing_hunyuan_vl.HunYuanVLImageProcessorKwargs'>)
```

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

**参数：**

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

min_pixels (`int`, *kwargs*, *可选*，默认为 `512 * 512`) : 用于调整图像大小的最小像素数。

max_pixels (`int`, *kwargs*, *可选*，默认为 `2048 * 2048`) : 用于调整图像尺寸的最大像素数。

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

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

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

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

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

#### resize[[transformers.HunYuanVLImageProcessor.resize]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py#L147)

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

## HunYuanVLImageProcessorPil[[transformers.HunYuanVLImageProcessorPil]]

#### transformers.HunYuanVLImageProcessorPil[[transformers.HunYuanVLImageProcessorPil]]

```python
transformers.HunYuanVLImageProcessorPil(**kwargs: *<class 'transformers.models.hunyuan_vl.image_processing_pil_hunyuan_vl.HunYuanVLImageProcessorKwargs'>)
```

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

**参数：**

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

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*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

min_pixels (`int`, *kwargs*, *可选*，默认为 `512 * 512`) : 用于调整图像大小的最小像素数。

max_pixels (`int`, *kwargs*, *可选*，默认为 `2048 * 2048`) : 用于调整图像尺寸的最大像素数。

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

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

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

构建一个 HunYuanVLImageProcessor 图像处理器。

#### get_number_of_image_patches[[transformers.HunYuanVLImageProcessorPil.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/hunyuan_vl/image_processing_pil_hunyuan_vl.py#L263)

**参数：**

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

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

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

**返回：** `tuple[int, int]`

每张图像中图像块的数量，以 `(height, width)` 网格形式表示。

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

注意：请勿删除此方法！vLLM 使用该方法在缺少图像输入的情况下推断 patch 和占位符的数量。

#### patchify[[transformers.HunYuanVLImageProcessorPil.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/hunyuan_vl/image_processing_pil_hunyuan_vl.py#L167)

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

#### preprocess[[transformers.HunYuanVLImageProcessorPil.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.hunyuan_vl.image_processing_pil_hunyuan_vl.HunYuanVLImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/image_processing_pil_hunyuan_vl.py#L204)

**参数：**

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

min_pixels (`int`, *kwargs*, *可选*，默认为 `512 * 512`) : 用于调整图像大小的最小像素数。

max_pixels (`int`, *kwargs*, *可选*，默认为 `2048 * 2048`) : 用于调整图像尺寸的最大像素数。

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

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

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

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

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

#### resize[[transformers.HunYuanVLImageProcessorPil.resize]]

```python
resize(image: ndarray, size: SizeDict, resample: PILImageResampling | int | None, factor: int, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/image_processing_pil_hunyuan_vl.py#L138)

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

`HunYuanVLForConditionalGeneration` 是图文生成的主要公开入口。`HunYuanVLModel` 暴露了不带语言建模头部的多模态基础模型，而 `HunYuanVLTextModel` 则暴露了底层的文本骨干网络。

## HunYuanVLConfig[[transformers.HunYuanVLConfig]]

#### transformers.HunYuanVLConfig[[transformers.HunYuanVLConfig]]

```python
transformers.HunYuanVLConfig(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 = 120120, tie_word_embeddings: bool = True, im_start_id: int = 120118, im_end_id: int = 120119, im_newline_id: int = 120121)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/configuration_hunyuan_vl.py#L237)

**参数：**

text_config (`HunYuanVLTextConfig` 或 `dict`，*可选*)：文本主干的配置。当为 `None` 时，使用默认值。

vision_config (`HunYuanVLVisionConfig` 或 `dict`，*可选*)：视觉塔的配置文件。当为 `None` 时，使用默认值。

image_token_id (`int`，*可选*，默认为 `120120`)：用作输入图像占位符的图像 token 索引。

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

im_start_id (`int`, *可选*, 默认值为 120118) : 在多模态提示中标记图像片段起始位置的 Token ID。

im_end_id (`int`, *可选*, 默认值为 120119) : 在多模态提示中标记图像片段结束的 Token id。

im_newline_id (`int`，*可选*，默认为 120121)：用于在序列化图像区域内插入换行样式分隔符的 Token ID。

开源 HunYuanVL 集成的顶层配置。

此配置描述了一种仅包含稠密层、仅处理图像和文本的变体，适用于 OCR 和文档理解类工作负载。其结构与 `Qwen2_5_VL` / `Qwen3_VL` 系列保持一致：顶层配置由 [HunYuanVLTextConfig](/docs/transformers/main/zh/model_doc/hunyuan_vl#transformers.HunYuanVLTextConfig)（文本主干）和 [HunYuanVLVisionConfig](/docs/transformers/main/zh/model_doc/hunyuan_vl#transformers.HunYuanVLVisionConfig)（视觉塔）组合而成，并包含若干用于在多模态提示中界定图像片段的 token id。

示例：

```python
>>> from transformers import HunYuanVLConfig, HunYuanVLForConditionalGeneration
>>>
>>> configuration = HunYuanVLConfig()
>>> model = HunYuanVLForConditionalGeneration(configuration)
>>> configuration = model.config
```

## HunYuanVLVisionConfig[[transformers.HunYuanVLVisionConfig]]

#### transformers.HunYuanVLVisionConfig[[transformers.HunYuanVLVisionConfig]]

```python
transformers.HunYuanVLVisionConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_act: str = 'gelu', hidden_size: int = 1152, intermediate_size: int = 4304, interpolate_mode: str = 'bilinear', rms_norm_eps: float = 1e-05, attention_dropout: float = 0.0, num_attention_heads: int = 16, num_key_value_heads: int | None = None, num_channels: int = 3, num_hidden_layers: int = 27, out_hidden_size: int = 4096, patch_size: int = 16, spatial_merge_size: int = 2, temporal_patch_size: int = 1, img_max_token_num: int = 4096, max_image_size: int = 2048, min_image_size: int = 512, max_vit_seq_len: int = 16384, text_hidden_size: int = 3072)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/configuration_hunyuan_vl.py#L35)

**参数：**

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

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

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

interpolate_mode (`str`, *可选*, 默认为 `"bilinear"`) : 在调整学习到的 patch 位置嵌入大小以匹配当前图像网格时使用的插值模式。

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

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

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

num_key_value_heads (`int`, *可选*) : 这是用于实现分组查询注意力（Grouped Query Attention）的键值头数量。如果 `num_key_value_heads=num_attention_heads`，模型将使用多头注意力（MHA）；如果 `num_key_value_heads=1`，模型将使用多查询注意力（MQA）；否则将使用 GQA。在将多头检查点转换为 GQA 检查点时，每个组的键和值头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 [这篇论文](https://huggingface.co/papers/2305.13245)。如果未指定，则默认为 `num_attention_heads`。

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

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

out_hidden_size (`int`，*可选*，默认值为 4096)：视觉塔在输出给文本主干网络之前生成的隐藏层大小。

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

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

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

img_max_token_num (`int`，*可选*，默认值为 4096)：视觉栈预期的最大图像 token 数量。

max_image_size (`int`，*可选*，默认值为 2048)：当前开源视觉配置支持的最大图像尺寸。

min_image_size (`int`，*可选*，默认值为 512)：当前开源视觉配置所支持的最小图像尺寸。

max_vit_seq_len (`int`，*可选*，默认为 16384)：视觉 Transformer 生成的最大序列长度。

text_hidden_size (`int`，*可选*，默认为 3072)：文本骨干网络在消费视觉嵌入时期望的隐藏层大小。

仅包含稠密架构的图像-文本 HunYuanVL 开源变体的视觉骨干网络配置。

示例：

```python
>>> from transformers import HunYuanVLVisionConfig
>>>
>>> configuration = HunYuanVLVisionConfig()
>>> configuration.hidden_size
1152
```

## HunYuanVLTextConfig[[transformers.HunYuanVLTextConfig]]

#### transformers.HunYuanVLTextConfig[[transformers.HunYuanVLTextConfig]]

```python
transformers.HunYuanVLTextConfig(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 = 290943, hidden_size: int = 4096, intermediate_size: int = 11008, num_hidden_layers: int = 32, num_attention_heads: int = 32, num_key_value_heads: int | None = None, hidden_act: str = 'silu', max_position_embeddings: int = 2048, initializer_range: float = 0.02, rms_norm_eps: float = 1e-05, use_cache: bool = True, pad_token_id: int | None = 0, bos_token_id: int | None = 1, eos_token_id: int | list[int] | None = 2, eod_token_id: int | None = 3, pretraining_tp: int = 1, tie_word_embeddings: bool = True, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, attention_bias: bool = False, attention_dropout: float | int = 0.0, head_dim: int | None = None, sep_token_id: int | None = 4)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/configuration_hunyuan_vl.py#L106)

**参数：**

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

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

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

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

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

num_key_value_heads (`int`, *可选*) : 这是用于实现分组查询注意力（Grouped Query Attention）的键值头数量。如果 `num_key_value_heads=num_attention_heads`，模型将使用多头注意力（MHA）；如果 `num_key_value_heads=1`，模型将使用多查询注意力（MQA）；否则将使用 GQA。在将多头检查点转换为 GQA 检查点时，每个组的键和值头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 [这篇论文](https://huggingface.co/papers/2305.13245)。如果未指定，则默认为 `num_attention_heads`。

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

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

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`，*可选*，默认为 `0`)：词表中用于填充的 Token ID。

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

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

eod_token_id (`int`, *可选*，默认为 3)：表示文档结束标记的 Token ID。继承自 [HunYuanDenseV1Config](/docs/transformers/main/zh/model_doc/hunyuan_v1_dense#transformers.HunYuanDenseV1Config)，并在此重新记录，以确保自动生成的文档字符串保持同步。

pretraining_tp (`int`，*可选*，默认为 `1`)：实验性功能。预训练期间使用的张量并行 rank。请参阅[此文档](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism)以了解更多相关信息。此值对于确保预训练结果的精确可复现性是必需的。请参阅[此 issue](https://github.com/pytorch/pytorch/issues/76232)。

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

rope_parameters (`dict`, *可选*) : 从 [HunYuanDenseV1Config](/docs/transformers/main/zh/model_doc/hunyuan_v1_dense#transformers.HunYuanDenseV1Config) 继承的 RoPE 配置。当存在 `mrope_section` 时，它会将每个注意力头的一半划分到 HunYuanVL 的多模态 RoPE 轴上。对于 3 轴多模态 RoPE，预期的顺序为 `(width, height, image_index)`；对于 4 轴多模态 RoPE，预期的顺序为 `(position, width, height, image_index)`。`image_index` 轴表示输入序列中图像/帧的序号；来自同一张图像的所有视觉标记在该轴上共享相同的值。

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

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

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

sep_token_id (`int`，*可选*，默认为 4)：HunYuan 分词器用作分隔符标记的 Token id。

仅包含稠密模块的图文 HunYuanVL 开源变体的文本主干配置。

继承自 [HunYuanDenseV1Config](/docs/transformers/main/zh/model_doc/hunyuan_v1_dense#transformers.HunYuanDenseV1Config) 的标准字段，并将规范字段名（`pad_token_id`、`head_dim`、`vocab_size`）声明为唯一的公开属性。部分腾讯检查点在磁盘上保留的旧版别名（`pad_id`、`attention_head_dim`、`org_vocab_size`）通过 `attribute_map` 映射到这些规范字段，因此模型的其他部分只需读取规范字段即可。以 `rope_scaling` / `rope_theta` 形式持久化的旧版 RoPE 负载由基础配置类规范化为 `rope_parameters`。

## HunYuanVLVisionTransformer[[transformers.HunYuanVLVisionTransformer]]

#### transformers.HunYuanVLVisionTransformer[[transformers.HunYuanVLVisionTransformer]]

```python
transformers.HunYuanVLVisionTransformer(config: HunYuanVLVisionConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/modeling_hunyuan_vl.py#L657)

HunYuanVL 视觉塔：patch embedding -> transformer blocks -> 每图像 patch merger。

输入是展平的逐块像素张量，外加一个描述批处理中每张图片空间布局的 `image_grid_thw` 张量。输出为合并后的图像嵌入的拼接结果，可直接分散到语言模型的嵌入流中。

#### forward[[transformers.HunYuanVLVisionTransformer.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/modeling_hunyuan_vl.py#L683)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(num_patches, num_channels * patch_size * patch_size)`)：由图像处理器生成的按块展平的像素特征。

grid_thw (`torch.LongTensor`，形状为 `(num_images, 3)`)：每张图片的时间、高度和宽度维度。每一行包含 `[t, h, w]` 个 patch 的数量。

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

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

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

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

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

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

## HunYuanVLTextModel[[transformers.HunYuanVLTextModel]]

#### transformers.HunYuanVLTextModel[[transformers.HunYuanVLTextModel]]

```python
transformers.HunYuanVLTextModel(config: HunYuanVLTextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/modeling_hunyuan_vl.py#L726)

**参数：**

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

未添加任何特定头部的裸 Hunyuan Vl 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.HunYuanVLTextModel.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/hunyuan_vl/modeling_hunyuan_vl.py#L748)

**参数：**

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

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

[HunYuanVLTextModel](/docs/transformers/main/zh/model_doc/hunyuan_vl#transformers.HunYuanVLTextModel) 的 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 后的注意力权重，用于在自注意力头中计算加权平均值。

## HunYuanVLModel[[transformers.HunYuanVLModel]]

#### transformers.HunYuanVLModel[[transformers.HunYuanVLModel]]

```python
transformers.HunYuanVLModel(config: HunYuanVLConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/modeling_hunyuan_vl.py#L827)

**参数：**

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

HunYuanVL 模型由视觉主干网络和语言模型组成，不包含语言建模头。

该模型继承自 [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.HunYuanVLModel.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, image_grid_thw: typing.Optional[torch.LongTensor] = None, mm_token_type_ids: typing.Optional[torch.IntTensor] = 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/hunyuan_vl/modeling_hunyuan_vl.py#L1039)

**参数：**

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)`，*可选*)：与输入图像对应的张量。可以使用 [HunYuanVLImageProcessor](/docs/transformers/main/zh/model_doc/hunyuan_vl#transformers.HunYuanVLImageProcessor) 获取像素值。有关详细信息，请参阅 [HunYuanVLImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[HunYuanVLProcessor](/docs/transformers/main/zh/model_doc/hunyuan_vl#transformers.HunYuanVLProcessor) 使用 [HunYuanVLImageProcessor](/docs/transformers/main/zh/model_doc/hunyuan_vl#transformers.HunYuanVLImageProcessor) 处理图像）。

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

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

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

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

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

[HunYuanVLModel](/docs/transformers/main/zh/model_doc/hunyuan_vl#transformers.HunYuanVLModel) 的 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 后的注意力权重，用于在自注意力头中计算加权平均值。
- **image_hidden_states** (`torch.Tensor`，*可选*) -- 由视觉塔生成的最后一层图像特征，并分散到语言模型的 token 流中。

#### get_image_features[[transformers.HunYuanVLModel.get_image_features]]

```python
get_image_features(pixel_values: Tensor, image_grid_thw: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/modeling_hunyuan_vl.py#L968)

**参数：**

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

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

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

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

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

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

## HunYuanVLForConditionalGeneration[[transformers.HunYuanVLForConditionalGeneration]]

#### transformers.HunYuanVLForConditionalGeneration[[transformers.HunYuanVLForConditionalGeneration]]

```python
transformers.HunYuanVLForConditionalGeneration(config: HunYuanVLConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/modeling_hunyuan_vl.py#L1108)

**参数：**

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

用于基于其他模态（例如图像-文本到文本生成）进行 token 生成的 Hunyuan Vl 模型。

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

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, pixel_values: typing.Optional[torch.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, mm_token_type_ids: typing.Optional[torch.IntTensor] = 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/hunyuan_vl/modeling_hunyuan_vl.py#L1134)

**参数：**

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

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

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

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

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

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

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

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

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

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/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, HunYuanVLForConditionalGeneration
>>> import torch

>>> model_id = "tencent/HunyuanOCR"
>>> processor = AutoProcessor.from_pretrained(model_id, backend="pil")
>>> model = HunYuanVLForConditionalGeneration.from_pretrained(
...     model_id, attn_implementation="eager", torch_dtype=torch.bfloat16, device_map="auto"
... )

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {"type": "image", "image": "path/to/your/image.jpg"},
...             {"type": "text", "text": "Extract the text from the image."},
...         ],
...     }
... ]
>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     add_generation_prompt=True,
...     return_tensors="pt",
...     return_dict=True,
...     processor_kwargs={"padding": True},
... )

>>> with torch.no_grad():
...     generated_ids = model.generate(**inputs, max_new_tokens=128)
>>> generated_trimmed = generated_ids[0][inputs["input_ids"].shape[-1]:]
>>> print(processor.decode(generated_trimmed, skip_special_tokens=True))
```

#### get_image_features[[transformers.HunYuanVLForConditionalGeneration.get_image_features]]

```python
get_image_features(pixel_values: Tensor, image_grid_thw: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hunyuan_vl/modeling_hunyuan_vl.py#L1121)

**参数：**

pixel_values (`torch.Tensor`) : 由图像处理器生成的每个 patch 的扁平化像素特征。

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

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

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

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

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

示例：

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, HunYuanVLForConditionalGeneration

>>> model = HunYuanVLForConditionalGeneration.from_pretrained("None")
>>> processor = AutoProcessor.from_pretrained("None")

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

