friedrichor commited on
Commit
f3cb545
·
verified ·
1 Parent(s): 20a4d8d

Correct the inference code.

Browse files
.gitattributes CHANGED
@@ -37,3 +37,4 @@ tokenizer.json filter=lfs diff=lfs merge=lfs -text
37
  inference_demo/examples/1408px-Lilium_philadelphicum_var._philadelphicum.jpg filter=lfs diff=lfs merge=lfs -text
38
  inference_demo/examples/stock-footage-pictorial-upper-view-sunset-beams-light-waterfall-stone-cascade-and-fresh-green-tropical-trees.mp4 filter=lfs diff=lfs merge=lfs -text
39
  examples/stock-footage-timelapse-of-stormy-clouds-over-open-sea-and-snowcapped-mountain.mp4 filter=lfs diff=lfs merge=lfs -text
 
 
37
  inference_demo/examples/1408px-Lilium_philadelphicum_var._philadelphicum.jpg filter=lfs diff=lfs merge=lfs -text
38
  inference_demo/examples/stock-footage-pictorial-upper-view-sunset-beams-light-waterfall-stone-cascade-and-fresh-green-tropical-trees.mp4 filter=lfs diff=lfs merge=lfs -text
39
  examples/stock-footage-timelapse-of-stormy-clouds-over-open-sea-and-snowcapped-mountain.mp4 filter=lfs diff=lfs merge=lfs -text
