Transformers documentation

Qwen3-VL

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

and get access to the augmented documentation experience

to get started

该模型于 2025-02-19 在 HF papers 上发布,并于 2025-09-15 贡献至 Hugging Face Transformers。

FlashAttention SDPA

Qwen3-VL

Qwen3-VL 是一个多模态视觉语言模型系列,涵盖稠密模型和 MoE 变体,以及 Instruct 和 Thinking 版本。在前代模型的基础上,Qwen3-VL 在视觉理解方面实现了显著提升,同时保持了强大的纯文本能力。关键的架构改进包括:采用交错布局的增强版 MRope,以实现更好的时空建模;集成 DeepStack,以有效利用视觉 Transformer(ViT)的多层级特征;以及通过基于文本的时间对齐来改进视频理解——从 T-RoPE 演进为文本时间戳对齐,从而实现更精确的时间定位。这些创新共同使 Qwen3-VL 在复杂的多模态任务中取得了卓越的性能。

在 from_pretrained() 中设置 use_kernels=True,即可用 Hub 上的优化内核替换受支持的层。有关详细信息,请参阅 加载内核。

模型使用

AutoModel
from transformers import AutoProcessor, Qwen3VLForConditionalGeneration


model = Qwen3VLForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-VL",
    device_map="auto",
    attn_implementation="sdpa"
)
processor = AutoProcessor.from_pretrained("Qwen/Qwen3-VL")
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."
            }
        ]
    }

]

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt",
)
inputs.pop("token_type_ids", None)

generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [
            out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
       generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text)

Qwen3VLConfig

class transformers.Qwen3VLConfig

< >

( 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 = 151655video_token_id: int = 151656vision_start_token_id: int = 151652vision_end_token_id: int = 151653tie_word_embeddings: bool = False )

参数

  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。
  • image_token_id (int,可选,默认为 151655) — 用作输入图像占位符的图像 token 索引。
  • video_token_id (int,可选,默认为 151656) — 用作输入视频占位符的视频 token 索引。
  • vision_start_token_id (int,可选,默认为 151652) — 用于标记多模态输入序列中视觉片段起始位置的 Token ID。
  • vision_end_token_id (int,可选,默认为 151653) — 用于标记多模态输入序列中视觉片段结束的 Token ID。
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 Qwen3VLModel 配置的类。它根据指定的参数实例化 Qwen3 Vl 模型,并定义模型架构。使用默认值实例化配置,将得到与 Qwen/Qwen3-VL-4B-Instruct 类似的配置。

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

示例:

>>> from transformers import Qwen3VLForConditionalGeneration, Qwen3VLConfig

>>> # Initializing a Qwen3-VL style configuration
>>> configuration = Qwen3VLConfig()

