Transformers documentation
Qwen2-VL
Qwen2-VL
Overview
Qwen2-VL ๋ชจ๋ธ์ ์๋ฆฌ๋ฐ๋ฐ ๋ฆฌ์์น์ Qwenํ์์ ๊ฐ๋ฐํ Qwen-VL ๋ชจ๋ธ์ ์ฃผ์ ์ ๋ฐ์ดํธ ๋ฒ์ ์ ๋๋ค.
๋ธ๋ก๊ทธ์ ์์ฝ์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค:
์ด ๋ธ๋ก๊ทธ๋ ์ง๋ ๋ช ๋ ๊ฐ Qwen-VL์์ ์ค๋ํ ๊ฐ์ ์ ๊ฑฐ์ณ ๋ฐ์ ๋ Qwen2-VL ๋ชจ๋ธ์ ์๊ฐํฉ๋๋ค. ์ค์ ๊ฐ์ ์ฌํญ์ ํฅ์๋ ์ด๋ฏธ์ง ์ดํด, ๊ณ ๊ธ ๋น๋์ค ์ดํด, ํตํฉ ์๊ฐ ์์ด์ ํธ ๊ธฐ๋ฅ, ํ์ฅ๋ ๋ค์ธ์ด ์ง์์ ํฌํจํ๊ณ ์์ต๋๋ค.๋ชจ๋ธ ์ํคํ ์ฒ๋ Naive Dynamic Resolution ์ง์์ ํตํด ์์์ ์ด๋ฏธ์ง ํด์๋๋ฅผ ์ฒ๋ฆฌํ ์ ์๋๋ก ์ต์ ํ๋์์ผ๋ฉฐ, ๋ฉํฐ๋ชจ๋ฌ ํ์ ์์น ์๋ฒ ๋ฉ(M-ROPE)์ ํ์ฉํ์ฌ 1D ํ ์คํธ์ ๋ค์ฐจ์ ์๊ฐ ๋ฐ์ดํฐ๋ฅผ ํจ๊ณผ์ ์ผ๋ก ์ฒ๋ฆฌํฉ๋๋ค. ์ด ์ ๋ฐ์ดํธ๋ ๋ชจ๋ธ์ ์๊ฐ ๊ด๋ จ ์์ ์์ GPT-4o์ Claude 3.5 Sonnet ๊ฐ์ ์ ๋์ ์ธ AI ์์คํ ๊ณผ ๊ฒฝ์๋ ฅ ์๋ ์ฑ๋ฅ์ ๋ณด์ฌ์ฃผ๋ฉฐ, ํ ์คํธ ๋ฅ๋ ฅ์์๋ ์คํ์์ค ๋ชจ๋ธ ์ค ์์๊ถ์ ๋ญํฌ๋์ด ์์ต๋๋ค. ์ด๋ฌํ ๋ฐ์ ์ Qwen2-VL์ ๊ฐ๋ ฅํ ๋ฉํฐ๋ชจ๋ฌ ์ฒ๋ฆฌ ๋ฐ ์ถ๋ก ๋ฅ๋ ฅ์ด ํ์ํ ๋ค์ํ ์์ฉ ๋ถ์ผ์์ ํ์ฉํ ์ ์๋ ๋ค์ฌ๋ค๋ฅํ ๋๊ตฌ๋ก ๋ง๋ค์ด์ค๋๋ค.
์ด ๋ชจ๋ธ์ simonJJJ์ ์ํด ๊ธฐ์ฌ๋์์ต๋๋ค.
์ฌ์ฉ ์์
๋จ์ผ ๋ฏธ๋์ด ์ถ๋ก
์ด ๋ชจ๋ธ์ ์ด๋ฏธ์ง์ ๋น๋์ค๋ฅผ ๋ชจ๋ ์ธํ์ผ๋ก ๋ฐ์ ์ ์์ต๋๋ค. ๋ค์์ ์ถ๋ก ์ ์ํ ์์ ์ฝ๋์ ๋๋ค.
import torch
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
# ์ฌ์ฉ ๊ฐ๋ฅํ ์ฅ์น์์ ๋ชจ๋ธ์ ๋ฐ ์ ๋ฐ๋(half-precision)๋ก ๋ก๋
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)
# ์ถ๋ก : ์์ํ ์์ฑ
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 = [
{
"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)
# ์ถ๋ก : ์์ํ ์์ฑ
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)
๋ฐฐ์น ํผํฉ ๋ฏธ๋์ด ์ถ๋ก
์ด ๋ชจ๋ธ์ ์ด๋ฏธ์ง, ๋น๋์ค, ํ ์คํธ ๋ฑ ๋ค์ํ ์ ํ์ ๋ฐ์ดํฐ๋ฅผ ํผํฉํ์ฌ ๋ฐฐ์น ์ ๋ ฅ์ผ๋ก ์ฒ๋ฆฌํ ์ ์์ต๋๋ค. ๋ค์์ ์์ ์ ๋๋ค.
# ์ฒซ๋ฒ์งธ ์ด๋ฏธ์ง์ ๋ํ ๋ํ
conversation1 = [
{
"role": "user",
"content": [
{"type": "image", "path": "/path/to/image1.jpg"},
{"type": "text", "text": "Describe this image."}
]
}
]
# ๋ ๊ฐ์ ์ด๋ฏธ์ง์ ๋ํ ๋ํ
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?"}
]
}
]
# ์์ ํ
์คํธ๋ก๋ง ์ด๋ฃจ์ด์ง ๋ํ
conversation3 = [
{
"role": "user",
"content": "who are you?"
}
]
# ํผํฉ๋ ๋ฏธ๋์ด๋ก ์ด๋ฃจ์ด์ง ๋ํ
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]
# ๋ฐฐ์น ์ถ๋ก ์ ์ํ ์ค๋น
ipnuts = processor.apply_chat_template(
conversations,
fps=1,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt"
).to(model.device)
# ๋ฐฐ์น ์ถ๋ก
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)
์ฌ์ฉ ํ
์ด๋ฏธ์ง ํด์๋ ํธ๋ ์ด๋์คํ
์ด ๋ชจ๋ธ์ ๋ค์ํ ํด์๋์ ์ ๋ ฅ์ ์ง์ํฉ๋๋ค. ๋ํดํธ๋ก ์ ๋ ฅ์ ๋ํด ๋ค์ดํฐ๋ธ(native) ํด์๋๋ฅผ ์ฌ์ฉํ์ง๋ง, ๋ ๋์ ํด์๋๋ฅผ ์ ์ฉํ๋ฉด ์ฑ๋ฅ์ด ํฅ์๋ ์ ์์ต๋๋ค. ๋ค๋ง, ์ด๋ ๋ ๋ง์ ์ฐ์ฐ ๋น์ฉ์ ์ด๋ํฉ๋๋ค. ์ฌ์ฉ์๋ ์ต์ ์ ์ค์ ์ ์ํด ์ต์ ๋ฐ ์ต๋ ํฝ์ ์๋ฅผ ์กฐ์ ํ ์ ์์ต๋๋ค.
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 RAM์ ๊ฒฝ์ฐ, ๋ค์๊ณผ ๊ฐ์ด ํด์๋๋ฅผ ์ค์ผ ์ ์์ต๋๋ค:
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๊ฐ์ ํ ํฐ์ผ๋ก ์ธ์ฝ๋ฉ๋ฉ๋๋ค. ์ฌ๊ธฐ์ 28์ ๋ชจ๋ธ์ด 14 ํฌ๊ธฐ์ ํจ์น(patch)์ 2์ ์๊ฐ ํจ์น(temporal patch size)๋ฅผ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ ๋์จ ๊ฐ์ ๋๋ค (14 ร 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?"
}
]
# ๋ํดํธ:
prompt_without_id = processor.apply_chat_template(conversation, add_generation_prompt=True)
# ์์ ์์ํ: '<|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'
# id ์ถ๊ฐ
prompt_with_id = processor.apply_chat_template(conversation, add_generation_prompt=True, add_vision_id=True)
# ์์ ์์ํ: '<|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 repository์์ ํ์ธํ ์ ์์ต๋๋ค. 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",
dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
)
Qwen2VLConfig
class transformers.Qwen2VLConfig
< source >( text_config = None vision_config = None image_token_id = 151655 video_token_id = 151656 **kwargs )
Parameters
- text_config (
Union[PreTrainedConfig, dict]
, optional, defaults toQwen2_5_VLTextConfig
) — The config object or dictionary of the text backbone. - vision_config (
Union[PreTrainedConfig, dict]
, optional, defaults toQwen2_5_VLVisionConfig
) — The config object or dictionary of the vision backbone. - image_token_id (
int
, optional, defaults to 151655) — The image token index to encode the image prompt. - video_token_id (
int
, optional, defaults to 151656) — The video token index to encode the image prompt.
This is the configuration class to store the configuration of a Qwen2VLModel. It is used to instantiate a Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of Qwen2-VL-7B-Instruct Qwen/Qwen2-VL-7B-Instruct.
Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
>>> 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.config
Qwen2VLImageProcessor
class transformers.Qwen2VLImageProcessor
< source >( do_resize: bool = True size: typing.Optional[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, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_convert_rgb: bool = True min_pixels: typing.Optional[int] = None max_pixels: typing.Optional[int] = None patch_size: int = 14 temporal_patch_size: int = 2 merge_size: int = 2 **kwargs )
Parameters
- do_resize (
bool
, optional, defaults toTrue
) — Whether to resize the image’s (height, width) dimensions. - size (
dict[str, int]
, optional, defaults to{"shortest_edge" -- 56 * 56, "longest_edge": 28 * 28 * 1280}
): Size of the image after resizing.shortest_edge
andlongest_edge
keys must be present. - resample (
PILImageResampling
, optional, defaults toResampling.BICUBIC
) — Resampling filter to use when resizing the image. - do_rescale (
bool
, optional, defaults toTrue
) — Whether to rescale the image by the specified scalerescale_factor
. - rescale_factor (
int
orfloat
, optional, defaults to1/255
) — Scale factor to use if rescaling the image. - do_normalize (
bool
, optional, defaults toTrue
) — Whether to normalize the image. - image_mean (
float
orlist[float]
, optional, defaults to[0.48145466, 0.4578275, 0.40821073]
) — Mean to use if normalizing the image. This is a float or list of floats for each channel in the image. - image_std (
float
orlist[float]
, optional, defaults to[0.26862954, 0.26130258, 0.27577711]
) — Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image. - do_convert_rgb (
bool
, optional, defaults toTrue
) — Whether to convert the image to RGB. - min_pixels (
int
, optional, defaults to56 * 56
) — The min pixels of the image to resize the image. - max_pixels (
int
, optional, defaults to28 * 28 * 1280
) — The max pixels of the image to resize the image. - patch_size (
int
, optional, defaults to 14) — The spatial patch size of the vision encoder. - temporal_patch_size (
int
, optional, defaults to 2) — The temporal patch size of the vision encoder. - merge_size (
int
, optional, defaults to 2) — The merge size of the vision encoder to llm encoder.
Constructs a Qwen2-VL image processor that dynamically resizes images based on the original images.
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'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = None do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None min_pixels: typing.Optional[int] = None max_pixels: typing.Optional[int] = None resample: typing.Optional[PIL.Image.Resampling] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None patch_size: typing.Optional[int] = None temporal_patch_size: typing.Optional[int] = None merge_size: typing.Optional[int] = None do_convert_rgb: typing.Optional[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[str, transformers.image_utils.ChannelDimension, NoneType] = None )
Parameters
- images (
ImageInput
) — Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, setdo_rescale=False
. - videos (
VideoInput
) — Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If passing in videos with pixel values between 0 and 1, setdo_rescale=False
. - do_resize (
bool
, optional, defaults toself.do_resize
) — Whether to resize the image. - size (
dict[str, int]
, optional, defaults toself.size
) — Size of the image after resizing. Shortest edge of the image is resized to size[“shortest_edge”], with the longest edge resized to keep the input aspect ratio. - resample (
int
, optional, defaults toself.resample
) — Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling
. Only has an effect ifdo_resize
is set toTrue
. - do_rescale (
bool
, optional, defaults toself.do_rescale
) — Whether to rescale the image. - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — Rescale factor to rescale the image by ifdo_rescale
is set toTrue
. - do_normalize (
bool
, optional, defaults toself.do_normalize
) — Whether to normalize the image. - image_mean (
float
orlist[float]
, optional, defaults toself.image_mean
) — Image mean to use for normalization. Only has an effect ifdo_normalize
is set toTrue
. - image_std (
float
orlist[float]
, optional, defaults toself.image_std
) — Image standard deviation to use for normalization. Only has an effect ifdo_normalize
is set toTrue
. - min_pixels (
int
, optional, defaults toself.min_pixels
) — The min pixels of the image to resize the image. - max_pixels (
int
, optional, defaults toself.max_pixels
) — The max pixels of the image to resize the image. - patch_size (
int
, optional, defaults toself.patch_size
) — The spatial patch size of the vision encoder. - temporal_patch_size (
int
, optional, defaults toself.temporal_patch_size
) — The temporal patch size of the vision encoder. - merge_size (
int
, optional, defaults toself.merge_size
) — The merge size of the vision encoder to llm encoder. - do_convert_rgb (
bool
, optional, defaults toself.do_convert_rgb
) — Whether to convert the image to RGB. - return_tensors (
str
orTensorType
, optional) — The type of tensors to return. Can be one of:- Unset: Return a list of
np.ndarray
. TensorType.PYTORCH
or'pt'
: Return a batch of typetorch.Tensor
.TensorType.NUMPY
or'np'
: Return a batch of typenp.ndarray
.
- Unset: Return a list of
- data_format (
ChannelDimension
orstr
, optional, defaults toChannelDimension.FIRST
) — The channel dimension format for the output image. Can be one of:"channels_first"
orChannelDimension.FIRST
: image in (num_channels, height, width) format."channels_last"
orChannelDimension.LAST
: image in (height, width, num_channels) format.- Unset: Use the channel dimension format of the input image.
- input_data_format (
ChannelDimension
orstr
, optional) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:"channels_first"
orChannelDimension.FIRST
: image in (num_channels, height, width) format."channels_last"
orChannelDimension.LAST
: image in (height, width, num_channels) format."none"
orChannelDimension.NONE
: image in (height, width) format.
Qwen2VLImageProcessorFast
class transformers.Qwen2VLImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.models.qwen2_vl.image_processing_qwen2_vl_fast.Qwen2VLFastImageProcessorKwargs] )
Constructs a fast Qwen2 Vl image processor.
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'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = None **kwargs: typing_extensions.Unpack[transformers.models.qwen2_vl.image_processing_qwen2_vl_fast.Qwen2VLFastImageProcessorKwargs] ) โ <class 'transformers.image_processing_base.BatchFeature'>
Parameters
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]
) — Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, setdo_rescale=False
. - 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]], NoneType]
) — Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If passing in videos with pixel values between 0 and 1, setdo_rescale=False
. - do_resize (
bool
, optional) — Whether to resize the image. - size (
dict[str, int]
, optional) — Describes the maximum input dimensions to the model. - default_to_square (
bool
, optional) — Whether to default to a square image when resizing, if size is an int. - resample (
Union[PILImageResampling, F.InterpolationMode, NoneType]
) — Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling
. Only has an effect ifdo_resize
is set toTrue
. - do_center_crop (
bool
, optional) — Whether to center crop the image. - crop_size (
dict[str, int]
, optional) — Size of the output image after applyingcenter_crop
. - do_rescale (
bool
, optional) — Whether to rescale the image. - rescale_factor (
Union[int, float, NoneType]
) — Rescale factor to rescale the image by ifdo_rescale
is set toTrue
. - do_normalize (
bool
, optional) — Whether to normalize the image. - image_mean (
Union[float, list[float], NoneType]
) — Image mean to use for normalization. Only has an effect ifdo_normalize
is set toTrue
. - image_std (
Union[float, list[float], NoneType]
) — Image standard deviation to use for normalization. Only has an effect ifdo_normalize
is set toTrue
. - do_pad (
bool
, optional) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
dict[str, int]
, optional) — The size in{"height": int, "width" int}
to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_size
is not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True.
- do_convert_rgb (
bool
, optional) — Whether to convert the image to RGB. - return_tensors (
Union[str, ~utils.generic.TensorType, NoneType]
) — Returns stacked tensors if set to `pt, otherwise returns a list of tensors. - data_format (
~image_utils.ChannelDimension
, optional) — OnlyChannelDimension.FIRST
is supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension, NoneType]
) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:"channels_first"
orChannelDimension.FIRST
: image in (num_channels, height, width) format."channels_last"
orChannelDimension.LAST
: image in (height, width, num_channels) format."none"
orChannelDimension.NONE
: image in (height, width) format.
- device (
torch.device
, optional) — The device to process the images on. If unset, the device is inferred from the input images. - disable_grouping (
bool
, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - min_pixels (
int
, optional, defaults to56 * 56
) — The min pixels of the image to resize the image. - max_pixels (
int
, optional, defaults to28 * 28 * 1280
) — The max pixels of the image to resize the image. - patch_size (
int
, optional, defaults to 14) — The spatial patch size of the vision encoder. - temporal_patch_size (
int
, optional, defaults to 2) — The temporal patch size of the vision encoder. - merge_size (
int
, optional, defaults to 2) — The merge size of the vision encoder to llm encoder.
Returns
<class 'transformers.image_processing_base.BatchFeature'>
- data (
dict
) โ Dictionary of lists/arrays/tensors returned by the call method (โpixel_valuesโ, etc.). - tensor_type (
Union[None, str, TensorType]
, optional) โ You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
Qwen2VLProcessor
class transformers.Qwen2VLProcessor
< source >( image_processor = None tokenizer = None video_processor = None chat_template = None **kwargs )
Parameters
- image_processor (Qwen2VLImageProcessor, optional) — The image processor is a required input.
- tokenizer (
Qwen2TokenizerFast
, optional) — The tokenizer is a required input. - video_processor (
Qwen2VLVideoProcessor
, optional) — The video processor is a required input. - chat_template (
str
, optional) — A Jinja template which will be used to convert lists of messages in a chat into a tokenizable string.
Constructs a Qwen2-VL processor which wraps a Qwen2-VL image processor and a Qwen2 tokenizer into a single processor.
Qwen2VLProcessor offers all the functionalities of Qwen2VLImageProcessor and Qwen2TokenizerFast
. See the
__call__()
and decode() for more information.
post_process_image_text_to_text
< source >( generated_outputs skip_special_tokens = True clean_up_tokenization_spaces = False **kwargs ) โ list[str]
Parameters
- generated_outputs (
torch.Tensor
ornp.ndarray
) — The output of the modelgenerate
function. The output is expected to be a tensor of shape(batch_size, sequence_length)
or(sequence_length,)
. - skip_special_tokens (
bool
, optional, defaults toTrue
) — Whether or not to remove special tokens in the output. Argument passed to the tokenizer’sbatch_decode
method. - clean_up_tokenization_spaces (
bool
, optional, defaults toFalse
) — Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer’sbatch_decode
method. - **kwargs —
Additional arguments to be passed to the tokenizer’s
batch_decode method
.
Returns
list[str]
The decoded text.
Post-process the output of the model to decode the text.
Qwen2VLModel
class transformers.Qwen2VLModel
< source >( config: Qwen2VLConfig )
Parameters
- config (Qwen2VLConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The bare Qwen2 Vl Model outputting raw hidden-states without any specific head on top.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[transformers.cache_utils.Cache] = 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 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 **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) โ transformers.models.qwen2_vl.modeling_qwen2_vl.Qwen2VLModelOutputWithPast
or tuple(torch.FloatTensor)
Parameters
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]
. - past_key_values (
~cache_utils.Cache
, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_values
returned by the model at a previous stage of decoding, whenuse_cache=True
orconfig.use_cache=True
.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_values
are passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_values
are used, the user is expected to input only unprocessedinput_ids
(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)
instead of allinput_ids
of shape(batch_size, sequence_length)
. - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_ids
indices into associated vectors than the model’s internal embedding lookup matrix. - use_cache (
bool
, optional) — If set toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
). - output_attentions (
bool
, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail. - output_hidden_states (
bool
, optional) — Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail. - return_dict (
bool
, optional) — Whether or not to return a ModelOutput instead of a plain tuple. - pixel_values (
torch.Tensor
of shape(batch_size, num_channels, image_size, image_size)
, optional) — The tensors corresponding to the input images. Pixel values can be obtained using Qwen2VLImageProcessor. See Qwen2VLImageProcessor.call() for details (Qwen2VLProcessor uses Qwen2VLImageProcessor for processing images). - pixel_values_videos (
torch.FloatTensor
of shape(batch_size, num_frames, num_channels, frame_size, frame_size)
, optional) — The tensors corresponding to the input video. Pixel values for videos can be obtained usingQwen2VLVideoProcessor
. SeeQwen2VLVideoProcessor.__call__()
for details (Qwen2VLProcessor usesQwen2VLVideoProcessor
for processing videos). - image_grid_thw (
torch.LongTensor
of shape(num_images, 3)
, optional) — The temporal, height and width of feature shape of each image in LLM. - video_grid_thw (
torch.LongTensor
of shape(num_videos, 3)
, optional) — The temporal, height and width of feature shape of each video in LLM. - rope_deltas (
torch.LongTensor
of shape(batch_size, )
, optional) — The rope index difference between sequence length and multimodal rope. - cache_position (
torch.LongTensor
of shape(sequence_length)
, optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids
, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
Returns
transformers.models.qwen2_vl.modeling_qwen2_vl.Qwen2VLModelOutputWithPast
or tuple(torch.FloatTensor)
A transformers.models.qwen2_vl.modeling_qwen2_vl.Qwen2VLModelOutputWithPast
or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (Qwen2VLConfig) and inputs.
-
last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional, defaults toNone
) โ Sequence of hidden-states at the output of the last layer of the model. -
past_key_values (
Cache
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) โ It is a Cache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
past_key_values
input) to speed up sequential decoding. -
hidden_states (
tuple[torch.FloatTensor]
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) โ Tuple oftorch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
-
attentions (
tuple[torch.FloatTensor]
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) โ Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
-
rope_deltas (
torch.LongTensor
of shape(batch_size, )
, optional) โ The rope index difference between sequence length and multimodal rope.
The Qwen2VLModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Qwen2VLForConditionalGeneration
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[transformers.cache_utils.Cache] = 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 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 **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) โ transformers.models.qwen2_vl.modeling_qwen2_vl.Qwen2VLCausalLMOutputWithPast
or tuple(torch.FloatTensor)
Parameters
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]
. - past_key_values (
~cache_utils.Cache
, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_values
returned by the model at a previous stage of decoding, whenuse_cache=True
orconfig.use_cache=True
.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_values
are passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_values
are used, the user is expected to input only unprocessedinput_ids
(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)
instead of allinput_ids
of shape(batch_size, sequence_length)
. - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_ids
indices into associated vectors than the model’s internal embedding lookup matrix. - labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size]
or -100 (seeinput_ids
docstring). Tokens with indices set to-100
are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
. - use_cache (
bool
, optional) — If set toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
). - output_attentions (
bool
, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail. - output_hidden_states (
bool
, optional) — Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail. - pixel_values (
torch.Tensor
of shape(batch_size, num_channels, image_size, image_size)
, optional) — The tensors corresponding to the input images. Pixel values can be obtained using Qwen2VLImageProcessor. See Qwen2VLImageProcessor.call() for details (Qwen2VLProcessor uses Qwen2VLImageProcessor for processing images). - pixel_values_videos (
torch.FloatTensor
of shape(batch_size, num_frames, num_channels, frame_size, frame_size)
, optional) — The tensors corresponding to the input video. Pixel values for videos can be obtained usingQwen2VLVideoProcessor
. SeeQwen2VLVideoProcessor.__call__()
for details (Qwen2VLProcessor usesQwen2VLVideoProcessor
for processing videos). - image_grid_thw (
torch.LongTensor
of shape(num_images, 3)
, optional) — The temporal, height and width of feature shape of each image in LLM. - video_grid_thw (
torch.LongTensor
of shape(num_videos, 3)
, optional) — The temporal, height and width of feature shape of each video in LLM. - rope_deltas (
torch.LongTensor
of shape(batch_size, )
, optional) — The rope index difference between sequence length and multimodal rope. - cache_position (
torch.LongTensor
of shape(sequence_length)
, optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids
, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
Returns
transformers.models.qwen2_vl.modeling_qwen2_vl.Qwen2VLCausalLMOutputWithPast
or tuple(torch.FloatTensor)
A transformers.models.qwen2_vl.modeling_qwen2_vl.Qwen2VLCausalLMOutputWithPast
or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (Qwen2VLConfig) and inputs.
-
loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) โ Language modeling loss (for next-token prediction). -
logits (
torch.FloatTensor
of shape(batch_size, sequence_length, config.vocab_size)
) โ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). -
past_key_values (
Cache
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) โ It is a Cache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
past_key_values
input) to speed up sequential decoding. -
hidden_states (
tuple[torch.FloatTensor]
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) โ Tuple oftorch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
-
attentions (
tuple[torch.FloatTensor]
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) โ Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
-
rope_deltas (
torch.LongTensor
of shape(batch_size, )
, optional) โ The rope index difference between sequence length and multimodal rope.
The Qwen2VLForConditionalGeneration forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Example:
>>> 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 ..."