40
+ inference_demo/examples/stock-footage-timelapse-of-stormy-clouds-over-open-sea-and-snowcapped-mountain.mp4 filter=lfs diff=lfs merge=lfs -text
inference_demo/examples/518L0uDGe0L.jpg ADDED
inference_demo/examples/Q673659.jpg ADDED
inference_demo/examples/oven_05011373.jpg ADDED
inference_demo/examples/stock-footage-timelapse-of-stormy-clouds-over-open-sea-and-snowcapped-mountain.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c45bfeb693653ce84ae877d3a81ff5d181c4df6f80c47c7854b7e4b1ce866763
3
+ size 1430386
inference_demo/inference.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoTokenizer, AutoProcessor
3
+ from qwen_vl_utils import process_vision_info
4
+ from modeling_unite import UniteQwen2VL
5
+
6
+
7
+ model_path = 'friedrichor/Unite-Base-Qwen2-VL-2B'
8
+ model = UniteQwen2VL.from_pretrained(
9
+ model_path,
10
+ torch_dtype=torch.bfloat16,
11
+ device_map="cuda"
12
+ )
13
+
14
+ # We recommend enabling flash_attention_2 for better acceleration and memory saving.
15
+ # model = UniteQwen2VL.from_pretrained(
16
+ # model_path,
17
+ # device_map="cuda",
18
+ # torch_dtype=torch.bfloat16,
19
+ # attn_implementation='flash_attention_2',
20
+ # low_cpu_mem_usage=True,
21
+ # )
22
+
23
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
24
+ processor = AutoProcessor.from_pretrained(model_path, min_pixels=256*28*28, max_pixels=1280*28*28)
25
+
26
+ def process_messages(msg):
27
+ text = processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True) + "<|endoftext|>"
28
+ image_inputs, video_inputs = process_vision_info(msg)
29
+ inputs = processor(
30
+ text=[text],
31
+ images=image_inputs,
32
+ videos=video_inputs,
33
+ padding=True,
34
+ return_tensors="pt",
35
+ )
36
+ inputs = inputs.to("cuda")
37
+
38
+ return inputs
39
+
40
+ ## ============================== Text-Image ==============================
41
+ messages_txt = [
42
+ {
43
+ "role": "user",
44
+ "content": [
45
+ {"type": "text", "text": "The book titled 'Riding with Reindeer - A Bicycle Odyssey through Finland, Lapland, and the Arctic' provides a detailed account of a journey that explores the regions of Lapland and the Arctic, focusing on the experience of riding with reindeer."},
46
+ {"type": "text", "text": "\nSummary above sentence in one word:"},
47
+ ],
48
+ }
49
+ ]
50
+
51
+ messages_img = [
52
+ {
53
+ "role": "user",
54
+ "content": [
55
+ {"type": "image", "image": "./examples/518L0uDGe0L.jpg"},
56
+ {"type": "text", "text": "\nSummary above image in one word:"},
57
+ ],
58
+ }
59
+ ]
60
+
61
+ inputs_txt = process_messages(messages_txt)
62
+ inputs_img = process_messages(messages_img)
63
+
64
+ with torch.no_grad():
65
+ embeddings_txt = model(**inputs_txt) # [1, 1536]
66
+ embeddings_img = model(**inputs_img) # [1, 1536]
67
+ print(f"embeddings_txt.shape: {embeddings_txt.shape}")
68
+ print(f"embeddings_img.shape: {embeddings_img.shape}")
69
+
70
+ print(torch.matmul(embeddings_txt, embeddings_img.T))
71
+ # tensor([[0.7500]], dtype=torch.bfloat16)
72
+
73
+ ## ============================== Text-Video ==============================
74
+ messages_txt = [
75
+ {
76
+ "role": "user",
77
+ "content": [
78
+ {"type": "text", "text": "Timelapse of stormy clouds over open sea and snowcapped mountain"},
79
+ {"type": "text", "text": "\nSummary above sentence in one word:"},
80
+ ],
81
+ }
82
+ ]
83
+
84
+ messages_vid = [
85
+ {
86
+ "role": "user",
87
+ "content": [
88
+ {
89
+ "type": "video",
90
+ "video": "./examples/stock-footage-timelapse-of-stormy-clouds-over-open-sea-and-snowcapped-mountain.mp4",
91
+ "max_pixels": 360 * 420,
92
+ "fps": 1,
93
+ "max_frames": 32
94
+ },
95
+ {"type": "text", "text": "\nSummary above video in one word:"},
96
+ ],
97
+ }
98
+ ]
99
+
100
+ inputs_txt = process_messages(messages_txt)
101
+ inputs_vid = process_messages(messages_vid)
102
+
103
+ with torch.no_grad():
104
+ embeddings_txt = model(**inputs_txt) # [1, 1536]
105
+ embeddings_vid = model(**inputs_vid) # [1, 1536]
106
+
107
+ print(torch.matmul(embeddings_txt, embeddings_vid.T))
108
+ # tensor([[0.5664]], dtype=torch.bfloat16)
109
+
110
+ ## ============================== Fused Modal ==============================
111
+ messages_qry = [
112
+ {
113
+ "role": "user",
114
+ "content": [
115
+ {"type": "image", "image": "./examples/oven_05011373.jpg"},
116
+ {"type": "text", "text": "What is the name of this place?"},
117
+ {"type": "text", "text": "\nSummary above sentence and image in one word:"},
118
+ ],
119
+ }
120
+ ]
121
+
122
+ messages_tgt = [
123
+ {
124
+ "role": "user",
125
+ "content": [
126
+ {"type": "image", "image": "./examples/Q673659.jpg"},
127
+ {"type": "text", "text": "Marina Beach."},
128
+ {"type": "text", "text": "\nSummary above sentence and image in one word:"},
129
+ ],
130
+ }
131
+ ]
132
+
133
+ inputs_qry = process_messages(messages_qry)
134
+ inputs_tgt = process_messages(messages_tgt)
135
+
136
+ with torch.no_grad():
137
+ embeddings_qry = model(**inputs_qry) # [1, 1536]
138
+ embeddings_tgt = model(**inputs_tgt) # [1, 1536]
139
+
140
+ print(torch.matmul(embeddings_qry, embeddings_tgt.T))
141
+ # tensor([[0.7695]], dtype=torch.bfloat16)
inference_demo/modeling_unite.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, List
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from transformers import Qwen2VLConfig, Qwen2VLForConditionalGeneration, Qwen2VLModel
6
+
7
+
8
+ class UniteQwen2VLConfig(Qwen2VLConfig):
9
+ model_type = "unite_qwen2_vl"
10
+
11
+
12
+ class UniteQwen2VL(Qwen2VLForConditionalGeneration):
13
+ def __init__(self, config):
14
+ Qwen2VLForConditionalGeneration.__init__(self, config)
15
+ config.model_type = "unite_qwen2_vl"
16
+
17
+ # Initialize weights and apply final processing
18
+ self.post_init()
19
+
20
+ self.normalize = True
21
+
22
+ def forward(
23
+ self,
24
+ input_ids: Optional[torch.LongTensor] = None,
25
+ attention_mask: Optional[torch.Tensor] = None,
26
+ position_ids: Optional[torch.LongTensor] = None,
27
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
28
+ inputs_embeds: Optional[torch.FloatTensor] = None,
29
+ use_cache: Optional[bool] = None,
30
+ pixel_values: Optional[torch.Tensor] = None,
31
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
32
+ image_grid_thw: Optional[torch.LongTensor] = None,
33
+ video_grid_thw: Optional[torch.LongTensor] = None,
34
+ pooling_mask: Optional[torch.LongTensor] = None,
35
+ **kwargs
36
+ ) -> torch.Tensor:
37
+ if inputs_embeds is None:
38
+ inputs_embeds = self.model.embed_tokens(input_ids)
39
+ if pixel_values is not None:
40
+ pixel_values = pixel_values.type(self.visual.get_dtype())
41
+ image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
42
+ image_mask = (
43
+ (input_ids == self.config.image_token_id)
44
+ .unsqueeze(-1)
45
+ .expand_as(inputs_embeds)
46
+ .to(inputs_embeds.device)
47
+ )
48
+ image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
49
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
50
+ if pixel_values_videos is not None:
51
+ pixel_values_videos = pixel_values_videos.type(self.visual.get_dtype())
52
+ video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
53
+ video_mask = (
54
+ (input_ids == self.config.video_token_id)
55
+ .unsqueeze(-1)
56
+ .expand_as(inputs_embeds)
57
+ .to(inputs_embeds.device)
58
+ )
59
+ video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
60
+ inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
61
+ if attention_mask is not None:
62
+ attention_mask = attention_mask.to(inputs_embeds.device)
63
+
64
+ outputs = self.model(
65
+ input_ids=None,
66
+ position_ids=position_ids,
67
+ attention_mask=attention_mask,
68
+ past_key_values=past_key_values,
69
+ inputs_embeds=inputs_embeds,
70
+ )
71
+
72
+ pooling_mask = attention_mask if pooling_mask is None else pooling_mask
73
+ left_padding = (pooling_mask[:, -1].sum() == pooling_mask.shape[0]) # TODO
74
+
75
+ if left_padding:
76
+ embeddings = outputs.last_hidden_state[:, -1]
77
+ else:
78
+ sequence_lengths = pooling_mask.sum(dim=1) - 1
79
+ batch_size = outputs.last_hidden_state.shape[0]
80
+ embeddings = outputs.last_hidden_state[torch.arange(
81
+ batch_size, device=outputs.last_hidden_state.device
82
+ ), sequence_lengths]
83
+ if self.normalize:
84
+ embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)
85
+
86
+ return embeddings.contiguous()
87
+
88
+