# HYV4VL

## 概述

HYV4VL 将 [HYV4](./hy_v4) 混合专家文本骨干与视觉编码器相结合，用于图像-文本和视频-文本生成。它支持动态分辨率的视觉输入，并使用多模态旋转位置嵌入（mRoPE）来表示时间和空间位置。

## 用法

示例中使用的暂定模型 ID 为 `tencent/Hy4`，该 ID 在正式发布前可能会更改。完整模型需要多块 GPU。示例通过张量并行对稠密层进行分片，并通过专家并行对专家进行分发，对于这种混合专家模型而言，这种方式比仅使用张量并行更高效。

将任一示例保存为 `generate.py`，并以每个 GPU 一个进程的方式启动。对于单节点分配，将 `NUM_GPUS` 设置为要使用的 GPU 数量，然后运行：

```bash
torchrun --standalone --nproc-per-node="$NUM_GPUS" generate.py
```

对于多节点分配，请配置分布式启动器的节点数量、节点排名和会合地址。模型加载会初始化分布式执行并选择每个排名对应的设备。

### 图像输入

```python
import os

import torch
from transformers import AutoModelForImageTextToText, AutoProcessor, DistributedConfig

model_id = "tencent/Hy4"
processor = AutoProcessor.from_pretrained(model_id)

distributed_config = DistributedConfig(
    tp_size=int(os.environ["WORLD_SIZE"]),  # Number of devices across which the dense layers are sharded
    ep_size=int(os.environ["WORLD_SIZE"]),  # Number of devices across which the experts are distributed
)
model = AutoModelForImageTextToText.from_pretrained(model_id, distributed_config=distributed_config)

messages = [{
    "role": "user",
    "content": [
        {
            "type": "image",
            "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
        },
        {"type": "text", "text": "Describe this image in one sentence."},
    ],
}]

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    reasoning_effort="no_think",
    return_dict=True,
    return_tensors="pt",
    processor_kwargs={"images_kwargs": {"device": model.device}},
).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=512, do_sample=False)

if torch.distributed.get_rank() == 0:
    completion = outputs[0, inputs["input_ids"].shape[1]:]

    print(processor.decode(completion, skip_special_tokens=True))
```

对于纯文本生成，请使用仅包含一个 `"text"` 项的消息。

### 视频输入

视频文件解码需要 TorchCodec 及其 FFmpeg 运行时依赖项。此示例采样四帧；在提供 `num_frames` 时，将 `fps=None` 设置为 `fps=None` 以禁用默认帧率。

```python
import os

import torch
from transformers import AutoModelForImageTextToText, AutoProcessor, DistributedConfig

model_id = "tencent/Hy4"
processor = AutoProcessor.from_pretrained(model_id)

distributed_config = DistributedConfig(
    tp_size=int(os.environ["WORLD_SIZE"]),  # Number of devices across which the dense layers are sharded
    ep_size=int(os.environ["WORLD_SIZE"]),  # Number of devices across which the experts are distributed
)
model = AutoModelForImageTextToText.from_pretrained(model_id, distributed_config=distributed_config)

messages = [{
    "role": "user",
    "content": [
        {
            "type": "video",
            "url": "https://huggingface.co/datasets/hf-internal-testing/fixtures_videos/resolve/main/tennis.mp4",
        },
        {"type": "text", "text": "Summarize the action in this video."},
    ],
}]

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    reasoning_effort="no_think",
    return_dict=True,
    return_tensors="pt",
    processor_kwargs={
        "videos_kwargs": {
            "do_sample_frames": True,
            "num_frames": 4,
            "fps": None,
            "device": model.device,
        },
    },
).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=512, do_sample=False)

if torch.distributed.get_rank() == 0:
    completion = outputs[0, inputs["input_ids"].shape[1]:]

    print(processor.decode(completion, skip_special_tokens=True))
```

## 使用技巧