>>> # Initializing a model from the Qwen3-VL-4B style configuration
>>> model = Qwen3VLForConditionalGeneration(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

Qwen3VLVisionConfig

class transformers.Qwen3VLVisionConfig

< >

( 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 = Nonedepth: int = 27hidden_size: int = 1152hidden_act: str = 'gelu_pytorch_tanh'intermediate_size: int = 4304num_heads: int = 16in_channels: int = 3patch_size: int | list[int] | tuple[int, int] = 16spatial_merge_size: int = 2temporal_patch_size: int | list[int] | tuple[int, int] = 2out_hidden_size: int = 3584num_position_embeddings: int = 2304deepstack_visual_indexes: list[int] | tuple[int, ...] = (8, 16, 24)initializer_range: float = 0.02rope_parameters: dict | None = None )

参数

  • depth (int,可选,默认为 27) — 视觉编码器中 Transformer 层的数量。
  • hidden_size (int,可选,默认为 1152) — 隐藏表示的维度。
  • hidden_act (str,可选,默认为 gelu_pytorch_tanh) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • intermediate_size (int,可选,默认为 4304) — MLP 表示的维度。
  • num_heads (int,可选,默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • in_channels (int,可选,默认为 3) — 输入通道的数量。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 16) — 每个 patch 的大小(分辨率)。
  • spatial_merge_size (int,可选,默认为 2) — 用于通过合并相邻 patch 来减少视觉 token 数量的空间合并窗口大小。
  • temporal_patch_size (Union[int, list[int], tuple[int, int]], 可选,默认为 2) — 用于视频输入 3D 补丁嵌入的时间维度补丁大小。
  • out_hidden_size (int,可选,默认为 3584) — 视觉模型的输出隐藏层大小。
  • num_position_embeddings (int,可选,默认为 2304) — 该模型可能使用的最大序列长度
  • deepstack_visual_indexes (list[int],可选,默认为 [8, 16, 24]) — 用于 deepstack 嵌入的层索引。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • rope_parameters (dict, 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。

这是用于存储 Qwen3VLModel 配置的类。它根据指定的参数实例化 Qwen3 Vl 模型,并定义模型架构。使用默认值实例化配置,将得到与 Qwen/Qwen3-VL-4B-Instruct 类似的配置。

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

Qwen3VLTextConfig

类 transformers.Qwen3VLTextConfig

< >

( 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 = 151936hidden_size: int = 4096intermediate_size: int = 22016num_hidden_layers: int = 32num_attention_heads: int = 32num_key_value_heads: int | None = 32head_dim: int = 128hidden_act: str = 'silu'max_position_embeddings: int = 128000initializer_range: float = 0.02rms_norm_eps: float = 1e-06use_cache: bool = Truerope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falseattention_dropout: float | int = 0.0pad_token_id: int | None = None )

参数

  • vocab_size (int,可选,默认为 151936) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 4096) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 22016) — MLP 表示的维度。
  • num_hidden_layers (int,可选,默认为 32) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 32) — 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,可选,默认为 128) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads
  • hidden_act (str,可选,默认为 silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • max_position_embeddings (int,可选,默认为 128000) — 该模型可能使用的最大序列长度。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • rms_norm_eps (float,可选,默认为 1e-06) — RMS 归一化层使用的 epsilon 值。
  • use_cache (bool,可选,默认为 True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 或模型为仅解码器生成式模型时相关。
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • attention_bias (bool,可选,默认为 False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • pad_token_id (int, 可选) — 词表中用于填充的 token id。

这是用于存储 Qwen3VLModel 配置的类。它根据指定的参数实例化 Qwen3 Vl 模型,并定义模型架构。使用默认值实例化配置,将得到与 Qwen/Qwen3-VL-4B-Instruct 类似的配置。

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

示例:

>>> from transformers import Qwen3VLTextModel, Qwen3VLTextConfig

>>> # Initializing a Qwen3VL style configuration
>>> configuration = Qwen3VLTextConfig()

>>> # Initializing a model from the Qwen3-VL-7B style configuration
>>> model = Qwen3VLTextModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

Qwen3VLProcessor

class transformers.Qwen3VLProcessor

< >

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

参数

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

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

Qwen3VLProcessor 提供了 Qwen2VLImageProcessor、Qwen2Tokenizer 和 Qwen3VLVideoProcessor 的所有功能。有关更多信息,请参阅 ~Qwen2VLImageProcessor、~Qwen2Tokenizer 和 ~Qwen3VLVideoProcessor。

__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_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

Qwen3VLVideoProcessor

class transformers.Qwen3VLVideoProcessor

< >

( **kwargs: *<class 'transformers.models.qwen3_vl.video_processing_qwen3_vl.Qwen3VLVideoProcessorInitKwargs'> )

参数

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

构建一个 Qwen3VLVideoProcessor 视频处理器。

get_num_of_video_patches

< >

( num_frames: intheight: intwidth: intvideos_kwargs = None ) → int

参数

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

返回值

int

每个视频的视频块数量。

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

patchify

< >

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

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

调整大小

< >

( videos: torch.Tensorsize: SizeDictresample: PILImageResampling | tvF.InterpolationMode | int | Nonefactor: inttemporal_factor: intcap_pixels_per_frame: bool | None = None**kwargs )

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

sample_frames

< >

( metadata: VideoMetadatanum_frames: int | None = Nonefps: int | float | None = None**kwargs ) → np.ndarray

参数

  • video (torch.Tensor) — 需要采样的视频。
  • metadata (VideoMetadata) — 视频的元数据,包含总时长、帧率(fps)和总帧数等信息。
  • num_frames (int, 可选) — 要采样的最大帧数。默认为 self.num_frames。
  • fps (int 或 float,可选) — 每秒采样的目标帧数。默认为 self.fps。

返回值

np.ndarray

采样的视频帧。

默认采样函数,在 0 到总帧数之间均匀采样指定数量的帧。 如果同时传入 fps 和元数据,则按 fps 帧/秒均匀采样。参数 num_frames 和 fps 互斥。

Qwen3VLVisionModel

class transformers.Qwen3VLVisionModel

< >

( config: Qwen3VLVisionConfig*inputs**kwargs )

forward

< >

( hidden_states: Tensorgrid_thw: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → torch.Tensor

参数

  • hidden_states(形状为 (seq_len, hidden_size) 的 torch.Tensor)— 模型的最终隐藏状态。
  • grid_thw (torch.Tensor,形状为 (num_images_or_videos, 3)) — LLM 中每张图片特征形状的时间、高度和宽度。

返回值

torch.Tensor

hidden_states.

Qwen3VLTextModel

class transformers.Qwen3VLTextModel

< >

( config: Qwen3VLTextConfig )

参数

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

Qwen3VL 的文本部分,并非纯文本模型,因为 DeepStack 将视觉特征整合到了早期的隐藏状态中。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonevisual_pos_masks: typing.Optional[torch.Tensor] = Nonedeepstack_visual_embeds: list[torch.Tensor] | None = None**kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'> ) → BaseModelOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

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

    什么是位置 ID?

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

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

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

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

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • visual_pos_masks(形状为 (batch_size, seqlen) 的 torch.Tensor,可选) — 视觉位置的掩码。
  • deepstack_visual_embeds (list[torch.Tensor], 可选) — Deepstack 视觉嵌入。其形状为 (num_layers, visual_seqlen, embed_dim)。 该特征从不同的视觉编码器层中提取,并输入到解码器的隐藏状态中。它来自论文 DeepStack(https://arxiv.org/abs/2406.04334)。

返回值

BaseModelOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

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

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

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

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

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

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

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

Qwen3VLModel

class transformers.Qwen3VLModel

< >

( config: Qwen3VLConfig )

参数

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

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

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

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

forward

< >

( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = 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'> ) → BaseModelOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

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

    什么是位置 ID?

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

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

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

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

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 对应输入图像的张量。像素值可通过 Qwen2VLImageProcessor 获取。有关详细信息,请参阅 Qwen2VLImageProcessor.call()(Qwen3VLProcessor 使用 Qwen2VLImageProcessor 处理图像)。
  • pixel_values_videos (torch.Tensor,形状为 (batch_size, num_frames, num_channels, frame_size, frame_size),可选) — 对应输入视频的张量。可以使用 Qwen3VLVideoProcessor 获取视频的像素值。有关详细信息,请参阅 Qwen3VLVideoProcessor.call()(Qwen3VLProcessor 使用 Qwen3VLVideoProcessor 处理视频)。
  • 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),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

BaseModelOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

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

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

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

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

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

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

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

get_video_features

< >

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

参数

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

返回值

BaseModelOutputWithDeepstackFeatures 或 tuple(torch.Tensor)

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

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

  • deepstack_features (List[torch.Tensor], 可选) — 来自 deepstack 层的隐藏状态(特征图)列表。

get_image_features

< >

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

参数

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

返回值

BaseModelOutputWithDeepstackFeatures 或 tuple(torch.Tensor)

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

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

  • deepstack_features (List[torch.Tensor], 可选) — 来自 deepstack 层的隐藏状态(特征图)列表。

Qwen3VLForConditionalGeneration

类 transformers.Qwen3VLForConditionalGeneration

< >

( config: Qwen3VLConfig )

forward

< >

( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = 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'> ) → CausalLMOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

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

    什么是位置 ID?

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

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

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

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

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。
  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 对应输入图像的张量。像素值可通过 Qwen2VLImageProcessor 获取。有关详细信息,请参阅 Qwen2VLImageProcessor.call()(Qwen3VLProcessor 使用 Qwen2VLImageProcessor 处理图像)。
  • pixel_values_videos (torch.Tensor,形状为 (batch_size, num_frames, num_channels, frame_size, frame_size),可选) — 对应输入视频的张量。可以使用 Qwen3VLVideoProcessor 获取视频的像素值。有关详细信息,请参阅 Qwen3VLVideoProcessor.call()(Qwen3VLProcessor 使用 Qwen3VLVideoProcessor 处理视频)。
  • 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),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

CausalLMOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

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

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

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

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

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

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

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

示例:

>>> from transformers import AutoProcessor, Qwen3VLForConditionalGeneration

>>> model = Qwen3VLForConditionalGeneration.from_pretrained("Qwen/Qwen3-VL-8B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3-VL-8B-Instruct")

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

>>> inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt"
)

>>> # Generate
>>> generated_ids = model.generate(**inputs, max_new_tokens=1024)
>>> generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
>>> output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
>>> print(output_text)

get_video_features

< >

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

参数

  • pixel_values_videos(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 与输入视频对应的张量。
  • video_grid_thw(形状为 (num_videos, 3) 的 torch.LongTensor,可选) — LLM 中每个视频的特征形状的时间、高度和宽度。

返回值

BaseModelOutputWithDeepstackFeatures 或 tuple(torch.Tensor)

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

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

  • deepstack_features (List[torch.Tensor], 可选) — 来自 deepstack 层的隐藏状态(特征图)列表。

示例:

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

>>> model = Qwen3VLForConditionalGeneration.from_pretrained("Qwen/Qwen3-VL-4B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3-VL-4B-Instruct")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]

get_image_features

< >

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

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 与输入图像对应的张量。
  • image_grid_thw (torch.LongTensor,形状为 (num_images, 3),可选) — LLM 中每张图片特征形状的时间、高度和宽度。

返回值

BaseModelOutputWithDeepstackFeatures 或 tuple(torch.Tensor)

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

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

  • deepstack_features (List[torch.Tensor], 可选) — 来自 deepstack 层的隐藏状态(特征图)列表。

示例:

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

>>> model = Qwen3VLForConditionalGeneration.from_pretrained("Qwen/Qwen3-VL-4B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3-VL-4B-Instruct")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
Update on GitHub