wcy1122 commited on
Commit
c0ef9c8
·
1 Parent(s): 71aeee5

add utils files

Browse files
Files changed (4) hide show
  1. mgm/constants.py +47 -0
  2. mgm/conversation.py +333 -0
  3. mgm/mm_utils.py +453 -0
  4. mgm/utils.py +126 -0
mgm/constants.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
2
+ WORKER_HEART_BEAT_INTERVAL = 15
3
+
4
+ LOGDIR = "."
5
+
6
+ # Model Constants
7
+ IGNORE_INDEX = -100
8
+ IMAGE_TOKEN_INDEX = -200
9
+ PREDICT_TOKEN_INDEX = -300
10
+ SPEECH_TOKEN_INDEX = -500
11
+ DEFAULT_IMAGE_TOKEN = "<image>"
12
+ DEFAULT_SPEECH_TOKEN = "<speech>"
13
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
14
+ DEFAULT_IM_START_TOKEN = "<im_start>"
15
+ DEFAULT_IM_END_TOKEN = "<im_end>"
16
+ IMAGE_PLACEHOLDER = "<image-placeholder>"
17
+ DEFAULT_PREDICT_TOKEN = "<predict>"
18
+ AUDIO_START = '<|audio_start|>'
19
+ AUDIO_END = '<|audio_end|>'
20
+ AUDIO_SEP = '<|audio_sep|>'
21
+
22
+ DESCRIPT_PROMPT = [
23
+ "Describe this image thoroughly.",
24
+ "Provide a detailed description in this picture.",
25
+ "Detail every aspect of what's in this picture.",
26
+ "Explain this image with precision and detail.",
27
+ "Give a comprehensive description of this visual.",
28
+ "Elaborate on the specifics within this image.",
29
+ "Offer a detailed account of this picture's contents.",
30
+ "Describe in detail what this image portrays.",
31
+ "Break down this image into detailed descriptions.",
32
+ "Provide a thorough description of the elements in this image."]
33
+
34
+ BLANK_SPEECH_TOKENS = [
35
+ 1707, 1788, 1950, 1951, 1959, 2031, 2040, 2112, 3894, 3903,
36
+ 3975, 4056, 4137, 4138, 4143, 4146, 4164, 4173, 4218, 4219,
37
+ 4227, 4299, 4300, 5520, 5523, 5547, 5760, 5763, 5766, 5790,
38
+ 6009, 6081, 6082, 6087, 6090, 6091, 6092, 6117, 6162, 6163,
39
+ 6165, 6168, 6171, 6172, 6198, 6243, 6244, 6249, 6252, 6253,
40
+ 6261, 6276, 6279, 6296, 6299, 6321, 6324, 6325, 6330, 6331,
41
+ 6333, 6334, 6335, 6339, 6342, 6351, 6357, 6360, 6361, 6378,
42
+ 6387, 6399, 6402, 6405, 6406, 6408, 6411, 6412, 6413, 6414,
43
+ 6415, 6416, 6432, 6433, 6435, 6436, 6438, 6439, 6441, 6459,
44
+ 6460, 6461, 6466, 6468, 6469, 6480, 6483, 6486, 6487, 6489,
45
+ 6492, 6493, 6495, 6496, 6511, 6513, 6514, 6519, 6522, 6523,
46
+ 6540, 6541, 6549
47
+ ]
mgm/conversation.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from enum import auto, Enum
3
+ from typing import List, Tuple
4
+ import base64
5
+ from io import BytesIO
6
+ from PIL import Image
7
+
8
+
9
+ def img_to_base64(img_file_path):
10
+ with open(img_file_path, "rb") as wav_file:
11
+ wav_data = wav_file.read()
12
+ base64_encoded = base64.b64encode(wav_data).decode('utf-8')
13
+ return base64_encoded
14
+
15
+ def wav_to_base64(wav_file_path):
16
+ with open(wav_file_path, "rb") as wav_file:
17
+ wav_data = wav_file.read()
18
+ base64_encoded = base64.b64encode(wav_data).decode('utf-8')
19
+ return base64_encoded
20
+
21
+ def mov_to_base64(mov_file_path):
22
+ with open(mov_file_path, "rb") as mov_file:
23
+ mov_data = mov_file.read()
24
+ base64_encoded = base64.b64encode(mov_data).decode('utf-8')
25
+ return base64_encoded
26
+
27
+
28
+ class SeparatorStyle(Enum):
29
+ """Different separator style."""
30
+ SINGLE = auto()
31
+ TWO = auto()
32
+ PLAIN = auto()
33
+ SPEECH_PLAIN = auto()
34
+ QWEN2 = auto()
35
+ QWEN2VL = auto()
36
+
37
+
38
+ @dataclasses.dataclass
39
+ class Conversation:
40
+ """A class that keeps all conversation history."""
41
+ system: str
42
+ roles: List[str]
43
+ messages: List[List[str]]
44
+ offset: int
45
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
46
+ sep: str = "###"
47
+ sep2: str = None
48
+ version: str = "Unknown"
49
+
50
+ skip_next: bool = False
51
+
52
+ def get_prompt(self):
53
+ messages = self.messages
54
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
55
+ messages = self.messages.copy()
56
+ prompt_token = messages[0][1][0]
57
+ init_role, init_msg = messages[0].copy()
58
+ init_msg = init_msg[0].replace(prompt_token, "").strip()
59
+ messages[0] = (init_role, f"{prompt_token}\n" + init_msg)
60
+
61
+ if self.sep_style == SeparatorStyle.SINGLE:
62
+ ret = self.system + self.sep
63
+ for role, message in messages:
64
+ if message:
65
+ if type(message) is tuple:
66
+ message = message[0]
67
+ ret += role + ": " + message + self.sep
68
+ else:
69
+ ret += role + ":"
70
+ elif self.sep_style == SeparatorStyle.TWO:
71
+ seps = [self.sep, self.sep2]
72
+ ret = self.system + seps[0]
73
+ for i, (role, message) in enumerate(messages):
74
+ if message:
75
+ if type(message) is tuple:
76
+ message = message[0]
77
+ ret += role + ": " + message + seps[i % 2]
78
+ else:
79
+ ret += role + ":"
80
+ elif self.sep_style == SeparatorStyle.QWEN2:
81
+ ret = self.system + self.sep
82
+ for role, message in messages:
83
+ if message:
84
+ if type(message) is tuple:
85
+ message = message[0]
86
+ ret += role + message + self.sep
87
+ else:
88
+ ret += role
89
+ elif self.sep_style == SeparatorStyle.QWEN2VL:
90
+ ret = self.system + self.sep
91
+ for role, message in messages:
92
+ if message:
93
+ if type(message) is tuple:
94
+ message = message[0]
95
+ ret += role + message + self.sep
96
+ else:
97
+ ret += role
98
+ elif self.sep_style == SeparatorStyle.PLAIN:
99
+ seps = [self.sep, self.sep2]
100
+ ret = self.system
101
+ for i, (role, message) in enumerate(messages):
102
+ if message:
103
+ if type(message) is tuple:
104
+ message, _, _ = message
105
+ ret += message + seps[i % 2]
106
+ else:
107
+ ret += ""
108
+ elif self.sep_style == SeparatorStyle.SPEECH_PLAIN:
109
+ seps = [self.sep, self.sep2]
110
+ ret = self.system
111
+ for i, (role, message) in enumerate(messages):
112
+ if message:
113
+ if type(message) is tuple:
114
+ message, _, _ = message
115
+ ret += message + seps[i % 2]
116
+ else:
117
+ ret += ""
118
+ else:
119
+ raise ValueError(f"Invalid style: {self.sep_style}")
120
+
121
+ return ret
122
+
123
+ def append_message(self, role, message):
124
+ self.messages.append([role, message])
125
+
126
+ def process_image(self, image, image_process_mode, return_pil=False, image_format='PNG', max_len=1344, min_len=672):
127
+ if image_process_mode == "Pad":
128
+ def expand2square(pil_img, background_color=(122, 116, 104)):
129
+ width, height = pil_img.size
130
+ if width == height:
131
+ return pil_img
132
+ elif width > height:
133
+ result = Image.new(pil_img.mode, (width, width), background_color)
134
+ result.paste(pil_img, (0, (width - height) // 2))
135
+ return result
136
+ else:
137
+ result = Image.new(pil_img.mode, (height, height), background_color)
138
+ result.paste(pil_img, ((height - width) // 2, 0))
139
+ return result
140
+ image = expand2square(image)
141
+ elif image_process_mode in ["Default", "Crop"]:
142
+ pass
143
+ elif image_process_mode == "Resize":
144
+ image = image.resize((336, 336))
145
+ else:
146
+ raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
147
+ if max(image.size) > max_len:
148
+ max_hw, min_hw = max(image.size), min(image.size)
149
+ aspect_ratio = max_hw / min_hw
150
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
151
+ longest_edge = int(shortest_edge * aspect_ratio)
152
+ W, H = image.size
153
+ if H > W:
154
+ H, W = longest_edge, shortest_edge
155
+ else:
156
+ H, W = shortest_edge, longest_edge
157
+ image = image.resize((W, H))
158
+ if return_pil:
159
+ return image
160
+ else:
161
+ buffered = BytesIO()
162
+ image.save(buffered, format=image_format)
163
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
164
+ return img_b64_str
165
+
166
+ def get_images(self, return_pil=False):
167
+ images = []
168
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
169
+ if i % 2 == 0:
170
+ if type(msg) is tuple:
171
+ msg, speech, image, video, image_process_mode = msg
172
+ images.append(image)
173
+ return images
174
+
175
+ def get_speeches(self):
176
+ speeches = []
177
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
178
+ if i % 2 == 0:
179
+ if type(msg) is tuple:
180
+ msg, speech, image, video, image_process_mode = msg
181
+ speeches.append(speech)
182
+ print(speeches)
183
+ return speeches
184
+
185
+ def get_videos(self):
186
+ videos = []
187
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
188
+ if i % 2 == 0:
189
+ if type(msg) is tuple:
190
+ msg, speech, image, video, image_process_mode = msg
191
+ videos.append(video)
192
+ print(videos)
193
+ return videos
194
+
195
+ def to_gradio_chatbot(self):
196
+ ret = []
197
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
198
+ if i % 2 == 0:
199
+ if type(msg) is tuple:
200
+ msg, speech, image, video, image_process_mode = msg
201
+ if video is not None:
202
+ base64_string = mov_to_base64(video)
203
+ video_str = f'''
204
+ <video width="300" controls>
205
+ <source src="data:video/quicktime;base64,{base64_string}" type="video/quicktime">
206
+ Your browser does not support the video element.
207
+ </video>
208
+ '''
209
+ msg = video_str + msg.replace('<image>', '').strip().replace('<speech>', '').strip()
210
+ ret.append([msg, None])
211
+ elif image is not None:
212
+ image = Image.open(image)
213
+ img_b64_str = self.process_image(
214
+ image, "Default", return_pil=False,
215
+ image_format='JPEG')
216
+ img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" alt="user upload image" />'
217
+ if speech is not None:
218
+ base64_string = wav_to_base64(speech)
219
+ aud_str = f'''
220
+ <audio controls>
221
+ <source src="data:audio/wav;base64,{base64_string}" type="audio/wav">
222
+ Your browser does not support the audio element.
223
+ </audio>
224
+ '''
225
+ msg = img_str + aud_str + msg.replace('<image>', '').strip().replace('<speech>', '').strip()
226
+ ret.append([msg, None])
227
+ else:
228
+ msg = img_str + msg.replace('<image>', '').strip()
229
+ ret.append([msg, None])
230
+ elif speech is not None:
231
+ base64_string = wav_to_base64(speech)
232
+ aud_str = f'''
233
+ <audio controls>
234
+ <source src="data:audio/wav;base64,{base64_string}" type="audio/wav">
235
+ Your browser does not support the audio element.
236
+ </audio>
237
+ '''
238
+ msg = aud_str + msg.replace('<speech>', '').strip()
239
+ ret.append([msg, None])
240
+ else:
241
+ ret.append([msg, None])
242
+ else:
243
+ ret.append([msg, None])
244
+ else:
245
+ if type(msg) is tuple and len(msg) == 2:
246
+ msg, img_b64_str = msg
247
+ img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" alt="user upload image" />'
248
+ msg = msg.strip() + img_str
249
+ ret[-1][-1] = msg
250
+ return ret
251
+
252
+ def copy(self):
253
+ return Conversation(
254
+ system=self.system,
255
+ roles=self.roles,
256
+ messages=[[x, y] for x, y in self.messages],
257
+ offset=self.offset,
258
+ sep_style=self.sep_style,
259
+ sep=self.sep,
260
+ sep2=self.sep2,
261
+ version=self.version)
262
+
263
+ def dict(self):
264
+ if len(self.get_images()) > 0:
265
+ return {
266
+ "system": self.system,
267
+ "roles": self.roles,
268
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
269
+ "offset": self.offset,
270
+ "sep": self.sep,
271
+ "sep2": self.sep2,
272
+ }
273
+ return {
274
+ "system": self.system,
275
+ "roles": self.roles,
276
+ "messages": self.messages,
277
+ "offset": self.offset,
278
+ "sep": self.sep,
279
+ "sep2": self.sep2,
280
+ }
281
+
282
+
283
+ conv_qwen = Conversation(
284
+ system="""<|im_start|>system\nYou are a helpful assistant.""",
285
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
286
+ version="qwen",
287
+ messages=[],
288
+ offset=0,
289
+ sep_style=SeparatorStyle.QWEN2,
290
+ sep="<|im_end|>\n",
291
+ )
292
+
293
+ conv_qwen2vl = Conversation(
294
+ system="""<|im_start|>system\nYou are a helpful assistant.""",
295
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
296
+ version="qwen",
297
+ messages=[],
298
+ offset=0,
299
+ sep_style=SeparatorStyle.QWEN2VL,
300
+ sep="<|im_end|>\n",
301
+ )
302
+
303
+ conv_llava_plain = Conversation(
304
+ system="",
305
+ roles=("", ""),
306
+ messages=(
307
+ ),
308
+ offset=0,
309
+ sep_style=SeparatorStyle.PLAIN,
310
+ sep="\n",
311
+ )
312
+
313
+ speech_plain = Conversation(
314
+ system="",
315
+ roles=("", ""),
316
+ messages=(
317
+ ),
318
+ offset=0,
319
+ sep_style=SeparatorStyle.SPEECH_PLAIN,
320
+ sep="\n",
321
+ )
322
+
323
+ default_conversation = conv_qwen2vl
324
+ conv_templates = {
325
+ "qwen2": conv_qwen,
326
+ "qwen2vl": conv_qwen2vl,
327
+ "plain": conv_llava_plain,
328
+ "speech_plain": speech_plain,
329
+ }
330
+
331
+
332
+ if __name__ == "__main__":
333
+ print(default_conversation.get_prompt())
mgm/mm_utils.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from io import BytesIO
3
+ import base64
4
+ import math
5
+ import ast
6
+ import re
7
+ import torch
8
+ from transformers import StoppingCriteria
9
+ from mgm.constants import IMAGE_TOKEN_INDEX, SPEECH_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_SPEECH_TOKEN, IGNORE_INDEX
10
+ import numpy as np
11
+
12
+
13
+ def resize_and_center_crop(image, shortest_edge_length):
14
+ # Calculate new dimensions and resize
15
+ aspect_ratio = float(image.width) / float(image.height)
16
+ if aspect_ratio > 1:
17
+ new_width = int(shortest_edge_length * aspect_ratio)
18
+ new_height = shortest_edge_length
19
+ else:
20
+ new_width = shortest_edge_length
21
+ new_height = int(shortest_edge_length / aspect_ratio)
22
+ resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
23
+
24
+ # Calculate the position and perform the center crop
25
+ left = (new_width - shortest_edge_length) / 2
26
+ top = (new_height - shortest_edge_length) / 2
27
+ right = (new_width + shortest_edge_length) / 2
28
+ bottom = (new_height + shortest_edge_length) / 2
29
+ cropped_image = resized_image.crop((left, top, right, bottom))
30
+
31
+ return cropped_image
32
+
33
+
34
+ def auto_pad_images(image, grid_params):
35
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
36
+ assert len(grid_params) > 0, "Grid parameters should not be empty"
37
+
38
+ # Step 1: Calculate and find the closest aspect ratio
39
+ input_width, input_height = image.size
40
+ input_aspect_ratio = input_width / input_height
41
+ candidate_resolutions = [(w / h, w, h) for w in grid_params for h in grid_params]
42
+ closest_aspect_ratio = min(candidate_resolutions, key=lambda x: abs(input_aspect_ratio - x[0]))
43
+
44
+ candidate_resolutions = [(x[1], x[2]) for x in candidate_resolutions if abs(x[0] - closest_aspect_ratio[0]) < 1e-3]
45
+
46
+ target_resolution = min(candidate_resolutions, key=lambda res: abs(max(input_width, input_height) / max(res) - 1))
47
+
48
+ resize_width, resize_height = target_resolution
49
+ if input_width > input_height:
50
+ resize_height = int(resize_width / input_aspect_ratio)
51
+ else:
52
+ resize_width = int(resize_height * input_aspect_ratio)
53
+ resized_image = image.resize((resize_width, resize_height), Image.ANTIALIAS)
54
+
55
+ # Step 5: Pad the resized image if necessary to match the target resolution
56
+ pad_width = target_resolution[0] - resize_width
57
+ pad_height = target_resolution[1] - resize_height
58
+ padded_image = Image.new("RGB", target_resolution, color=(0, 0, 0))
59
+ padded_image.paste(resized_image, (pad_width // 2, pad_height // 2))
60
+
61
+ return padded_image
62
+
63
+
64
+ def extract_patches(image, patch_size, overlap_ratio):
65
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
66
+ assert patch_size > 0, "Patch size should be greater than 0"
67
+ assert 0 <= overlap_ratio < 1, "Overlap ratio should be between 0 and 1"
68
+
69
+ W, H = image.size
70
+ patches = []
71
+
72
+ stride = int(patch_size * (1 - overlap_ratio))
73
+
74
+ num_patches_y = (H - patch_size) // stride + 1
75
+ num_patches_x = (W - patch_size) // stride + 1
76
+
77
+ y_start = (H - (num_patches_y - 1) * stride - patch_size) // 2
78
+ x_start = (W - (num_patches_x - 1) * stride - patch_size) // 2
79
+
80
+ for y in range(y_start, y_start + num_patches_y * stride, stride):
81
+ for x in range(x_start, x_start + num_patches_x * stride, stride):
82
+ patch = image.crop((x, y, x + patch_size, y + patch_size))
83
+ patches.append(patch)
84
+
85
+ return patches
86
+
87
+
88
+ def process_highres_image_crop_split(image, data_args, processor=None):
89
+ crop_resolution = data_args.image_crop_resolution
90
+ split_resolution = data_args.image_split_resolution
91
+ if processor is None:
92
+ processor = data_args.image_processor
93
+ image_crop = resize_and_center_crop(image, crop_resolution)
94
+ image_patches = extract_patches(image_crop, patch_size=split_resolution, overlap_ratio=0)
95
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
96
+ return torch.stack(image_patches, dim=0)
97
+
98
+
99
+ def process_highres_image(image, processor, grid_pinpoints):
100
+ grid_params = [int(x) for x in grid_pinpoints.split(",")]
101
+ width_height = max(image.size)
102
+ fit_grid_params = [x for x in grid_params if x >= width_height]
103
+ if len(fit_grid_params) == 0:
104
+ select_size = max(grid_params)
105
+ else:
106
+ select_size = min(fit_grid_params)
107
+ # FIXME: always select the 448
108
+ select_size = max(grid_params)
109
+ image_padded = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
110
+
111
+ # FIXME: this seems to be a bug that it always resizes instead of padding
112
+ image_original_resize = image.resize((processor.size["shortest_edge"], processor.size["shortest_edge"]))
113
+ image_padded = image_padded.resize((select_size, select_size))
114
+ image_patches = extract_patches(image_padded, patch_size=processor.size["shortest_edge"], overlap_ratio=0)
115
+ image_patches = [image_original_resize] + image_patches
116
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
117
+ return torch.stack(image_patches, dim=0)
118
+
119
+
120
+ def select_best_resolution(original_size, possible_resolutions):
121
+ """
122
+ Selects the best resolution from a list of possible resolutions based on the original size.
123
+
124
+ Args:
125
+ original_size (tuple): The original size of the image in the format (width, height).
126
+ possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
127
+
128
+ Returns:
129
+ tuple: The best fit resolution in the format (width, height).
130
+ """
131
+ original_width, original_height = original_size
132
+ best_fit = None
133
+ max_effective_resolution = 0
134
+ min_wasted_resolution = float("inf")
135
+
136
+ for width, height in possible_resolutions:
137
+ # Calculate the downscaled size to keep the aspect ratio
138
+ scale = min(width / original_width, height / original_height)
139
+ downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
140
+
141
+ # Calculate effective and wasted resolutions
142
+ effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
143
+ wasted_resolution = (width * height) - effective_resolution
144
+
145
+ if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
146
+ max_effective_resolution = effective_resolution
147
+ min_wasted_resolution = wasted_resolution
148
+ best_fit = (width, height)
149
+
150
+ return best_fit
151
+
152
+
153
+ def resize_and_pad_image(image, target_resolution):
154
+ """
155
+ Resize and pad an image to a target resolution while maintaining aspect ratio.
156
+
157
+ Args:
158
+ image (PIL.Image.Image): The input image.
159
+ target_resolution (tuple): The target resolution (width, height) of the image.
160
+
161
+ Returns:
162
+ PIL.Image.Image: The resized and padded image.
163
+ """
164
+ original_width, original_height = image.size
165
+ target_width, target_height = target_resolution
166
+
167
+ # Determine which dimension (width or height) to fill
168
+ scale_w = target_width / original_width
169
+ scale_h = target_height / original_height
170
+
171
+ if scale_w < scale_h:
172
+ # Width will be filled completely
173
+ new_width = target_width
174
+ new_height = min(math.ceil(original_height * scale_w), target_height)
175
+ else:
176
+ # Height will be filled completely
177
+ new_height = target_height
178
+ new_width = min(math.ceil(original_width * scale_h), target_width)
179
+
180
+ # Resize the image
181
+ resized_image = image.resize((new_width, new_height))
182
+
183
+ # Create a new image with the target size and paste the resized image onto it
184
+ new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0))
185
+ paste_x = (target_width - new_width) // 2
186
+ paste_y = (target_height - new_height) // 2
187
+ new_image.paste(resized_image, (paste_x, paste_y))
188
+
189
+ return new_image
190
+
191
+
192
+ def divide_to_patches(image, patch_size):
193
+ """
194
+ Divides an image into patches of a specified size.
195
+
196
+ Args:
197
+ image (PIL.Image.Image): The input image.
198
+ patch_size (int): The size of each patch.
199
+
200
+ Returns:
201
+ list: A list of PIL.Image.Image objects representing the patches.
202
+ """
203
+ patches = []
204
+ width, height = image.size
205
+ for i in range(0, height, patch_size):
206
+ for j in range(0, width, patch_size):
207
+ box = (j, i, j + patch_size, i + patch_size)
208
+ patch = image.crop(box)
209
+ patches.append(patch)
210
+
211
+ return patches
212
+
213
+
214
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
215
+ """
216
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
217
+
218
+ Args:
219
+ image_size (tuple): The size of the input image in the format (width, height).
220
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
221
+ patch_size (int): The size of each image patch.
222
+
223
+ Returns:
224
+ tuple: The shape of the image patch grid in the format (width, height).
225
+ """
226
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
227
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
228
+ # Use regex to extract the range from the input string
229
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
230
+ range_start = tuple(map(int, matches[0]))
231
+ range_end = tuple(map(int, matches[-1]))
232
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
233
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
234
+ # Multiply all elements by patch_size
235
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
236
+ if type(grid_pinpoints) is list:
237
+ possible_resolutions = grid_pinpoints
238
+ else:
239
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
240
+ width, height = select_best_resolution(image_size, possible_resolutions)
241
+ return width // patch_size, height // patch_size
242
+
243
+
244
+ def process_anyres_image(image, processor, grid_pinpoints, overlap_ratio=0):
245
+ """
246
+ Process an image with variable resolutions.
247
+
248
+ Args:
249
+ image (PIL.Image.Image): The input image to be processed.
250
+ processor: The image processor object.
251
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
252
+
253
+ Returns:
254
+ torch.Tensor: A tensor containing the processed image patches.
255
+ """
256
+ # Convert grid_pinpoints from string to list
257
+ if grid_pinpoints == '[]':
258
+ patches = []
259
+ else:
260
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
261
+ try:
262
+ patch_size = processor.size[0]
263
+ except Exception as e:
264
+ # CLIP
265
+ if "shortest_edge" in processor.size.keys():
266
+ patch_size = processor.size["shortest_edge"]
267
+ # SigLip
268
+ elif "height" in processor.size.keys():
269
+ patch_size = processor.size["height"]
270
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
271
+ # Use regex to extract the range from the input string
272
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
273
+ range_start = tuple(map(int, matches[0]))
274
+ range_end = tuple(map(int, matches[-1]))
275
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
276
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
277
+ # Multiply all elements by patch_size
278
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
279
+
280
+ if type(grid_pinpoints) is list:
281
+ possible_resolutions = grid_pinpoints
282
+ else:
283
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
284
+ best_resolution = select_best_resolution(image.size, possible_resolutions)
285
+ image_padded = resize_and_pad_image(image, best_resolution)
286
+
287
+ if hasattr(processor, "crop_size"):
288
+ patches = extract_patches(image_padded, processor.crop_size["height"], overlap_ratio)
289
+ elif hasattr(processor, "size"):
290
+ patches = extract_patches(image_padded, processor.size["height"], overlap_ratio)
291
+
292
+
293
+ # FIXME: this seems to be a bug that it resizes instead of pad.
294
+ # but to keep it consistent with previous, i will keep it as it is
295
+ # TODO: uncomment below to ablate with the padding
296
+ if isinstance(processor.size, dict):
297
+ # CLIP
298
+ if "shortest_edge" in processor.size.keys():
299
+ shortest_edge = processor.size["shortest_edge"]
300
+ # SigLip
301
+ elif "height" in processor.size.keys():
302
+ shortest_edge = processor.size["height"]
303
+
304
+ else:
305
+ shortest_edge = min(processor.size)
306
+ image_original_resize = image.resize((shortest_edge, shortest_edge))
307
+
308
+
309
+ image_patches = [image_original_resize] + patches
310
+
311
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
312
+ return torch.stack(image_patches, dim=0)
313
+
314
+
315
+ def load_image_from_base64(image):
316
+ return Image.open(BytesIO(base64.b64decode(image)))
317
+
318
+
319
+ def expand2square(pil_img, background_color):
320
+ width, height = pil_img.size
321
+ if width == height:
322
+ return pil_img
323
+ elif width > height:
324
+ result = Image.new(pil_img.mode, (width, width), background_color)
325
+ result.paste(pil_img, (0, (width - height) // 2))
326
+ return result
327
+ else:
328
+ result = Image.new(pil_img.mode, (height, height), background_color)
329
+ result.paste(pil_img, ((height - width) // 2, 0))
330
+ return result
331
+
332
+
333
+ def process_images(images, image_processor, model_cfg):
334
+ image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
335
+ new_images = []
336
+ if image_aspect_ratio == "highres":
337
+ for image in images:
338
+ image = process_highres_image(image, image_processor, model_cfg.image_grid_pinpoints)
339
+ new_images.append(image)
340
+ elif image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio:
341
+ for image in images:
342
+ image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints)
343
+ new_images.append(image)
344
+ elif image_aspect_ratio == "crop_split":
345
+ for image in images:
346
+ image = process_highres_image_crop_split(image, model_cfg, image_processor)
347
+ new_images.append(image)
348
+ elif image_aspect_ratio == "pad":
349
+ for image in images:
350
+ image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean))
351
+ image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
352
+ new_images.append(image)
353
+ else:
354
+ return image_processor.preprocess(images, return_tensors="pt")["pixel_values"]
355
+ if all(x.shape == new_images[0].shape for x in new_images):
356
+ new_images = torch.stack(new_images, dim=0)
357
+ return new_images
358
+
359
+
360
+ def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
361
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
362
+
363
+ def insert_separator(X, sep):
364
+ return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
365
+
366
+ input_ids = []
367
+ offset = 0
368
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
369
+ offset = 1
370
+ input_ids.append(prompt_chunks[0][0])
371
+
372
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
373
+ input_ids.extend(x[offset:])
374
+
375
+ if return_tensors is not None:
376
+ if return_tensors == "pt":
377
+ return torch.tensor(input_ids, dtype=torch.long)
378
+ raise ValueError(f"Unsupported tensor type: {return_tensors}")
379
+ return input_ids
380
+
381
+ def tokenizer_speech_token(prompt, tokenizer, speech_token_index=SPEECH_TOKEN_INDEX, return_tensors=None):
382
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split(DEFAULT_SPEECH_TOKEN)]
383
+
384
+ def insert_separator(X, sep):
385
+ return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1]
386
+
387
+ input_ids = []
388
+ offset = 0
389
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
390
+ offset = 1
391
+ input_ids.append(prompt_chunks[0][0])
392
+
393
+ for x in insert_separator(prompt_chunks, [speech_token_index] * (offset + 1)):
394
+ input_ids.extend(x[offset:])
395
+
396
+ if return_tensors is not None:
397
+ if return_tensors == 'pt':
398
+ return torch.tensor(input_ids, dtype=torch.long)
399
+ raise ValueError(f'Unsupported tensor type: {return_tensors}')
400
+ return input_ids
401
+
402
+ def tokenizer_image_speech_token(prompt, tokenizer, return_tensors=None):
403
+ # pdb.set_trace()
404
+ PATTERN = re.compile(rf'({DEFAULT_IMAGE_TOKEN}|{DEFAULT_SPEECH_TOKEN})')
405
+ input_ids = []
406
+ for chunk in PATTERN.split(prompt):
407
+ if chunk == DEFAULT_IMAGE_TOKEN:
408
+ input_ids.extend([IMAGE_TOKEN_INDEX])
409
+ elif chunk == DEFAULT_SPEECH_TOKEN:
410
+ input_ids.extend([SPEECH_TOKEN_INDEX])
411
+ else:
412
+ input_ids.extend(tokenizer(chunk).input_ids)
413
+
414
+ if return_tensors is not None:
415
+ if return_tensors == 'pt':
416
+ return torch.tensor(input_ids, dtype=torch.long)
417
+ raise ValueError(f'Unsupported tensor type: {return_tensors}')
418
+ return input_ids
419
+
420
+
421
+ def get_model_name_from_path(model_path):
422
+ model_path = model_path.strip("/")
423
+ model_paths = model_path.split("/")
424
+ if model_paths[-1].startswith("checkpoint-"):
425
+ return model_paths[-2] + "_" + model_paths[-1]
426
+ else:
427
+ return model_paths[-1]
428
+
429
+
430
+ class KeywordsStoppingCriteria(StoppingCriteria):
431
+ def __init__(self, keywords, tokenizer, input_ids):
432
+ self.keywords = keywords
433
+ self.keyword_ids = []
434
+ for keyword in keywords:
435
+ cur_keyword_ids = tokenizer(keyword).input_ids
436
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
437
+ cur_keyword_ids = cur_keyword_ids[1:]
438
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
439
+ self.tokenizer = tokenizer
440
+ self.start_len = input_ids.shape[1]
441
+
442
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
443
+ assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
444
+ offset = min(output_ids.shape[1] - self.start_len, 3)
445
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
446
+ for keyword_id in self.keyword_ids:
447
+ if output_ids[0, -keyword_id.shape[0] :] == keyword_id:
448
+ return True
449
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
450
+ for keyword in self.keywords:
451
+ if keyword in outputs:
452
+ return True
453
+ return False
mgm/utils.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import logging
3
+ import logging.handlers
4
+ import os
5
+ import sys
6
+
7
+ import requests
8
+
9
+ from mgm.constants import LOGDIR
10
+
11
+ server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
12
+ moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN."
13
+
14
+ handler = None
15
+
16
+
17
+ def build_logger(logger_name, logger_filename):
18
+ global handler
19
+
20
+ formatter = logging.Formatter(
21
+ fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
22
+ datefmt="%Y-%m-%d %H:%M:%S",
23
+ )
24
+
25
+ # Set the format of root handlers
26
+ if not logging.getLogger().handlers:
27
+ logging.basicConfig(level=logging.INFO)
28
+ logging.getLogger().handlers[0].setFormatter(formatter)
29
+
30
+ # Redirect stdout and stderr to loggers
31
+ stdout_logger = logging.getLogger("stdout")
32
+ stdout_logger.setLevel(logging.INFO)
33
+ sl = StreamToLogger(stdout_logger, logging.INFO)
34
+ sys.stdout = sl
35
+
36
+ stderr_logger = logging.getLogger("stderr")
37
+ stderr_logger.setLevel(logging.ERROR)
38
+ sl = StreamToLogger(stderr_logger, logging.ERROR)
39
+ sys.stderr = sl
40
+
41
+ # Get logger
42
+ logger = logging.getLogger(logger_name)
43
+ logger.setLevel(logging.INFO)
44
+
45
+ # Add a file handler for all loggers
46
+ if handler is None:
47
+ os.makedirs(LOGDIR, exist_ok=True)
48
+ filename = os.path.join(LOGDIR, logger_filename)
49
+ handler = logging.handlers.TimedRotatingFileHandler(
50
+ filename, when='D', utc=True, encoding='UTF-8')
51
+ handler.setFormatter(formatter)
52
+
53
+ for name, item in logging.root.manager.loggerDict.items():
54
+ if isinstance(item, logging.Logger):
55
+ item.addHandler(handler)
56
+
57
+ return logger
58
+
59
+
60
+ class StreamToLogger(object):
61
+ """
62
+ Fake file-like stream object that redirects writes to a logger instance.
63
+ """
64
+ def __init__(self, logger, log_level=logging.INFO):
65
+ self.terminal = sys.stdout
66
+ self.logger = logger
67
+ self.log_level = log_level
68
+ self.linebuf = ''
69
+
70
+ def __getattr__(self, attr):
71
+ return getattr(self.terminal, attr)
72
+
73
+ def write(self, buf):
74
+ temp_linebuf = self.linebuf + buf
75
+ self.linebuf = ''
76
+ for line in temp_linebuf.splitlines(True):
77
+ # From the io.TextIOWrapper docs:
78
+ # On output, if newline is None, any '\n' characters written
79
+ # are translated to the system default line separator.
80
+ # By default sys.stdout.write() expects '\n' newlines and then
81
+ # translates them so this is still cross platform.
82
+ if line[-1] == '\n':
83
+ self.logger.log(self.log_level, line.rstrip())
84
+ else:
85
+ self.linebuf += line
86
+
87
+ def flush(self):
88
+ if self.linebuf != '':
89
+ self.logger.log(self.log_level, self.linebuf.rstrip())
90
+ self.linebuf = ''
91
+
92
+
93
+ def disable_torch_init():
94
+ """
95
+ Disable the redundant torch default initialization to accelerate model creation.
96
+ """
97
+ import torch
98
+ setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
99
+ setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
100
+
101
+
102
+ def violates_moderation(text):
103
+ """
104
+ Check whether the text violates OpenAI moderation API.
105
+ """
106
+ url = "https://api.openai.com/v1/moderations"
107
+ headers = {"Content-Type": "application/json",
108
+ "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]}
109
+ text = text.replace("\n", "")
110
+ data = "{" + '"input": ' + f'"{text}"' + "}"
111
+ data = data.encode("utf-8")
112
+ try:
113
+ ret = requests.post(url, headers=headers, data=data, timeout=5)
114
+ flagged = ret.json()["results"][0]["flagged"]
115
+ except requests.exceptions.RequestException as e:
116
+ flagged = False
117
+ except KeyError as e:
118
+ flagged = False
119
+
120
+ return flagged
121
+
122
+
123
+ def pretty_print_semaphore(semaphore):
124
+ if semaphore is None:
125
+ return "None"
126
+ return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"