Transformers documentation

HYV4VL

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.24.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2026-11-17 贡献至 Hugging Face Transformers。

HYV4VL

概述

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

用法

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

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

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

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

图像输入

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 以禁用默认帧率。

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;视频预处理使用 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_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneimage_token_id: int = 120120video_token_id: int = 120124tie_word_embeddings: bool = False )

参数

  • 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 类似的配置。

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

HYV4VLTextConfig

类 transformers.HYV4VLTextConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 120832hidden_size: int = 6144intermediate_size: int = 18432moe_intermediate_size: int = 2048num_hidden_layers: int = 78num_attention_heads: int = 64num_key_value_heads: int = 32head_dim: int = 256hidden_act: str = 'silu'max_position_embeddings: int = 262144initializer_range: float = 0.006rms_norm_eps: float = 1e-05use_cache: bool = Truepad_token_id: int | None = 120002bos_token_id: int | None = 120000eos_token_id: int | list[int] | None = 120025tie_word_embeddings: bool = Falseattention_bias: bool = Falseattention_dropout: float = 0.0n_routed_experts: int = 256output_router_logits: bool = Falsen_shared_experts: int = 1num_experts_per_tok: int = 8routed_scaling_factor: float = 2.827norm_topk_prob: bool = Truen_group: int = 1topk_group: int = 1q_lora_rank: int = 2048kv_lora_rank: int = 512qk_nope_head_dim: int = 192qk_rope_head_dim: int = 64v_head_dim: int = 256mlp_layer_types: list[str] | None = Nonelayer_types: list[str] | None = Noneindex_topk: int = 2048index_head_dim: int = 128index_n_heads: int = 32indexer_types: list[str] | None = Nonehc_mult: int = 4hc_magnitude: float = 2.0hc_eps: float = 1e-06learnable_sink_init: float = 0.0swiglu_limit: float = 10.0rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None )

参数

  • 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 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 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) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • 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], 可选) — 一个列表,用于显式地将每个层索引映射到其层类型。如果未提供,将根据 config 值自动生成。
  • 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) — 每个可学习注意力 sink 对数几率的初始值。
  • swiglu_limit (float,可选,默认为 10.0) — 路由专家 SwiGLU 截断的幅度。值小于或等于零时,将禁用该截断。
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。

这是用于存储 HYV4VLModel 配置的类。它根据指定的参数实例化 Hy V4 Vl 模型,并定义模型架构。使用默认值实例化配置将生成与 tencent/Hy4 类似的配置。

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

HYV4VLVisionConfig

类 transformers.HYV4VLVisionConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_act: str = 'gelu'hidden_size: int = 1536intermediate_size: int = 6144interpolate_mode: str = 'bilinear'rms_norm_eps: float = 1e-05attention_dropout: float = 0.0num_attention_heads: int = 16num_key_value_heads: int | None = Nonenum_channels: int = 3num_hidden_layers: int = 40out_hidden_size: int = 6144patch_size: int = 16spatial_merge_size: int = 2max_image_size: int = 2048 )

参数

  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • hidden_size (int,可选,默认为 1536) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 6144) — 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 的 key_value 头数。如果 num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果 num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 num_attention_heads。
  • 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 类似的配置。

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

HYV4VLProcessor

类 transformers.HYV4VLProcessor

< >

( image_processor = Nonetokenizer = Nonevideo_processor = Nonechat_template = None**kwargs )

参数

  • image_processor (HYV4VLImageProcessor) — 图像处理器是必需的输入。
  • tokenizer (tokenizer_class) — 分词器是必需的输入。
  • video_processor (HYV4VLVideoProcessor) — 视频处理器是必需的输入。
  • chat_template (str) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。

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

HYV4VLProcessor 提供了 HYV4VLImageProcessor、tokenizer_class 和 HYV4VLVideoProcessor 的所有功能。有关更多信息,请参阅 ~HYV4VLImageProcessor、~tokenizer_class 和 ~HYV4VLVideoProcessor。

__call__

< >

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

参数

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

HYV4VLImageProcessor

类 transformers.HYV4VLImageProcessor

< >

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

参数

  • 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 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 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

< >

( height: intwidth: intimages_kwargs: dict | None = None ) → tuple[int, int]

参数

  • height (int) — 输入图像的高度。
  • width (int) — 输入图像的宽度。
  • images_kwargs (dict, 可选) — 用于覆盖图像处理器默认值的任意关键字参数。

返回值

tuple[int, int]

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

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

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

patchify

< >

( images: torch.Tensorpatch_size: intmerge_size: inttemporal_patch_size: int )

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

预处理

< >

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

参数

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

调整大小

< >

( images: torch.Tensorsize: SizeDictresample: PILImageResampling | tvF.InterpolationMode | int | Nonefactor: int**kwargs )

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

HYV4VLImageProcessorPil

类 transformers.HYV4VLImageProcessorPil

< >

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

参数

  • 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 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 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

< >

( height: intwidth: intimages_kwargs: dict | None = None ) → tuple[int, int]

参数

  • height (int) — 输入图像的高度。
  • width (int) — 输入图像的宽度。
  • images_kwargs (dict, 可选) — 用于覆盖图像处理器默认值的任意关键字参数。

返回值

tuple[int, int]

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

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

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

patchify

< >

( image: ndarraypatch_size: intmerge_size: inttemporal_patch_size: int )

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

预处理

< >

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

参数

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

调整大小

< >

( image: ndarraysize: SizeDictresample: PILImageResampling | int | Nonefactor: int**kwargs )

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

HYV4VLVideoProcessor

类 transformers.HYV4VLVideoProcessor