- 聊天模板默认使用 `reasoning_effort="high"`。如需直接获取答案，请使用 `reasoning_effort="no_think"`。对于推理任务，请确保生成的 token 数量足以容纳推理过程和最终答案。
- 从检查点加载处理器，以使用其图像和视频设置。图像使用 [HunYuanVLImageProcessor](/docs/transformers/main/zh/model_doc/hunyuan_vl#transformers.HunYuanVLImageProcessor)；视频预处理使用 [HYV4VLVideoProcessor](/docs/transformers/main/zh/model_doc/hy_v4_vl#transformers.HYV4VLVideoProcessor)。
- 通过 `processor_kwargs["images_kwargs"]` 和 `processor_kwargs["videos_kwargs"]` 分别传入图像和视频的覆盖参数。图像的 `size["longest_edge"]` 是每张图像的像素预算；视频的 `size["longest_edge"]` 是整个片段的像素预算，因此采样更多帧可能会降低每帧的分辨率。视频的 `max_image_size["longest_edge"]` 还会限制每帧的像素面积，而非其边长。
- 视频采样默认处于禁用状态。启用 `do_sample_frames` 并传入 `num_frames` 或 `fps`；按帧率采样需要源帧率元数据。
- 对于文本长度不同的批次，请在 `processor_kwargs["text_kwargs"]` 中传入 `padding=True`。

## HYV4VLConfig[[transformers.HYV4VLConfig]]

#### transformers.HYV4VLConfig[[transformers.HYV4VLConfig]]

```python
transformers.HYV4VLConfig(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, video_token_id: int = 120124, tie_word_embeddings: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/configuration_hy_v4_vl.py#L216)

**参数：**

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

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

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

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

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

这是用于存储 HYV4VLModel 配置的类。它根据指定的参数实例化 Hy V4 Vl 模型，并定义模型架构。使用默认值实例化配置将生成与 [tencent/Hy4](https://huggingface.co/tencent/Hy4) 类似的配置。

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

## HYV4VLTextConfig[[transformers.HYV4VLTextConfig]]

#### transformers.HYV4VLTextConfig[[transformers.HYV4VLTextConfig]]

```python
transformers.HYV4VLTextConfig(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 = 120832, hidden_size: int = 6144, intermediate_size: int = 18432, moe_intermediate_size: int = 2048, num_hidden_layers: int = 78, num_attention_heads: int = 64, num_key_value_heads: int = 32, head_dim: int = 256, hidden_act: str = 'silu', max_position_embeddings: int = 262144, initializer_range: float = 0.006, rms_norm_eps: float = 1e-05, use_cache: bool = True, pad_token_id: int | None = 120002, bos_token_id: int | None = 120000, eos_token_id: int | list[int] | None = 120025, tie_word_embeddings: bool = False, attention_bias: bool = False, attention_dropout: float = 0.0, n_routed_experts: int = 256, output_router_logits: bool = False, n_shared_experts: int = 1, num_experts_per_tok: int = 8, routed_scaling_factor: float = 2.827, norm_topk_prob: bool = True, n_group: int = 1, topk_group: int = 1, q_lora_rank: int = 2048, kv_lora_rank: int = 512, qk_nope_head_dim: int = 192, qk_rope_head_dim: int = 64, v_head_dim: int = 256, mlp_layer_types: list[str] | None = None, layer_types: list[str] | None = None, index_topk: int = 2048, index_head_dim: int = 128, index_n_heads: int = 32, indexer_types: list[str] | None = None, hc_mult: int = 4, hc_magnitude: float = 2.0, hc_eps: float = 1e-06, learnable_sink_init: float = 0.0, swiglu_limit: float = 10.0, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/configuration_hy_v4_vl.py#L67)

**参数：**

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

topk_group (`int`，*可选*，默认为 1)：路由过程中保留的专家组数量。

q_lora_rank (`int`, *可选*, 默认值为 `2048`) : 查询投影的 LoRA 矩阵的秩。

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

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

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

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

mlp_layer_types (`list[str]`, *可选*) : 每层 MLP 的类型，为 `"dense"` 或 `"sparse"`。默认值为一层 dense 层后跟若干 sparse 层。

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

index_topk (`int`，*可选*，默认为 2048)：每个 DSA 查询选择的最大键位置数。

index_head_dim (`int`，*可选*，默认为 128)：每个 DSA 索引器头的隐藏维度。

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

indexer_types (`list[str]`, *可选*) : 每层 DSA 索引器类型，为 `"full"` 或 `"shared"`（复用前一个完整层的选择）。

hc_mult (`int`，*可选*，默认为 4)：iHC 维护的隐藏状态通道数。

hc_magnitude (`float`, *可选*，默认为 2.0)：应用于 iHC 门控后分支的缩放系数。

hc_eps (`float`, *可选*，默认为 1e-6) : 添加到 iHC sigmoid 门控中的数值 epsilon。

learnable_sink_init (`float`, *可选*，默认为 0.0)：每个学习到的注意力汇聚（attention-sink）logit 的初始值。

swiglu_limit (`float`, *可选*，默认为 10.0)：路由专家 SwiGLU 钳位的幅度。小于或等于零的值将禁用钳位。

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

这是用于存储 HYV4VLModel 配置的类。它根据指定的参数实例化 Hy V4 Vl 模型，并定义模型架构。使用默认值实例化配置将生成与 [tencent/Hy4](https://huggingface.co/tencent/Hy4) 类似的配置。

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

## HYV4VLVisionConfig[[transformers.HYV4VLVisionConfig]]

#### transformers.HYV4VLVisionConfig[[transformers.HYV4VLVisionConfig]]

```python
transformers.HYV4VLVisionConfig(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 = 1536, intermediate_size: int = 6144, 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 = 40, out_hidden_size: int = 6144, patch_size: int = 16, spatial_merge_size: int = 2, max_image_size: int = 2048)
```

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

**参数：**

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

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

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

interpolate_mode (`str`, *可选*, 默认为 `"bilinear"`) : 用于学习到的补丁位置嵌入的插值模式。

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`，*可选*，默认为 `40`)：Transformer 解码器中的隐藏层数。

out_hidden_size (`int`，*可选*，默认为 6144)：传递给文本骨干网络的视觉特征的宽度。

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

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

max_image_size (`int`，*可选*，默认为 2048)：用于定义学习到的位置嵌入网格的图像尺寸。

这是用于存储 HYV4VLModel 配置的类。它根据指定的参数实例化 Hy V4 Vl 模型，并定义模型架构。使用默认值实例化配置将生成与 [tencent/Hy4](https://huggingface.co/tencent/Hy4) 类似的配置。

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

## HYV4VLProcessor[[transformers.HYV4VLProcessor]]

#### transformers.HYV4VLProcessor[[transformers.HYV4VLProcessor]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/processing_hy_v4_vl.py#L25)

**参数：**

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

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

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

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

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

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

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

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

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

**参数：**

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

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

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

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

return_mm_token_type_ids (`bool`, *kwargs*) : 是否返回多模态 token 类型 ID，以指示多模态占位符 token 的位置。

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

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

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

## HYV4VLImageProcessor[[transformers.HYV4VLImageProcessor]]

#### transformers.HYV4VLImageProcessor[[transformers.HYV4VLImageProcessor]]

```python
transformers.HYV4VLImageProcessor(**kwargs: *<class 'transformers.models.hy_v4_vl.image_processing_hy_v4_vl.HYV4VLImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/image_processing_hy_v4_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 编码器的合并大小。

构建 HYV4VLImageProcessor 图像处理器。

#### get_number_of_image_patches[[transformers.HYV4VLImageProcessor.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/hy_v4_vl/image_processing_hy_v4_vl.py#L268)

**参数：**

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

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

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

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

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

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

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

#### patchify[[transformers.HYV4VLImageProcessor.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/hy_v4_vl/image_processing_hy_v4_vl.py#L176)

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

#### preprocess[[transformers.HYV4VLImageProcessor.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.hy_v4_vl.image_processing_hy_v4_vl.HYV4VLImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/image_processing_hy_v4_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.HYV4VLImageProcessor.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/hy_v4_vl/image_processing_hy_v4_vl.py#L147)

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

## HYV4VLImageProcessorPil[[transformers.HYV4VLImageProcessorPil]]

#### transformers.HYV4VLImageProcessorPil[[transformers.HYV4VLImageProcessorPil]]

```python
transformers.HYV4VLImageProcessorPil(**kwargs: *<class 'transformers.models.hy_v4_vl.image_processing_pil_hy_v4_vl.HYV4VLImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/image_processing_pil_hy_v4_vl.py#L85)

**参数：**

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 编码器的合并大小。

构建 HYV4VLImageProcessor 图像处理器。

#### get_number_of_image_patches[[transformers.HYV4VLImageProcessorPil.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/hy_v4_vl/image_processing_pil_hy_v4_vl.py#L261)

**参数：**

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

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

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

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

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

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

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

#### patchify[[transformers.HYV4VLImageProcessorPil.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/hy_v4_vl/image_processing_pil_hy_v4_vl.py#L165)

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

#### preprocess[[transformers.HYV4VLImageProcessorPil.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.hy_v4_vl.image_processing_pil_hy_v4_vl.HYV4VLImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/image_processing_pil_hy_v4_vl.py#L202)

**参数：**

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.HYV4VLImageProcessorPil.resize]]

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

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

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

## HYV4VLVideoProcessor[[transformers.HYV4VLVideoProcessor]]

#### transformers.HYV4VLVideoProcessor[[transformers.HYV4VLVideoProcessor]]

```python
transformers.HYV4VLVideoProcessor(**kwargs: *<class 'transformers.models.hy_v4_vl.video_processing_hy_v4_vl.HYV4VLVideoProcessorInitKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/video_processing_hy_v4_vl.py#L102)

**参数：**

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

构造一个 HYV4VLVideoProcessor 视频处理器。

#### preprocess[[transformers.HYV4VLVideoProcessor.preprocess]]

```python
preprocess(videos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]]], **kwargs: *<class 'transformers.processing_utils.VideosKwargs'>)
```

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

**参数：**

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

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`，*kwargs*，*可选*)：是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*)：描述模型的最大输入维度。

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

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*) : 是否对图像进行重新缩放。

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

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

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

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

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

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

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

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

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

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

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

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

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

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

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

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

## HYV4VLVisionModel[[transformers.HYV4VLVisionModel]]

#### transformers.HYV4VLVisionModel[[transformers.HYV4VLVisionModel]]

```python
transformers.HYV4VLVisionModel(config: HYV4VLVisionConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/modeling_hy_v4_vl.py#L1003)

**参数：**

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

未添加任何特定头部的裸 Hy V4 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.HYV4VLVisionModel.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/hy_v4_vl/modeling_hy_v4_vl.py#L1032)

**参数：**

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

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

## HYV4VLTextModel[[transformers.HYV4VLTextModel]]

#### transformers.HYV4VLTextModel[[transformers.HYV4VLTextModel]]

```python
transformers.HYV4VLTextModel(config: HYV4VLTextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/modeling_hy_v4_vl.py#L1137)

**参数：**

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

未附加任何特定头部的裸 Hy V4 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.HYV4VLTextModel.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/modeling_hy_v4_vl.py#L1157)

**参数：**

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

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

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

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

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

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

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

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

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

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

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

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

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

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **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 之后），这些术语用于计算混合专家模型的辅助损失。

## HYV4VLModel[[transformers.HYV4VLModel]]

#### transformers.HYV4VLModel[[transformers.HYV4VLModel]]

```python
transformers.HYV4VLModel(config: HYV4VLConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/modeling_hy_v4_vl.py#L1230)

**参数：**

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

未添加任何特定头部的裸 Hy V4 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.HYV4VLModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, 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_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/hy_v4_vl/modeling_hy_v4_vl.py#L1520)

**参数：**

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

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

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

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

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

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

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

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

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

video_grid_thw (`torch.LongTensor`，形状为 `(num_videos, 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)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

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

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

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

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

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

#### get_image_features[[transformers.HYV4VLModel.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/hy_v4_vl/modeling_hy_v4_vl.py#L1413)

**参数：**

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

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

- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

#### get_video_features[[transformers.HYV4VLModel.get_video_features]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/modeling_hy_v4_vl.py#L1401)

**参数：**

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

video_grid_thw (`torch.LongTensor`，形状为 `(num_videos, 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`），其包含的元素取决于配置（[HYV4VLConfig](/docs/transformers/main/zh/model_doc/hy_v4_vl#transformers.HYV4VLConfig)）和输入。

- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

## HYV4VLForConditionalGeneration[[transformers.HYV4VLForConditionalGeneration]]

#### transformers.HYV4VLForConditionalGeneration[[transformers.HYV4VLForConditionalGeneration]]

```python
transformers.HYV4VLForConditionalGeneration(config: HYV4VLConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/hy_v4_vl/modeling_hy_v4_vl.py#L1602)

**参数：**

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

用于基于其他模态（例如图像-文本到文本生成）进行 token 生成的 Hy V4 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.HYV4VLForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, 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_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/hy_v4_vl/modeling_hy_v4_vl.py#L1643)

**参数：**

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

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

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

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

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

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

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

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

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

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

video_grid_thw (`torch.LongTensor`，形状为 `(num_videos, 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__)。

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`），其包含的元素取决于配置（`None`）和输入。

[HYV4VLForConditionalGeneration](/docs/transformers/main/zh/model_doc/hy_v4_vl#transformers.HYV4VLForConditionalGeneration) 的 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 如何被分发到各个专家。
- **cache**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **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
>>> import os
>>> from transformers import AutoProcessor, DistributedConfig, HYV4VLForConditionalGeneration

>>> model_path = "tencent/Hy4"  # Tentative release identifier.
>>> world_size = int(os.environ["WORLD_SIZE"])
>>> processor = AutoProcessor.from_pretrained(model_path)
>>> model = HYV4VLForConditionalGeneration.from_pretrained(
...     model_path, distributed_config=DistributedConfig(tp_size=world_size, ep_size=world_size),
... )

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {"type": "image", "image": "path/to/your/image.jpg"},
...             {"type": "text", "text": "Describe this image."},
...         ],
...     }
... ]
>>> inputs = processor.apply_chat_template(
...     messages, tokenize=True, add_generation_prompt=True, reasoning_effort="no_think",
...     return_tensors="pt", return_dict=True,
... ).to(model.device)

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

