Transformers documentation
Qwen2.5-VL
该模型于 2025-02-19 在 HF papers 上发布,并于 2025-01-23 贡献至 Hugging Face Transformers。
Qwen2.5-VL
Qwen2.5-VL 是一款多模态视觉语言模型,提供 3B、7B 和 72B 三种参数规模,基于 4.1T tokens 进行预训练。该模型在 ViT 编码器中引入了窗口注意力机制以加速训练和推理,在空间和时间维度上采用动态 FPS 采样,从而在不同采样率下实现更好的视频理解能力,并升级了 MRoPE(多分辨率旋转位置编码)机制,以更好地捕捉和学习时间动态。
您可以在 Qwen2.5-VL 集合中找到所有原始的 Qwen2.5-VL 检查点。
点击右侧边栏中的 Qwen2.5-VL 模型,以查看更多将 Qwen2.5-VL 应用于不同视觉和语言任务的示例。
在 from_pretrained() 中设置
use_kernels=True,即可用 Hub 上的优化内核替换受支持的层。有关详细信息,请参阅 加载内核。
以下示例演示了如何使用 Pipeline 或 AutoModel 类基于图像生成文本。
from transformers import pipeline
pipe = pipeline(
task="image-text-to-text",
model="Qwen/Qwen2.5-VL-7B-Instruct",
device=0,
)
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."},
]
}
]
pipe(text=messages,max_new_tokens=20, return_full_text=False)from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
"Qwen/Qwen2.5-VL-7B-Instruct",
device_map="auto",
attn_implementation="sdpa"
)
processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
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,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt"
).to(model.device)
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)量化通过以较低精度表示权重来降低大模型的内存负担。有关更多可用的量化后端,请参阅 量化 概述。
以下示例使用 torchao 仅将权重量化为 int4。
from transformers import Qwen2_5_VLForConditionalGeneration, TorchAoConfig
quantization_config = TorchAoConfig("int4_weight_only", group_size=128)
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
"Qwen/Qwen2.5-VL-7B-Instruct",
device_map="auto",
quantization_config=quantization_config
)备注
通过设置
"type": "video"来使用 Qwen2.5-VL 处理视频输入,如下所示。conversation = [ { "role": "user", "content": [ {"type": "video", "path": "/path/to/video.mp4"}, {"type": "text", "text": "What happened in the video?"}, ], } ] inputs = processor.apply_chat_template( conversation, fps=1, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" ).to(model.device) # Inference: Generation of the output output_ids = model.generate(**inputs, max_new_tokens=128) generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, output_ids)] output_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True) print(output_text)使用 Qwen2.5-VL 处理混合输入批次(图像、视频、文本)。在处理多张图像或多个视频时,请添加标签以便更好地引用,如下所示。
import torch from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor model = Qwen2_5_VLForConditionalGeneration.from_pretrained( "Qwen/Qwen2.5-VL-7B-Instruct", device_map="auto", attn_implementation="sdpa" ) processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct") conversation = [ { "role": "user", "content": [ {"type": "image"}, {"type": "text", "text": "Hello, how are you?"} ] }, { "role": "assistant", "content": "I'm doing well, thank you for asking. How can I assist you today?" }, { "role": "user", "content": [ {"type": "text", "text": "Can you describe these images and video?"}, {"type": "image"}, {"type": "image"}, {"type": "video"}, {"type": "text", "text": "These are from my vacation."} ] }, { "role": "assistant", "content": "I'd be happy to describe the images and video for you. Could you please provide more context about your vacation?" }, { "role": "user", "content": "It was a trip to the mountains. Can you see the details in the images and video?" } ] # default: prompt_without_id = processor.apply_chat_template(conversation, add_generation_prompt=True) # Excepted output: '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Hello, how are you?<|im_end|>\n<|im_start|>assistant\nI'm doing well, thank you for asking. How can I assist you today?<|im_end|>\n<|im_start|>user\nCan you describe these images and video?<|vision_start|><|image_pad|><|vision_end|><|vision_start|><|image_pad|><|vision_end|><|vision_start|><|video_pad|><|vision_end|>These are from my vacation.<|im_end|>\n<|im_start|>assistant\nI'd be happy to describe the images and video for you. Could you please provide more context about your vacation?<|im_end|>\n<|im_start|>user\nIt was a trip to the mountains. Can you see the details in the images and video?<|im_end|>\n<|im_start|>assistant\n' # add ids prompt_with_id = processor.apply_chat_template(conversation, add_generation_prompt=True, add_vision_id=True) # Excepted output: '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\nPicture 1: <|vision_start|><|image_pad|><|vision_end|>Hello, how are you?<|im_end|>\n<|im_start|>assistant\nI'm doing well, thank you for asking. How can I assist you today?<|im_end|>\n<|im_start|>user\nCan you describe these images and video?Picture 2: <|vision_start|><|image_pad|><|vision_end|>Picture 3: <|vision_start|><|image_pad|><|vision_end|>Video 1: <|vision_start|><|video_pad|><|vision_end|>These are from my vacation.<|im_end|>\n<|im_start|>assistant\nI'd be happy to describe the images and video for you. Could you please provide more context about your vacation?<|im_end|>\n<|im_start|>user\nIt was a trip to the mountains. Can you see the details in the images and video?<|im_end|>\n<|im_start|>assistant\n'使用 AutoProcessor 中的
min_pixels和max_pixels参数来设置分辨率。min_pixels = 224*224 max_pixels = 2048*2048 processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)更高的分辨率可能需要更多的计算资源,而降低分辨率则可以节省内存,具体如下:
min_pixels = 256*28*28 max_pixels = 1024*28*28 processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
Qwen2_5_VLConfig
类 transformers.Qwen2_5_VLConfig
< source >( 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映射来绑定权重嵌入。
这是用于存储 Qwen2_5_VLModel 配置的类。它根据指定的参数实例化 Qwen2 5 Vl 模型,并定义模型架构。使用默认值实例化配置,将得到与 Qwen/Qwen2-VL-7B-Instruct 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2_5_VLConfig
>>> # Initializing a Qwen2_5_VL style configuration
>>> configuration = Qwen2_5_VLConfig()
>>> # Initializing a model from the Qwen2-VL-7B style configuration
>>> model = Qwen2_5_VLForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configQwen2_5_VLVisionConfig
class transformers.Qwen2_5_VLVisionConfig
< source >( 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 = 32hidden_size: int = 3584hidden_act: str = 'silu'intermediate_size: int = 3420num_heads: int = 16in_channels: int = 3patch_size: int | list[int] | tuple[int, int] = 14spatial_merge_size: int = 2temporal_patch_size: int | list[int] | tuple[int, int] = 2tokens_per_second: int = 4window_size: int = 112out_hidden_size: int = 3584fullatt_block_indexes: list[int] | tuple[int, ...] = (7, 15, 23, 31)initializer_range: float = 0.02rope_parameters: dict | None = None )
参数
- depth (
int,可选,默认为32) — 视觉编码器中 Transformer 层的数量。 - hidden_size (
int,可选,默认为3584) — 隐藏表示的维度。 - hidden_act (
str,可选,默认为silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - intermediate_size (
int,可选,默认为3420) — MLP 表示的维度。 - num_heads (
int,可选,默认为16) — Transformer 解码器中每个注意力层的注意力头数量。 - in_channels (
int,可选,默认为3) — 输入通道的数量。 - patch_size (
Union[int, list[int], tuple[int, int]],可选,默认为14) — 每个 patch 的大小(分辨率)。 - spatial_merge_size (
int,可选,默认为2) — 用于通过合并相邻 patch 来减少视觉 token 数量的空间合并窗口大小。 - temporal_patch_size (
Union[int, list[int], tuple[int, int]], 可选,默认为2) — 用于视频输入 3D 补丁嵌入的时间维度补丁大小。 - tokens_per_second(
int,可选,默认值为 41)— 每秒视频需要合并的 token 数量。 - window_size (
int,可选,默认为 11) — 窗口大小。 - out_hidden_size (
int,可选,默认为 3584) — 视觉模型的输出隐藏层大小。 - fullatt_block_indexes(
int,可选,默认为[7, 15, 23, 31])— 使用完整注意力的层索引 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - rope_parameters (
dict, 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含rope_theta的值,并且如果希望使用 RoPE 处理更长的max_position_embeddings,则可选地包含用于缩放的参数。
这是用于存储 Qwen2_5_VLModel 配置的类。它根据指定的参数实例化 Qwen2 5 Vl 模型,并定义模型架构。使用默认值实例化配置,将得到与 Qwen/Qwen2-VL-7B-Instruct 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
Qwen2_5_VLTextConfig
class transformers.Qwen2_5_VLTextConfig
< source >( 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 = 152064hidden_size: int = 8192intermediate_size: int = 29568num_hidden_layers: int = 80num_attention_heads: int = 64num_key_value_heads: int | None = 8hidden_act: str = 'silu'max_position_embeddings: int = 32768initializer_range: float = 0.02rms_norm_eps: float = 1e-05use_cache: bool = Trueuse_sliding_window: bool | None = Falsesliding_window: int | None = 4096max_window_layers: int | None = 80layer_types: list[str] | None = Noneattention_dropout: float | int | None = 0.0rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Nonebos_token_id: int | None = 151643eos_token_id: int | list[int] | None = 151645pad_token_id: int | None = None )
参数
- vocab_size (
int,可选,默认为152064) — 模型的词汇表大小。定义了input_ids可以表示的不同 token 数量。 - hidden_size (
int,可选,默认为8192) — 隐藏表示的维度。 - intermediate_size (
int,可选,默认为29568) — MLP 表示的维度。 - num_hidden_layers (
int,可选,默认为80) — Transformer 解码器中的隐藏层数。 - num_attention_heads (
int,可选,默认为64) — Transformer 解码器中每个注意力层的注意力头数量。 - num_key_value_heads (
int, 可选,默认为8) — 这是用于实现 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 头应通过对该组内所有原始头进行 meanpooling 来构建。更多详情请参阅 这篇论文。如果未指定,则默认为num_attention_heads。 - hidden_act (
str,可选,默认为silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - max_position_embeddings (
int,可选,默认为32768) — 该模型可能使用的最大序列长度。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - rms_norm_eps (
float,可选,默认为1e-05) — RMS 归一化层使用的 epsilon 值。 - use_cache (
bool,可选,默认为True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当config.is_decoder=True或模型为仅解码器生成式模型时相关。 - use_sliding_window (
bool,可选,默认为False) — 是否使用滑动窗口注意力机制。 - sliding_window (
int,可选,默认为4096) — 滑动窗口注意力的窗口大小。如果为None,则不应用滑动窗口。 - max_window_layers (
int,可选,默认为80) — 使用完整注意力的层数。前max_window_layers层将使用完整注意力,而之后的任何额外层都将使用 SWA(滑动窗口注意力)。 - layer_types (
list[str], 可选) — 一个列表,用于显式地将每个层索引映射到其层类型。如果未提供,将根据 config 值自动生成。 - attention_dropout (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含rope_theta的值,并且如果希望使用 RoPE 处理更长的max_position_embeddings,则可选地包含用于缩放的参数。 - bos_token_id (
int,可选,默认为151643) — 词汇表中用于表示流起始的 token id。 - eos_token_id (
Union[int, list[int]],可选,默认为151645) — 词汇表中用于表示流结束(end-of-stream)的 Token id。 - pad_token_id (
int, 可选) — 词表中用于填充的 token id。
这是用于存储 Qwen2_5_VLModel 配置的类。它根据指定的参数实例化 Qwen2 5 Vl 模型,并定义模型架构。使用默认值实例化配置,将得到与 Qwen/Qwen2-VL-7B-Instruct 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
>>> from transformers import Qwen2_5_VLTextModel, Qwen2_5_VLConfig
>>> # Initializing a Qwen2_5_VL style configuration
>>> configuration = Qwen2_5_VLConfig()
>>> # Initializing a model from the Qwen2-VL-7B style configuration
>>> model = Qwen2_5_VLTextModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configQwen2_5_VLProcessor
类 transformers.Qwen2_5_VLProcessor
< source >( image_processor = Nonetokenizer = Nonevideo_processor = Nonechat_template = None**kwargs )
构建一个 Qwen2_5_VLProcessor,它将图像处理器、分词器和视频处理器封装为单一处理器。
Qwen2_5_VLProcessor 提供了 Qwen2VLImageProcessor、Qwen2Tokenizer 和 Qwen2VLVideoProcessor 的所有功能。有关更多信息,请参阅 ~Qwen2VLImageProcessor、~Qwen2Tokenizer 和 ~Qwen2VLVideoProcessor。
__call__
< source >( 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':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
- **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。
Qwen2_5_VLTextModel
class transformers.Qwen2_5_VLTextModel
< source >( config: Qwen2_5_VLTextConfig )
参数
- config (Qwen2_5_VLTextConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未添加任何特定头部的裸 Qwen2 5 Vl Text Model,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( 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 = 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()。
- 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]. - 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)。
返回值
BaseModelOutputWithPast 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Qwen2_5_VLConfig)和输入。
Qwen2_5_VLTextModel 的 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 之后的权重,用于在自注意力头中计算加权平均值。
Qwen2_5_VisionTransformerPretrainedModel
类 transformers.Qwen2_5_VisionTransformerPretrainedModel
< source >( config: Qwen2_5_VLVisionConfig*inputs**kwargs )
forward
< source >( hidden_states: Tensorgrid_thw: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → torch.Tensor
Qwen2_5_VLModel
class transformers.Qwen2_5_VLModel
< source >( config: Qwen2_5_VLConfig )
参数
- config (Qwen2_5_VLConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未添加任何特定头部的裸 Qwen2 5 Vl 模型,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( 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 = 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] = Nonesecond_per_grid_ts: typing.Optional[torch.Tensor] = 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()。
- 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]. - 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)。 - pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 对应输入图像的张量。可以使用 Qwen2VLImageProcessor 获取像素值。有关详细信息,请参阅 Qwen2VLImageProcessor.call()(Qwen2_5_VLProcessor 使用 Qwen2VLImageProcessor 处理图像)。 - pixel_values_videos (
torch.Tensor,形状为(batch_size, num_frames, num_channels, frame_size, frame_size),可选) — 对应输入视频的张量。可以使用 Qwen2VLVideoProcessor 获取视频的像素值。有关详细信息,请参阅 Qwen2VLVideoProcessor.call()(Qwen2_5_VLProcessor 使用 Qwen2VLVideoProcessor 来处理视频)。 - 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()。 - second_per_grid_ts(形状为
(num_videos)的torch.Tensor,可选) — 3D 位置 ID 中沿时间维度每个网格的时间间隔(以秒为单位)。 - 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),其包含的元素取决于配置(Qwen2_5_VLConfig)和输入。
Qwen2_5_VLModel 的 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
< source >( 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)) — 对应输入视频的张量。可以使用 Qwen2VLVideoProcessor 获取视频的像素值。有关详细信息,请参阅 Qwen2VLVideoProcessor.call()(Qwen2_5_VLProcessor 使用 Qwen2VLVideoProcessor 来处理视频)。 - video_grid_thw(形状为
(num_videos, 3)的torch.LongTensor,可选) — LLM 中每个视频的特征形状的时间、高度和宽度。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Qwen2_5_VLConfig)和输入。
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_image_features
< source >( 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)) — 与输入图像对应的张量。可以使用 Qwen2VLImageProcessor 获取像素值。有关详细信息,请参阅 Qwen2VLImageProcessor.call()(Qwen2_5_VLProcessor 使用 Qwen2VLImageProcessor 来处理图像)。 - image_grid_thw (
torch.LongTensor,形状为(num_images, 3),可选) — LLM 中每张图片特征形状的时间、高度和宽度。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Qwen2_5_VLConfig)和输入。
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 之后的权重,用于在自注意力头中计算加权平均值。
Qwen2_5_VLForConditionalGeneration
forward
< source >( 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] = 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] = Nonesecond_per_grid_ts: typing.Optional[torch.Tensor] = 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()。
- 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]. - 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 进行计算。 - use_cache (
bool,可选) — 如果设置为True,则会返回past_key_values键值状态,可用于加速解码(参见past_key_values)。 - pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 对应输入图像的张量。可以使用 Qwen2VLImageProcessor 获取像素值。有关详细信息,请参阅 Qwen2VLImageProcessor.call()(Qwen2_5_VLProcessor 使用 Qwen2VLImageProcessor 处理图像)。 - pixel_values_videos (
torch.Tensor,形状为(batch_size, num_frames, num_channels, frame_size, frame_size),可选) — 对应输入视频的张量。可以使用 Qwen2VLVideoProcessor 获取视频的像素值。有关详细信息,请参阅 Qwen2VLVideoProcessor.call()(Qwen2_5_VLProcessor 使用 Qwen2VLVideoProcessor 来处理视频)。 - 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()。 - second_per_grid_ts(形状为
(num_videos)的torch.Tensor,可选) — 3D 位置 ID 中沿时间维度每个网格的时间间隔(以秒为单位)。 - 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),其包含的元素取决于配置(Qwen2_5_VLConfig)和输入。
Qwen2_5_VLForConditionalGeneration 的 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, Qwen2_5_VLForConditionalGeneration
>>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-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
< source >( 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(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor)— 与输入视频对应的张量。 - video_grid_thw(形状为
(num_videos, 3)的torch.LongTensor,可选) — LLM 中每个视频的特征形状的时间、高度和宽度。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Qwen2_5_VLConfig)和输入。
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 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> from PIL import Image
>>> from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
>>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-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
< source >( pixel_values: Tensorimage_grid_thw: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling 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 中每张图片特征形状的时间、高度和宽度。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Qwen2_5_VLConfig)和输入。
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 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> from PIL import Image
>>> from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
>>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-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]