Transformers 文档
Qwen2-VL
并获取增强的文档体验
开始使用
Qwen2-VL
概述
Qwen2-VL 模型是阿里巴巴研究团队 Qwen 团队对 Qwen-VL 的一次重大更新。
来自博客的摘要如下:
本博客介绍了 Qwen2-VL,它是 Qwen-VL 模型的升级版本,在过去一年中经历了重大改进。主要改进包括增强的图像理解、先进的视频理解、集成的视觉代理功能以及扩展的多语言支持。该模型架构经过优化,可通过 Naive Dynamic Resolution 支持处理任意图像分辨率,并利用多模态旋转位置嵌入 (M-ROPE) 有效处理一维文本和多维视觉数据。这个更新的模型在视觉相关任务中展示了与 GPT-4o 和 Claude 3.5 Sonnet 等领先 AI 系统相媲美的性能,并在文本能力方面在开源模型中名列前茅。这些进步使 Qwen2-VL 成为各种需要强大的多模态处理和推理能力的应用的通用工具。

此模型由 simonJJJ 贡献。
使用示例
单媒体推理
该模型可以接受图像和视频作为输入。以下是推理的示例代码。
import torch
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
# Load the model in half-precision on the available device(s)
model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", device_map="auto")
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
conversation = [
{
"role":"user",
"content":[
{
"type":"image",
"url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
},
{
"type":"text",
"text":"Describe this image."
}
]
}
]
inputs = processor.apply_chat_template(
conversation,
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)
# Video
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,
video_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)
批量混合媒体推理
该模型可以批量处理由各种类型样本(如图像、视频和文本)组成的输入。这是一个例子。
# Conversation for the first image
conversation1 = [
{
"role": "user",
"content": [
{"type": "image", "path": "/path/to/image1.jpg"},
{"type": "text", "text": "Describe this image."}
]
}
]
# Conversation with two images
conversation2 = [
{
"role": "user",
"content": [
{"type": "image", "path": "/path/to/image2.jpg"},
{"type": "image", "path": "/path/to/image3.jpg"},
{"type": "text", "text": "What is written in the pictures?"}
]
}
]
# Conversation with pure text
conversation3 = [
{
"role": "user",
"content": "who are you?"
}
]
# Conversation with mixed midia
conversation4 = [
{
"role": "user",
"content": [
{"type": "image", "path": "/path/to/image3.jpg"},
{"type": "image", "path": "/path/to/image4.jpg"},
{"type": "video", "path": "/path/to/video.jpg"},
{"type": "text", "text": "What are the common elements in these medias?"},
],
}
]
conversations = [conversation1, conversation2, conversation3, conversation4]
# Preparation for batch inference
ipnuts = processor.apply_chat_template(
conversations,
video_fps=1,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt"
).to(model.device)
# Batch Inference
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)
使用技巧
图像分辨率权衡
该模型支持各种分辨率的输入。默认情况下,它使用原始分辨率进行输入,但更高的分辨率可以提高性能,但会增加计算成本。用户可以设置最小和最大像素数,以实现满足其需求的最佳配置。
min_pixels = 224*224
max_pixels = 2048*2048
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
如果 GPU 内存有限,可以按如下方式降低分辨率
min_pixels = 256*28*28
max_pixels = 1024*28*28
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
这确保了每张图像都使用 256-1024 个 token 进行编码。数字 28 来自于模型使用 14 的 patch size 和 2 的 temporal patch size(14 x 2 = 28)。
多图像输入
默认情况下,图像和视频内容直接包含在对话中。当处理多张图像时,为图像和视频添加标签以便更好地引用会很有帮助。用户可以使用以下设置来控制此行为
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'
Flash-Attention 2 加速生成
首先,请确保安装最新版本的 Flash Attention 2
pip install -U flash-attn --no-build-isolation
此外,您应该拥有与 Flash-Attention 2 兼容的硬件。有关详细信息,请阅读 flash attention 仓库的官方文档。FlashAttention-2 只能在模型以 torch.float16
或 torch.bfloat16
加载时使用。
要使用 Flash Attention-2 加载和运行模型,只需在加载模型时添加 attn_implementation="flash_attention_2"
,如下所示
from transformers import Qwen2VLForConditionalGeneration
model = Qwen2VLForConditionalGeneration.from_pretrained(
"Qwen/Qwen2-VL-7B-Instruct",
torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
)
Qwen2VLConfig
class transformers.Qwen2VLConfig
< source >( vocab_size = 152064 hidden_size = 8192 intermediate_size = 29568 num_hidden_layers = 80 num_attention_heads = 64 num_key_value_heads = 8 hidden_act = 'silu' max_position_embeddings = 32768 initializer_range = 0.02 rms_norm_eps = 1e-05 use_cache = True tie_word_embeddings = False rope_theta = 1000000.0 use_sliding_window = False sliding_window = 4096 max_window_layers = 80 attention_dropout = 0.0 vision_config = None rope_scaling = None **kwargs )
参数
- vocab_size (
int
, 可选, 默认为 152064) — Qwen2VL 模型的词汇表大小。定义了在调用 Qwen2VLModel 时传递的inputs_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 头应通过平均池化该组内的所有原始头来构建。有关更多详细信息,请查看本文。如果未指定,则默认为32
。 - hidden_act (
str
或function
, 可选, 默认为"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
) — 模型是否应返回最后的 key/values 注意力张量(并非所有模型都使用)。仅当config.is_decoder=True
时相关。 - tie_word_embeddings (
bool
, 可选, 默认为False
) — 模型的输入和输出词嵌入是否应该绑定。 - rope_theta (
float
, 可选, 默认为 1000000.0) — RoPE 嵌入的基础周期。 - use_sliding_window (
bool
, 可选, 默认为False
) — 是否使用滑动窗口注意力。 - sliding_window (
int
, 可选, 默认为 4096) — 滑动窗口注意力 (SWA) 窗口大小。如果未指定,则默认为4096
。 - max_window_layers (
int
, 可选, 默认为 80) — 使用 SWA(滑动窗口注意力)的层数。底层使用 SWA,而顶层使用完整注意力。 - attention_dropout (
float
, 可选, 默认为 0.0) — 注意力概率的 dropout 比率。 - vision_config (
Dict
, 可选) — 用于视觉编码器初始化的配置。 - rope_scaling (
Dict
, 可选) — 包含 RoPE 嵌入缩放配置的字典。注意:如果您应用新的 rope 类型,并且期望模型在更长的max_position_embeddings
上工作,我们建议您相应地更新此值。预期内容:rope_type
(str
):要使用的 RoPE 的子变体。可以是 [‘default’, ‘linear’, ‘dynamic’, ‘yarn’, ‘longrope’, ‘llama3’] 之一,其中 ‘default’ 是原始的 RoPE 实现。factor
(float
, 可选):与除 ‘default’ 之外的所有 rope 类型一起使用。应用于 RoPE 嵌入的缩放因子。在大多数缩放类型中,因子 x 将使模型能够处理长度为 x * 原始最大预训练长度的序列。original_max_position_embeddings
(int
, 可选):与 ‘dynamic’、‘longrope’ 和 ‘llama3’ 一起使用。预训练期间使用的原始最大位置嵌入。attention_factor
(float
, 可选):与 ‘yarn’ 和 ‘longrope’ 一起使用。应用于注意力计算的缩放因子。如果未指定,则默认为实现建议的值,使用factor
字段推断建议的值。beta_fast
(float
, 可选):仅与 ‘yarn’ 一起使用。用于设置线性斜坡函数中外推(仅限)边界的参数。如果未指定,则默认为 32。beta_slow
(float
, 可选):仅与 ‘yarn’ 一起使用。用于设置线性斜坡函数中内插(仅限)边界的参数。如果未指定,则默认为 1。short_factor
(List[float]
, 可选):仅与 ‘longrope’ 一起使用。应用于短上下文(<original_max_position_embeddings
)的缩放因子。必须是数字列表,其长度与隐藏层大小除以注意力头数再除以 2 相同。long_factor
(List[float]
, 可选):仅与 ‘longrope’ 一起使用。应用于长上下文(<original_max_position_embeddings
)的缩放因子。必须是数字列表,其长度与隐藏层大小除以注意力头数再除以 2 相同。low_freq_factor
(float
, 可选):仅与 ‘llama3’ 一起使用。应用于 RoPE 低频分量的缩放因子。high_freq_factor
(float
, 可选):仅与 ‘llama3’ 一起使用。应用于 RoPE 高频分量的缩放因子。
这是用于存储 Qwen2VLModel 配置的配置类。它用于根据指定的参数实例化 Qwen2-VL 模型,定义模型架构。使用默认值实例化配置将产生与 Qwen2-VL-7B-Instruct Qwen/Qwen2-VL-7B-Instruct 类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
>>> from transformers import Qwen2VLForConditionalGeneration, Qwen2VLConfig
>>> # Initializing a Qwen2VL style configuration
>>> configuration = Qwen2VLConfig()
>>> # Initializing a model from the Qwen2-VL-7B style configuration
>>> model = Qwen2VLForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
Qwen2VLImageProcessor
class transformers.Qwen2VLImageProcessor
< source >( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BICUBIC: 3> do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_rgb: bool = True min_pixels: int = None max_pixels: int = None patch_size: int = 14 temporal_patch_size: int = 2 merge_size: int = 2 **kwargs )
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否调整图像(高度,宽度)尺寸。 - size (
Dict[str, int]
, 可选, 默认为{"shortest_edge" -- 56 * 56, "longest_edge": 28 * 28 * 1280}
): 调整大小后图像的尺寸。必须存在shortest_edge
和longest_edge
键。 - resample (
PILImageResampling
, 可选, 默认为Resampling.BICUBIC
) — 调整图像大小时使用的重采样过滤器。 - do_rescale (
bool
, 可选, 默认为True
) — 是否按指定的比例rescale_factor
缩放图像。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 如果缩放图像,则使用的缩放因子。 - do_normalize (
bool
, 可选, 默认为True
) — 是否标准化图像。 - image_mean (
float
或List[float]
, 可选, 默认为[0.48145466, 0.4578275, 0.40821073]
) — 如果标准化图像,则使用的均值。这是一个浮点数或浮点数列表,对应于图像中每个通道。 - image_std (
float
或List[float]
, 可选, 默认为[0.26862954, 0.26130258, 0.27577711]
) — 如果标准化图像,则使用的标准差。这是一个浮点数或浮点数列表,对应于图像中每个通道。 - do_convert_rgb (
bool
, 可选, 默认为True
) — 是否将图像转换为 RGB 格式。 - min_pixels (
int
, 可选, 默认为56 * 56
) — 调整图像大小的最小像素数。 - max_pixels (
int
, 可选, 默认为28 * 28 * 1280
) — 调整图像大小的最大像素数。 - patch_size (
int
, 可选, 默认为 14) — 视觉编码器的空间 patch 大小。 - temporal_patch_size (
int
, 可选, 默认为 2) — 视觉编码器的时间 patch 大小。 - merge_size (
int
, 可选, 默认为 2) — 视觉编码器到 llm 编码器的合并大小。
构建 Qwen2-VL 图像处理器,该处理器根据原始图像动态调整图像大小。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] videos: typing.Union[list['PIL.Image.Image'], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), list['np.ndarray'], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list['np.ndarrray']], list[list['torch.Tensor']]] = None do_resize: bool = None size: typing.Dict[str, int] = None min_pixels: int = None max_pixels: int = None resample: Resampling = None do_rescale: bool = None rescale_factor: float = None do_normalize: bool = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None patch_size: int = None temporal_patch_size: int = None merge_size: int = None do_convert_rgb: bool = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None )
参数
- images (
ImageInput
) — 要预处理的图像。 期望输入像素值范围为 0 到 255 的单张或一批图像。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False
。 - videos (
VideoInput
) — 要预处理的视频。 期望输入像素值范围为 0 到 255 的单张或一批视频。如果传入的视频像素值在 0 到 1 之间,请设置do_rescale=False
。 - do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, 可选, 默认为self.size
) — 调整大小后图像的尺寸。 图像的最短边将调整为 size[“shortest_edge”],最长边将调整大小以保持输入宽高比。 - resample (
int
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样过滤器。 这可以是枚举PILImageResampling
之一。 仅当do_resize
设置为True
时才有效。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否缩放图像。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于缩放图像的缩放因子。 - do_normalize (
bool
, 可选, 默认为self.do_normalize
) — 是否标准化图像。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 用于归一化的图像均值。仅当do_normalize
设置为True
时有效。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 用于归一化的图像标准差。仅当do_normalize
设置为True
时有效。 - min_pixels (
int
, 可选, 默认为self.min_pixels
) — 调整图像大小的最小像素数。 - max_pixels (
int
, 可选, 默认为self.max_pixels
) — 调整图像大小的最大像素数。 - patch_size (
int
, 可选, 默认为self.patch_size
) — 视觉编码器的空间 patch 大小。 - temporal_patch_size (
int
, 可选, 默认为self.temporal_patch_size
) — 视觉编码器的时间 patch 大小。 - merge_size (
int
, 可选, 默认为self.merge_size
) — 视觉编码器到 llm 编码器的合并大小。 - do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
或TensorType
, 可选) — 返回张量的类型。可以是以下之一:- Unset: 返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
: 返回tf.Tensor
类型的批次。TensorType.PYTORCH
或'pt'
: 返回torch.Tensor
类型的批次。TensorType.NUMPY
或'np'
: 返回np.ndarray
类型的批次。TensorType.JAX
或'jax'
: 返回jax.numpy.ndarray
类型的批次。
- Unset: 返回
- data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- Unset: 使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
Qwen2VLImageProcessorFast
class transformers.Qwen2VLImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.models.qwen2_vl.image_processing_qwen2_vl_fast.Qwen2VLFastImageProcessorKwargs] )
参数
- do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否将图像的 (height, width) 尺寸调整为指定的size
。可以被preprocess
方法中的do_resize
参数覆盖。 - size (
dict
, 可选, 默认为self.size
) — 调整大小后输出图像的大小。可以被preprocess
方法中的size
参数覆盖。 - default_to_square (
bool
, 可选, 默认为self.default_to_square
) — 如果 size 是整数,是否默认调整为方形图像。 - resample (
PILImageResampling
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样滤波器。仅当do_resize
设置为True
时有效。可以被preprocess
方法中的resample
参数覆盖。 - do_center_crop (
bool
, 可选, 默认为self.do_center_crop
) — 是否将图像中心裁剪为指定的crop_size
。可以被preprocess
方法中的do_center_crop
覆盖。 - crop_size (
Dict[str, int]
可选, 默认为self.crop_size
) — 应用center_crop
后输出图像的大小。可以被preprocess
方法中的crop_size
覆盖。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否按指定的比例rescale_factor
缩放图像。可以被preprocess
方法中的do_rescale
参数覆盖。 - rescale_factor (
int
或float
, 可选, 默认为self.rescale_factor
) — 缩放图像时使用的比例因子。仅当do_rescale
设置为True
时有效。可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_normalize (
bool
, 可选, 默认为self.do_normalize
) — 是否对图像进行归一化。可以被preprocess
方法中的do_normalize
参数覆盖。可以被preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,其长度为图像中通道的数量。可以被preprocess
方法中的image_mean
参数覆盖。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或浮点数列表,其长度为图像中通道的数量。可以被preprocess
方法中的image_std
参数覆盖。可以被preprocess
方法中的image_std
参数覆盖。 - do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
或TensorType
, 可选, 默认为self.return_tensors
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
ChannelDimension
或str
, 可选, 默认为self.data_format
) — 仅支持ChannelDimension.FIRST
。为了与慢速处理器兼容而添加。 - input_data_format (
ChannelDimension
或str
, 可选, 默认为self.input_data_format
) — 输入图像的通道维度格式。如果未设置,则通道维度格式将从输入图像中推断。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:图像格式为 (height, width)。
- device (
torch.device
, 可选, 默认为self.device
) — 处理图像的设备。如果未设置,则设备从输入图像中推断。 - min_pixels (
int
, 可选, 默认为56 * 56
) — 调整图像大小的最小像素数。 - max_pixels (
int
, 可选, 默认为28 * 28 * 1280
) — 调整图像大小的最大像素数。 - patch_size (
int
, 可选, 默认为 14) — 视觉编码器的空间 patch 大小。 - temporal_patch_size (
int
, 可选, 默认为 2) — 视觉编码器的时间 patch 大小。 - merge_size (
int
, 可选, 默认为 2) — 视觉编码器到 llm 编码器的合并大小。
构建一个快速 Qwen2-VL 图像处理器,该处理器基于原始图像动态调整图像大小。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] videos: typing.Union[list['PIL.Image.Image'], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), list['np.ndarray'], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list['np.ndarrray']], list[list['torch.Tensor']]] = None do_resize: bool = None size: typing.Dict[str, int] = None resample: typing.Union[ForwardRef('PILImageResampling'), ForwardRef('F.InterpolationMode'), NoneType] = None do_rescale: bool = None rescale_factor: float = None do_normalize: bool = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None min_pixels: int = None max_pixels: int = None patch_size: int = None temporal_patch_size: int = None merge_size: int = None do_convert_rgb: bool = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None device: typing.Optional[ForwardRef('torch.device')] = None **kwargs )
参数
- images (
ImageInput
) — 要预处理的图像。 期望单个或批量的图像,像素值范围为 0 到 255。 如果传入像素值在 0 到 1 之间的图像,请设置do_rescale=False
。 - videos (
VideoInput
) — 要预处理的视频。 期望单个或批量的视频,像素值范围为 0 到 255。 如果传入像素值在 0 到 1 之间的视频,请设置do_rescale=False
。 - do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, 可选, 默认为self.size
) — 调整大小后图像的尺寸。 必须存在shortest_edge
和longest_edge
键。 - resample (
int
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样滤波器。 这可以是枚举PILImageResampling
之一。 仅当do_resize
设置为True
时才有效。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否重新缩放图像。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的缩放因子。 - do_normalize (
bool
, 可选, 默认为self.do_normalize
) — 是否标准化图像。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 用于标准化的图像均值。 仅当do_normalize
设置为True
时才有效。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 用于标准化的图像标准差。 仅当do_normalize
设置为True
时才有效。 - min_pixels (
int
, 可选, 默认为self.min_pixels
) — 调整图像大小的最小像素数。 - max_pixels (
int
, 可选, 默认为self.max_pixels
) — 调整图像大小的最大像素数。 - patch_size (
int
, 可选, 默认为self.patch_size
) — 视觉编码器的空间 patch 大小。 - temporal_patch_size (
int
, 可选, 默认为self.temporal_patch_size
) — 视觉编码器的时间 patch 大小。 - merge_size (
int
, 可选, 默认为self.merge_size
) — 视觉编码器到llm编码器的合并大小。 - do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为RGB格式。 - return_tensors (
str
或TensorType
, 可选) — 返回张量的类型。 可以是以下之一:- Unset: 返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
: 返回tf.Tensor
类型的批次。TensorType.PYTORCH
或'pt'
: 返回torch.Tensor
类型的批次。TensorType.NUMPY
或'np'
: 返回np.ndarray
类型的批次。TensorType.JAX
或'jax'
: 返回jax.numpy.ndarray
类型的批次。
- Unset: 返回
- data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。 可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- Unset: 使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。 如果未设置,则通道维度格式从输入图像中推断。 可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
- device (
torch.device
, 可选) — 处理图像的设备。 如果未设置,则设备从输入图像中推断。
Qwen2VLProcessor
class transformers.Qwen2VLProcessor
< source >( image_processor = None tokenizer = None chat_template = None **kwargs )
参数
- image_processor (Qwen2VLImageProcessor, 可选) — 图像处理器是必需的输入。
- tokenizer (Qwen2TokenizerFast, 可选) — 分词器是必需的输入。
- chat_template (
str
, 可选) — Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。
构建一个 Qwen2-VL 处理器,它将 Qwen2-VL 图像处理器和 Qwen2 分词器包装到单个处理器中。Qwen2VLProcessor 提供 Qwen2VLImageProcessor 和 Qwen2TokenizerFast 的所有功能。 有关更多信息,请参阅 __call__()
和 decode()。
此方法将其所有参数转发到 Qwen2TokenizerFast 的 batch_decode()。 有关更多信息,请参阅此方法的文档字符串。
此方法将其所有参数转发到 Qwen2TokenizerFast 的 decode()。 有关更多信息,请参阅此方法的文档字符串。
post_process_image_text_to_text
< source >( generated_outputs skip_special_tokens = True clean_up_tokenization_spaces = False **kwargs ) → List[str]
参数
- generated_outputs (
torch.Tensor
或np.ndarray
) — 模型generate
函数的输出。 预期输出是形状为(batch_size, sequence_length)
或(sequence_length,)
的张量。 - skip_special_tokens (
bool
, 可选, 默认为True
) — 是否删除输出中的特殊 token。 传递给分词器的batch_decode
方法的参数。 - Clean_up_tokenization_spaces (
bool
, 可选, 默认为False
) — 是否清理分词空格。 传递给分词器的batch_decode
方法的参数。 - **kwargs — 要传递给分词器的
batch_decode method
的其他参数。
返回
List[str]
解码后的文本。
后处理模型的输出以解码文本。
Qwen2VLModel
class transformers.Qwen2VLModel
< source >( config: Qwen2VLConfig )
参数
- config (Qwen2VLConfig) — 具有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
裸 Qwen2VL 模型,输出原始隐藏状态,顶部没有任何特定的 head。 此模型继承自 PreTrainedModel。 查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。
此模型也是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。
forward
< source >( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None )
Qwen2VLForConditionalGeneration
forward
< source >( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None pixel_values: typing.Optional[torch.Tensor] = None pixel_values_videos: typing.Optional[torch.FloatTensor] = None image_grid_thw: typing.Optional[torch.LongTensor] = None video_grid_thw: typing.Optional[torch.LongTensor] = None rope_deltas: typing.Optional[torch.LongTensor] = None cache_position: typing.Optional[torch.LongTensor] = None ) → transformers.models.qwen2_vl.modeling_qwen2_vl.Qwen2VLCausalLMOutputWithPast
或 tuple(torch.FloatTensor)
参数
- input_ids (形状为
(batch_size, sequence_length)
的torch.LongTensor
) — 词汇表中输入序列令牌的索引。如果您提供填充,默认情况下填充将被忽略。索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (形状为
(batch_size, sequence_length)
的torch.Tensor
,可选) — 用于避免在填充令牌索引上执行注意力的掩码。掩码值在[0, 1]
中选择:- 1 表示令牌未被掩蔽,
- 0 表示令牌被掩蔽。
索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
如果使用
past_key_values
,则可以选择仅输入最后一个decoder_input_ids
(请参阅past_key_values
)。如果您想更改填充行为,您应该阅读
modeling_opt._prepare_decoder_attention_mask
并根据您的需求进行修改。有关默认策略的更多信息,请参见 论文 中的图 1。- 1 表示 head 未被掩蔽,
- 0 表示 head 被掩蔽。
- position_ids (形状为
(batch_size, sequence_length)
的torch.LongTensor
,可选) — 每个输入序列令牌在位置嵌入中的位置索引。在范围[0, config.n_positions - 1]
中选择。什么是位置 IDs? - past_key_values (
tuple(tuple(torch.FloatTensor))
,可选,当传递use_cache=True
或config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(tuple(torch.FloatTensor))
元组,其中每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量和 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的额外张量。包含预先计算的隐藏状态(自注意力模块和交叉注意力模块中的键和值),可以用于(参见
past_key_values
输入)加速顺序解码。如果使用
past_key_values
,用户可以选择仅输入最后一个decoder_input_ids
(那些没有将其过去的键值状态提供给此模型的),形状为(batch_size, 1)
,而不是所有形状为(batch_size, sequence_length)
的decoder_input_ids
。 - inputs_embeds (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
,可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - use_cache (
bool
,可选) — 如果设置为True
,则返回past_key_values
键值状态,并且可以用于加速解码(请参阅past_key_values
)。 - output_attentions (
bool
,可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通元组。 - pixel_values (形状为 `(seq_length, num_channels image_size image_size)` 的
torch.FloatTensor
) — 与输入图像相对应的张量。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 Qwen2VLImageProcessor.call()。Qwen2VLProcessor 使用 Qwen2VLImageProcessor 处理图像。 - pixel_values_videos (形状为 `(seq_length, num_channels temporal_size image_size * image_size)` 的
torch.FloatTensor
) — 与输入视频相对应的张量。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 Qwen2VLImageProcessor.call()。Qwen2VLProcessor 使用 Qwen2VLImageProcessor 处理视频。 - image_grid_thw (形状为
(num_images, 3)
的torch.LongTensor
,可选) — LLM 中每个图像的特征形状的时间、高度和宽度。 - video_grid_thw (形状为
(num_videos, 3)
的torch.LongTensor
,可选) — LLM 中每个视频的特征形状的时间、高度和宽度。 - rope_deltas (形状为
(batch_size, )
的torch.LongTensor
,可选) — 序列长度和多模态 rope 之间的 rope 索引差异。 - labels (形状为
(batch_size, sequence_length)
的torch.LongTensor
,可选) — 用于计算掩码语言建模损失的标签。索引应为[0, ..., config.vocab_size]
或 -100(请参阅input_ids
文档字符串)。索引设置为-100
的令牌将被忽略(掩码),损失仅针对标签在[0, ..., config.vocab_size]
中的令牌计算。
返回
transformers.models.qwen2_vl.modeling_qwen2_vl.Qwen2VLCausalLMOutputWithPast
或 tuple(torch.FloatTensor)
一个 transformers.models.qwen2_vl.modeling_qwen2_vl.Qwen2VLCausalLMOutputWithPast
或 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (Qwen2VLConfig) 和输入。
-
loss (形状为
(1,)
的torch.FloatTensor
,可选,当提供labels
时返回) — 语言建模损失(用于下一个令牌预测)。 -
logits (形状为
(batch_size, sequence_length, config.vocab_size)
的torch.FloatTensor
) — 语言建模头的预测分数(SoftMax 之前每个词汇表令牌的分数)。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(tuple(torch.FloatTensor))
元组,其中每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量)包含预先计算的隐藏状态(自注意力模块中的键和值),可以用于(参见
past_key_values
输入)加速顺序解码。 -
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 之后的注意力权重,用于计算自注意力头中的加权平均值。
-
rope_deltas (形状为
(batch_size, )
的torch.LongTensor
,可选) — 序列长度和多模态 rope 之间的 rope 索引差异。
Qwen2VLForConditionalGeneration forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
>>> model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
>>> messages = [
{
"role": "user",
"content": [
{"type": "image"},
{"type": "text", "text": "What is shown in this image?"},
],
},
]
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
>>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."