< >

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

参数

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

构造一个 HYV4VLVideoProcessor 视频处理器。

预处理

< >

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

参数

  • videos (Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]) — 要预处理的视频。期望输入单个视频或一批视频,其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间,请设置 do_rescale=False。
  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • default_to_square (bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float, kwargs, 可选) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • do_sample_frames (bool, kwargs, 可选) — 是否在处理前对视频进行帧采样,还是处理整个视频。
  • video_metadata (Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None], kwargs) — 视频的元数据,包含总时长、帧率(fps)和总帧数等信息。该元数据将用于从视频中采样帧或计算时间戳。除非您打算在预处理之前手动解码视频,否则请勿传入任何元数据。
  • fps (Annotated[int | float | None, None], kwargs) — 当 do_sample_frames=True 时,每秒要采样的目标帧数。
  • num_frames (Annotated[int | None, None], kwargs) — 当 do_sample_frames=True 时,要采样的最大帧数。
  • return_metadata (bool, kwargs, 可选) — 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

HYV4VLVisionModel

类 transformers.HYV4VLVisionModel

< >

( config: HYV4VLVisionConfig )

参数

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

未添加任何特定头部的裸 Hy V4 Vl 模型,输出原始隐藏状态。

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

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

forward

< >

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

参数

  • pixel_values(形状为 (num_patches, num_channels * patch_size * patch_size) 的 torch.Tensor)— 由图像处理器生成的按块展平的像素特征。
  • grid_thw(形状为 (num_images, 3) 的 torch.LongTensor)— 每张图片的时间、高度和宽度维度。每一行包含 [t, h, w] 个 patch 的数量。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

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

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

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

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

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 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

< >

( config: HYV4VLTextConfig )

参数

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

未附加任何特定头部的裸 Hy V4 Vl Text Model,直接输出原始隐藏状态。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeModelOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

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

    什么是位置 ID?

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

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

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

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

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 True,则会返回 cache 键值状态,可用于加速解码(参见 cache)。

返回值

MoeModelOutputWithPast 或 tuple(torch.Tensor)

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

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 实例。更多详情,请参阅我们的 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

< >

( config: HYV4VLConfig )

参数

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

未添加任何特定头部的裸 Hy V4 Vl 模型,输出原始隐藏状态。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_values_videos: typing.Optional[torch.Tensor] = Noneimage_grid_thw: typing.Optional[torch.LongTensor] = Nonevideo_grid_thw: typing.Optional[torch.LongTensor] = Nonemm_token_type_ids: typing.Optional[torch.IntTensor] = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MultimodalMoeBaseModelOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

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

    什么是位置 ID?

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

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

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

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

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 True,则会返回 cache 键值状态,可用于加速解码(参见 cache)。
  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor,可选) — 与输入图像对应的张量。可以使用 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(形状为 (num_videos, 3) 的 torch.LongTensor,可选) — LLM 中每个视频的特征形状的时间、高度和宽度。
  • mm_token_type_ids (torch.IntTensor,形状为 (batch_size, sequence_length),可选) — 输入序列中匹配每种模态的 token 索引。例如文本 (0)、图像 (1)、视频 (2)。 可通过 AutoProcessor 获取多模态 token 类型 id。详情请参见 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 的 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 实例。有关更多详细信息,请参阅我们的 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

< >

( pixel_values: Tensorimage_grid_thw: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 HYV4VLImageProcessor 获取像素值。有关详细信息,请参阅 HYV4VLImageProcessor.call()(HYV4VLProcessor 使用 HYV4VLImageProcessor 来处理图像)。
  • image_grid_thw (torch.LongTensor,形状为 (num_images, 3),可选) — LLM 中每张图片特征形状的时间、高度和宽度。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

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

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

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 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

< >

( pixel_values_videos: Tensorvideo_grid_thw: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • pixel_values_videos (torch.Tensor,形状为 (batch_size, num_frames, num_channels, frame_size, frame_size)) — 与输入视频对应的张量。可以使用 HYV4VLVideoProcessor 获取视频的像素值。有关详细信息,请参阅 HYV4VLVideoProcessor.call()(HYV4VLProcessor 使用 HYV4VLVideoProcessor 来处理视频)。
  • video_grid_thw(形状为 (num_videos, 3) 的 torch.LongTensor,可选) — LLM 中每个视频的特征形状的时间、高度和宽度。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

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

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

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 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

< >

( config: HYV4VLConfig )

参数

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

用于基于其他模态(例如图像-文本到文本生成)进行 token 生成的 Hy V4 Vl 模型。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_values_videos: typing.Optional[torch.Tensor] = Noneimage_grid_thw: typing.Optional[torch.LongTensor] = Nonevideo_grid_thw: typing.Optional[torch.LongTensor] = Nonemm_token_type_ids: typing.Optional[torch.IntTensor] = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeCausalLMOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

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

    什么是位置 ID?

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

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

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

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

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。
  • use_cache (bool, 可选) — 如果设置为 True,则会返回 cache 键值状态,可用于加速解码(参见 cache)。
  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor,可选) — 与输入图像对应的张量。可以使用 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(形状为 (num_videos, 3) 的 torch.LongTensor,可选) — LLM 中每个视频的特征形状的时间、高度和宽度。
  • mm_token_type_ids (torch.IntTensor,形状为 (batch_size, sequence_length),可选) — 输入序列中匹配每种模态的 token 索引。例如文本 (0)、图像 (1)、视频 (2)。 可通过 AutoProcessor 获取多模态 token 类型 id。详情请参见 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 的 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 实例。更多详情,请参阅我们的 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

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