xinference 1.4.0__py3-none-any.whl → 1.4.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of xinference might be problematic. Click here for more details.
- xinference/_compat.py +1 -0
- xinference/_version.py +3 -3
- xinference/api/restful_api.py +4 -0
- xinference/core/model.py +23 -3
- xinference/core/supervisor.py +6 -0
- xinference/core/worker.py +54 -11
- xinference/model/llm/__init__.py +4 -2
- xinference/model/llm/core.py +1 -0
- xinference/model/llm/llama_cpp/core.py +6 -1
- xinference/model/llm/llm_family.json +117 -1
- xinference/model/llm/llm_family_modelscope.json +125 -1
- xinference/model/llm/reasoning_parser.py +3 -3
- xinference/model/llm/sglang/core.py +111 -13
- xinference/model/llm/transformers/core.py +1 -0
- xinference/model/llm/transformers/deepseek_vl.py +1 -1
- xinference/model/llm/transformers/deepseek_vl2.py +287 -0
- xinference/model/llm/utils.py +26 -14
- xinference/model/llm/vllm/core.py +149 -8
- xinference/model/llm/vllm/distributed_executor.py +314 -0
- xinference/model/rerank/core.py +16 -11
- xinference/thirdparty/deepseek_vl2/__init__.py +31 -0
- xinference/thirdparty/deepseek_vl2/models/__init__.py +26 -0
- xinference/thirdparty/deepseek_vl2/models/configuration_deepseek.py +210 -0
- xinference/thirdparty/deepseek_vl2/models/conversation.py +310 -0
- xinference/thirdparty/deepseek_vl2/models/modeling_deepseek.py +1975 -0
- xinference/thirdparty/deepseek_vl2/models/modeling_deepseek_vl_v2.py +697 -0
- xinference/thirdparty/deepseek_vl2/models/processing_deepseek_vl_v2.py +675 -0
- xinference/thirdparty/deepseek_vl2/models/siglip_vit.py +661 -0
- xinference/thirdparty/deepseek_vl2/serve/__init__.py +0 -0
- xinference/thirdparty/deepseek_vl2/serve/app_modules/__init__.py +0 -0
- xinference/thirdparty/deepseek_vl2/serve/app_modules/gradio_utils.py +83 -0
- xinference/thirdparty/deepseek_vl2/serve/app_modules/overwrites.py +81 -0
- xinference/thirdparty/deepseek_vl2/serve/app_modules/presets.py +115 -0
- xinference/thirdparty/deepseek_vl2/serve/app_modules/utils.py +333 -0
- xinference/thirdparty/deepseek_vl2/serve/assets/Kelpy-Codos.js +100 -0
- xinference/thirdparty/deepseek_vl2/serve/assets/avatar.png +0 -0
- xinference/thirdparty/deepseek_vl2/serve/assets/custom.css +355 -0
- xinference/thirdparty/deepseek_vl2/serve/assets/custom.js +22 -0
- xinference/thirdparty/deepseek_vl2/serve/assets/favicon.ico +0 -0
- xinference/thirdparty/deepseek_vl2/serve/assets/simsun.ttc +0 -0
- xinference/thirdparty/deepseek_vl2/serve/inference.py +197 -0
- xinference/thirdparty/deepseek_vl2/utils/__init__.py +18 -0
- xinference/thirdparty/deepseek_vl2/utils/io.py +80 -0
- xinference/web/ui/build/asset-manifest.json +3 -3
- xinference/web/ui/build/index.html +1 -1
- xinference/web/ui/build/static/js/{main.3cea968e.js → main.5ca4eea1.js} +3 -3
- xinference/web/ui/build/static/js/main.5ca4eea1.js.map +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/0f0967acaec5df1d45b80010949c258d64297ebbb0f44b8bb3afcbd45c6f0ec4.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/68249645124f37d01eef83b1d897e751f895bea919b6fb466f907c1f87cebc84.json +1 -0
- {xinference-1.4.0.dist-info → xinference-1.4.1.dist-info}/METADATA +4 -4
- {xinference-1.4.0.dist-info → xinference-1.4.1.dist-info}/RECORD +56 -31
- xinference/web/ui/build/static/js/main.3cea968e.js.map +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/7f59e45e3f268ab8a4788b6fb024cf8dab088736dff22f5a3a39c122a83ab930.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/dcd60488509450bfff37bfff56de2c096d51de17dd00ec60d4db49c8b483ada1.json +0 -1
- /xinference/web/ui/build/static/js/{main.3cea968e.js.LICENSE.txt → main.5ca4eea1.js.LICENSE.txt} +0 -0
- {xinference-1.4.0.dist-info → xinference-1.4.1.dist-info}/LICENSE +0 -0
- {xinference-1.4.0.dist-info → xinference-1.4.1.dist-info}/WHEEL +0 -0
- {xinference-1.4.0.dist-info → xinference-1.4.1.dist-info}/entry_points.txt +0 -0
- {xinference-1.4.0.dist-info → xinference-1.4.1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,675 @@
|
|
|
1
|
+
# Copyright (c) 2023-2024 DeepSeek.
|
|
2
|
+
#
|
|
3
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
4
|
+
# this software and associated documentation files (the "Software"), to deal in
|
|
5
|
+
# the Software without restriction, including without limitation the rights to
|
|
6
|
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
7
|
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
|
8
|
+
# subject to the following conditions:
|
|
9
|
+
#
|
|
10
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
# copies or substantial portions of the Software.
|
|
12
|
+
#
|
|
13
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
15
|
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
16
|
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
17
|
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
18
|
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
19
|
+
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from typing import Dict, Tuple, List, Literal, Optional
|
|
22
|
+
import math
|
|
23
|
+
|
|
24
|
+
import torch
|
|
25
|
+
from torch.nn.utils.rnn import pad_sequence
|
|
26
|
+
import torchvision.transforms as T
|
|
27
|
+
from transformers import LlamaTokenizerFast
|
|
28
|
+
from transformers.processing_utils import ProcessorMixin
|
|
29
|
+
from PIL import Image, ImageOps
|
|
30
|
+
|
|
31
|
+
from .conversation import get_conv_template
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def select_best_resolution(image_size, candidate_resolutions):
|
|
35
|
+
# used for cropping
|
|
36
|
+
original_width, original_height = image_size
|
|
37
|
+
best_fit = None
|
|
38
|
+
max_effective_resolution = 0
|
|
39
|
+
min_wasted_resolution = float("inf")
|
|
40
|
+
|
|
41
|
+
for width, height in candidate_resolutions:
|
|
42
|
+
scale = min(width / original_width, height / original_height)
|
|
43
|
+
downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
|
|
44
|
+
effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
|
|
45
|
+
wasted_resolution = (width * height) - effective_resolution
|
|
46
|
+
|
|
47
|
+
if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
|
|
48
|
+
max_effective_resolution = effective_resolution
|
|
49
|
+
min_wasted_resolution = wasted_resolution
|
|
50
|
+
best_fit = (width, height)
|
|
51
|
+
|
|
52
|
+
return best_fit
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class DictOutput(object):
|
|
56
|
+
def keys(self):
|
|
57
|
+
return self.__dict__.keys()
|
|
58
|
+
|
|
59
|
+
def __getitem__(self, item):
|
|
60
|
+
return self.__dict__[item]
|
|
61
|
+
|
|
62
|
+
def __setitem__(self, key, value):
|
|
63
|
+
self.__dict__[key] = value
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# 对于inference sample也可以维护input_ids,反正最后不会用到
|
|
67
|
+
@dataclass
|
|
68
|
+
class VLChatProcessorOutput(DictOutput):
|
|
69
|
+
sft_format: str
|
|
70
|
+
input_ids: torch.LongTensor
|
|
71
|
+
target_ids: torch.LongTensor
|
|
72
|
+
images: torch.Tensor
|
|
73
|
+
images_seq_mask: torch.BoolTensor
|
|
74
|
+
images_spatial_crop: torch.LongTensor
|
|
75
|
+
num_image_tokens: List[int]
|
|
76
|
+
|
|
77
|
+
def __len__(self):
|
|
78
|
+
return len(self.input_ids)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class BatchCollateOutput(DictOutput):
|
|
83
|
+
sft_format: List[str]
|
|
84
|
+
input_ids: torch.LongTensor
|
|
85
|
+
labels: torch.LongTensor
|
|
86
|
+
images: torch.Tensor
|
|
87
|
+
attention_mask: torch.Tensor
|
|
88
|
+
images_seq_mask: torch.BoolTensor
|
|
89
|
+
images_spatial_crop: torch.LongTensor
|
|
90
|
+
seq_lens: List[int]
|
|
91
|
+
|
|
92
|
+
def to(self, device, dtype=torch.bfloat16):
|
|
93
|
+
self.input_ids = self.input_ids.to(device)
|
|
94
|
+
self.labels = self.labels.to(device)
|
|
95
|
+
self.attention_mask = self.attention_mask.to(device)
|
|
96
|
+
self.images_seq_mask = self.images_seq_mask.to(device)
|
|
97
|
+
self.images_spatial_crop = self.images_spatial_crop.to(device)
|
|
98
|
+
self.images = self.images.to(device=device, dtype=dtype)
|
|
99
|
+
return self
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class ImageTransform(object):
|
|
103
|
+
def __init__(
|
|
104
|
+
self,
|
|
105
|
+
mean: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5),
|
|
106
|
+
std: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5),
|
|
107
|
+
normalize: bool = True
|
|
108
|
+
):
|
|
109
|
+
self.mean = mean
|
|
110
|
+
self.std = std
|
|
111
|
+
self.normalize = normalize
|
|
112
|
+
|
|
113
|
+
transform_pipelines = [
|
|
114
|
+
T.ToTensor()
|
|
115
|
+
]
|
|
116
|
+
|
|
117
|
+
if normalize:
|
|
118
|
+
transform_pipelines.append(T.Normalize(mean, std))
|
|
119
|
+
|
|
120
|
+
self.transform = T.Compose(transform_pipelines)
|
|
121
|
+
|
|
122
|
+
def __call__(self, pil_img: Image.Image):
|
|
123
|
+
x = self.transform(pil_img)
|
|
124
|
+
return x
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class DeepseekVLV2Processor(ProcessorMixin):
|
|
129
|
+
tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")
|
|
130
|
+
attributes = ["tokenizer"]
|
|
131
|
+
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
tokenizer: LlamaTokenizerFast,
|
|
135
|
+
candidate_resolutions: Tuple[Tuple[int, int]],
|
|
136
|
+
patch_size: int,
|
|
137
|
+
downsample_ratio: int,
|
|
138
|
+
image_mean: Tuple[float, float, float] = (0.5, 0.5, 0.5),
|
|
139
|
+
image_std: Tuple[float, float, float] = (0.5, 0.5, 0.5),
|
|
140
|
+
normalize: bool = True,
|
|
141
|
+
image_token: str = "<image>",
|
|
142
|
+
pad_token: str = "<|▁pad▁|>",
|
|
143
|
+
add_special_token: bool = False,
|
|
144
|
+
sft_format: str = "deepseek",
|
|
145
|
+
mask_prompt: bool = True,
|
|
146
|
+
ignore_id: int = -100,
|
|
147
|
+
**kwargs,
|
|
148
|
+
):
|
|
149
|
+
|
|
150
|
+
self.candidate_resolutions = candidate_resolutions
|
|
151
|
+
self.image_size = candidate_resolutions[0][0]
|
|
152
|
+
self.patch_size = patch_size
|
|
153
|
+
self.image_mean = image_mean
|
|
154
|
+
self.image_std = image_std
|
|
155
|
+
self.normalize = normalize
|
|
156
|
+
self.downsample_ratio = downsample_ratio
|
|
157
|
+
|
|
158
|
+
self.image_transform = ImageTransform(mean=image_mean, std=image_std, normalize=normalize)
|
|
159
|
+
self.tokenizer = tokenizer
|
|
160
|
+
self.tokenizer.padding_side = 'left' # must set this,padding side with make a difference in batch inference
|
|
161
|
+
|
|
162
|
+
# add the pad_token as special token to use 'tokenizer.pad_token' and 'tokenizer.pad_token_id'
|
|
163
|
+
if tokenizer.pad_token is None:
|
|
164
|
+
self.tokenizer.add_special_tokens({'pad_token': pad_token})
|
|
165
|
+
print(f"Add pad token = ['{pad_token}'] to the tokenizer\n"
|
|
166
|
+
f"{pad_token}:{tokenizer.encode(pad_token, add_special_tokens=False)[0]}")
|
|
167
|
+
|
|
168
|
+
# add image token
|
|
169
|
+
image_token_id = self.tokenizer.vocab.get(image_token)
|
|
170
|
+
if image_token_id is None:
|
|
171
|
+
special_tokens = [image_token]
|
|
172
|
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
|
173
|
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
|
174
|
+
self.image_token_id = self.tokenizer.vocab.get(image_token)
|
|
175
|
+
print(f"Add image token = ['{image_token}'] to the tokenizer\n"
|
|
176
|
+
f"{image_token}:{tokenizer.encode(image_token, add_special_tokens=False)[0]}")
|
|
177
|
+
|
|
178
|
+
# add five special tokens for grounding-related tasks
|
|
179
|
+
# <|ref|>, <|/ref|>, <|det|>, <|/det|>, <|grounding|>
|
|
180
|
+
special_tokens = ['<|ref|>', '<|/ref|>', '<|det|>', '<|/det|>', '<|grounding|>']
|
|
181
|
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
|
182
|
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
|
183
|
+
print(f"Add grounding-related tokens = {special_tokens} to the tokenizer with input_ids\n"
|
|
184
|
+
f"<|ref|>:{tokenizer.encode('<|ref|>', add_special_tokens=False)[0]}\n"
|
|
185
|
+
f"<|/ref|>:{tokenizer.encode('<|/ref|>', add_special_tokens=False)[0]}\n"
|
|
186
|
+
f"<|det|>:{tokenizer.encode('<|det|>', add_special_tokens=False)[0]}\n"
|
|
187
|
+
f"<|/det|>:{tokenizer.encode('<|/det|>', add_special_tokens=False)[0]}\n"
|
|
188
|
+
f"<|grounding|>:{tokenizer.encode('<|grounding|>', add_special_tokens=False)[0]}")
|
|
189
|
+
|
|
190
|
+
# add special tokens for SFT data
|
|
191
|
+
special_tokens = ["<|User|>", "<|Assistant|>"]
|
|
192
|
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
|
193
|
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
|
194
|
+
print(f"Add chat tokens = {special_tokens} to the tokenizer with input_ids\n"
|
|
195
|
+
f"<|User|>:{tokenizer.encode('<|User|>', add_special_tokens=False)[0]}\n"
|
|
196
|
+
f"<|Assistant|>:{tokenizer.encode('<|Assistant|>', add_special_tokens=False)[0]}\n")
|
|
197
|
+
|
|
198
|
+
self.image_token = image_token
|
|
199
|
+
self.pad_token = pad_token
|
|
200
|
+
self.add_special_token = add_special_token
|
|
201
|
+
self.sft_format = sft_format
|
|
202
|
+
self.mask_prompt = mask_prompt
|
|
203
|
+
self.ignore_id = ignore_id
|
|
204
|
+
|
|
205
|
+
super().__init__(
|
|
206
|
+
tokenizer,
|
|
207
|
+
**kwargs,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
def new_chat_template(self):
|
|
211
|
+
conv = get_conv_template(self.sft_format)
|
|
212
|
+
return conv
|
|
213
|
+
|
|
214
|
+
def format_messages(
|
|
215
|
+
self,
|
|
216
|
+
conversations: List[Dict[str, str]],
|
|
217
|
+
sft_format: str = "deepseek",
|
|
218
|
+
system_prompt: str = "",
|
|
219
|
+
):
|
|
220
|
+
"""
|
|
221
|
+
Applies the SFT template to conversation.
|
|
222
|
+
|
|
223
|
+
Args:
|
|
224
|
+
conversations (List[Dict]): A List of messages.
|
|
225
|
+
sft_format (str, optional): The format of the SFT template to use. Defaults to "deepseek".
|
|
226
|
+
system_prompt (str, optional): The system prompt to use in the SFT template. Defaults to "".
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
sft_prompt (str): The formatted text.
|
|
230
|
+
"""
|
|
231
|
+
|
|
232
|
+
conv = get_conv_template(sft_format)
|
|
233
|
+
conv.set_system_message(system_prompt)
|
|
234
|
+
for message in conversations:
|
|
235
|
+
conv.append_message(message["role"], message["content"].strip())
|
|
236
|
+
sft_prompt = conv.get_prompt().strip()
|
|
237
|
+
|
|
238
|
+
return sft_prompt
|
|
239
|
+
|
|
240
|
+
def format_messages_v2(self, messages, pil_images, systems=None):
|
|
241
|
+
"""play the role of format_messages_v2 and get_images_info in the last version"""
|
|
242
|
+
tokenized_data = []
|
|
243
|
+
masked_tokenized_data = [] # labels
|
|
244
|
+
images_list = []
|
|
245
|
+
images_seq_mask = []
|
|
246
|
+
images_spatial_crop = []
|
|
247
|
+
num_image_tokens = []
|
|
248
|
+
|
|
249
|
+
image_index = 0
|
|
250
|
+
|
|
251
|
+
conv = get_conv_template(self.sft_format)
|
|
252
|
+
conv_system_message = conv.system_message
|
|
253
|
+
|
|
254
|
+
for idx, message in enumerate(messages):
|
|
255
|
+
if idx == 0:
|
|
256
|
+
tokenized_data += [self.bos_id]
|
|
257
|
+
masked_tokenized_data += [self.bos_id]
|
|
258
|
+
images_seq_mask += [False]
|
|
259
|
+
conv.system_message = conv_system_message
|
|
260
|
+
else:
|
|
261
|
+
conv.system_message = ''
|
|
262
|
+
|
|
263
|
+
if message['role'] == conv.roles[0] or message['role'] == "user":
|
|
264
|
+
conv.reset_message()
|
|
265
|
+
conv.append_message(conv.roles[0], str(message['content']).strip())
|
|
266
|
+
conv.append_message(conv.roles[1], '')
|
|
267
|
+
formatted_question = conv.get_prompt()
|
|
268
|
+
tokenized_str, images, seq_mask, spatial_crop, n_image_tokens = self.tokenize_with_images(
|
|
269
|
+
formatted_question,
|
|
270
|
+
pil_images[image_index: image_index + formatted_question.count(self.image_token)],
|
|
271
|
+
bos=False,
|
|
272
|
+
eos=False,
|
|
273
|
+
cropping=len(pil_images) <= 2
|
|
274
|
+
)
|
|
275
|
+
image_index += formatted_question.count(self.image_token)
|
|
276
|
+
|
|
277
|
+
tokenized_data += tokenized_str
|
|
278
|
+
if self.mask_prompt:
|
|
279
|
+
masked_tokenized_data += [self.ignore_id] * len(tokenized_str)
|
|
280
|
+
else:
|
|
281
|
+
masked_tokenized_data += tokenized_str
|
|
282
|
+
images_list += images
|
|
283
|
+
images_seq_mask += seq_mask
|
|
284
|
+
images_spatial_crop += spatial_crop
|
|
285
|
+
num_image_tokens += n_image_tokens
|
|
286
|
+
|
|
287
|
+
elif message['role'] == conv.roles[1] or message['role'] == "assistant":
|
|
288
|
+
formatted_answer = message['content'].strip()
|
|
289
|
+
assert formatted_answer.count(
|
|
290
|
+
self.image_token) == 0, f"there should be no {self.image_token} in the assistant's reply, but got {messages}"
|
|
291
|
+
tokenized_str, images, seq_mask, spatial_crop, n_image_tokens = self.tokenize_with_images(
|
|
292
|
+
formatted_answer,
|
|
293
|
+
[],
|
|
294
|
+
bos=False,
|
|
295
|
+
eos=True,
|
|
296
|
+
cropping=len(pil_images) <= 2)
|
|
297
|
+
|
|
298
|
+
tokenized_data += tokenized_str
|
|
299
|
+
masked_tokenized_data += tokenized_str
|
|
300
|
+
images_seq_mask += seq_mask
|
|
301
|
+
|
|
302
|
+
elif message['role'] == 'system' or message['role'] == 'deepseekapi-sys':
|
|
303
|
+
# 如果message里面有system,那就只允许出现在message的第一句,同时conv原本的system就会失效
|
|
304
|
+
assert idx == 0, 'system information should only exist in the begining of the conversation'
|
|
305
|
+
formatted_system = message['content'].strip()
|
|
306
|
+
tokenized_str = self.encode(formatted_system, bos=False, eos=False)
|
|
307
|
+
tokenized_data += tokenized_str
|
|
308
|
+
if self.mask_prompt:
|
|
309
|
+
masked_tokenized_data += [self.ignore_id] * len(tokenized_str)
|
|
310
|
+
else:
|
|
311
|
+
masked_tokenized_data += tokenized_str
|
|
312
|
+
seq_mask = [False] * len(tokenized_str)
|
|
313
|
+
images_seq_mask += seq_mask
|
|
314
|
+
|
|
315
|
+
else:
|
|
316
|
+
assert False, f"Unknown role: {message['role']}"
|
|
317
|
+
|
|
318
|
+
assert len(tokenized_data) == len(
|
|
319
|
+
images_seq_mask), f"format_messages_v2: tokenized_str's length {len(tokenized_str)} is not equal to imags_seq_mask's length {len(images_seq_mask)}"
|
|
320
|
+
assert len(images_spatial_crop) == len(num_image_tokens), f"image number should be compatible"
|
|
321
|
+
|
|
322
|
+
return tokenized_data, masked_tokenized_data, images_list, images_seq_mask, images_spatial_crop, num_image_tokens
|
|
323
|
+
|
|
324
|
+
def format_prompts(
|
|
325
|
+
self,
|
|
326
|
+
prompts: str,
|
|
327
|
+
sft_format: str = "deepseek",
|
|
328
|
+
system_prompt: str = "",
|
|
329
|
+
):
|
|
330
|
+
"""
|
|
331
|
+
Applies the SFT template to prompts.
|
|
332
|
+
|
|
333
|
+
Args:
|
|
334
|
+
prompts (str): the non-sft formatted prompt;
|
|
335
|
+
sft_format (str, optional): The format of the SFT template to use. Defaults to "deepseek".
|
|
336
|
+
system_prompt (str, optional): The system prompt to use in the SFT template. Defaults to "".
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
sft_prompt (str): The formatted text.
|
|
340
|
+
"""
|
|
341
|
+
|
|
342
|
+
conv = get_conv_template(sft_format)
|
|
343
|
+
conv.set_system_message(system_prompt)
|
|
344
|
+
conv.append_message(conv.roles[0], prompts.strip())
|
|
345
|
+
conv.append_message(conv.roles[1], "")
|
|
346
|
+
|
|
347
|
+
sft_prompt = conv.get_prompt().strip()
|
|
348
|
+
|
|
349
|
+
return sft_prompt
|
|
350
|
+
|
|
351
|
+
@property
|
|
352
|
+
def bos_id(self):
|
|
353
|
+
return self.tokenizer.bos_token_id
|
|
354
|
+
|
|
355
|
+
@property
|
|
356
|
+
def eos_id(self):
|
|
357
|
+
return self.tokenizer.eos_token_id
|
|
358
|
+
|
|
359
|
+
@property
|
|
360
|
+
def pad_id(self):
|
|
361
|
+
return self.tokenizer.pad_token_id
|
|
362
|
+
|
|
363
|
+
def encode(self, text: str, bos: bool = True, eos: bool = False):
|
|
364
|
+
t = self.tokenizer.encode(text, add_special_tokens=False)
|
|
365
|
+
|
|
366
|
+
if bos:
|
|
367
|
+
t = [self.bos_id] + t
|
|
368
|
+
if eos:
|
|
369
|
+
t = t + [self.eos_id]
|
|
370
|
+
|
|
371
|
+
return t
|
|
372
|
+
|
|
373
|
+
def decode(self, t: List[int], **kwargs) -> str:
|
|
374
|
+
return self.tokenizer.decode(t, **kwargs)
|
|
375
|
+
|
|
376
|
+
def process_one(
|
|
377
|
+
self,
|
|
378
|
+
prompt: str = None,
|
|
379
|
+
conversations: List[Dict[str, str]] = None,
|
|
380
|
+
images: List[Image.Image] = None,
|
|
381
|
+
apply_sft_format: bool = False,
|
|
382
|
+
inference_mode: bool = True,
|
|
383
|
+
system_prompt: str = "",
|
|
384
|
+
**kwargs,
|
|
385
|
+
):
|
|
386
|
+
"""
|
|
387
|
+
|
|
388
|
+
Args:
|
|
389
|
+
prompt (str): the formatted prompt;
|
|
390
|
+
conversations (List[Dict]): conversations with a list of messages;
|
|
391
|
+
images (List[ImageType]): the list of images;
|
|
392
|
+
apply_sft_format (bool): if prompt is not None, then apply the SFT format to prompt;
|
|
393
|
+
if conversations is not None, then it will always apply the SFT format to conversations;
|
|
394
|
+
inference_mode (bool): if True, then remove the last eos token;
|
|
395
|
+
system_prompt (str): the system prompt;
|
|
396
|
+
**kwargs:
|
|
397
|
+
|
|
398
|
+
Returns:
|
|
399
|
+
outputs (BaseProcessorOutput): the output of the processor,
|
|
400
|
+
- input_ids (torch.LongTensor): [N + image tokens]
|
|
401
|
+
- target_ids (torch.LongTensor): [N + image tokens]
|
|
402
|
+
- images (torch.FloatTensor): [n_images, 3, H, W]
|
|
403
|
+
- image_id (int): the id of the image token
|
|
404
|
+
- num_image_tokens (List[int]): the number of image tokens
|
|
405
|
+
"""
|
|
406
|
+
|
|
407
|
+
assert (
|
|
408
|
+
prompt is None or conversations is None
|
|
409
|
+
), "prompt and conversations cannot be used at the same time."
|
|
410
|
+
|
|
411
|
+
if prompt is None:
|
|
412
|
+
# apply sft format
|
|
413
|
+
sft_format = self.format_messages(
|
|
414
|
+
conversations=conversations,
|
|
415
|
+
sft_format=self.sft_format,
|
|
416
|
+
system_prompt=system_prompt,
|
|
417
|
+
)
|
|
418
|
+
tokenized_str, masked_tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens = self.format_messages_v2(
|
|
419
|
+
conversations, images)
|
|
420
|
+
else:
|
|
421
|
+
if apply_sft_format:
|
|
422
|
+
sft_format = self.format_prompts(
|
|
423
|
+
prompts=prompt,
|
|
424
|
+
sft_format=self.sft_format,
|
|
425
|
+
system_prompt=system_prompt
|
|
426
|
+
)
|
|
427
|
+
else:
|
|
428
|
+
sft_format = prompt
|
|
429
|
+
tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens = self.tokenize_with_images(
|
|
430
|
+
sft_format, images, bos=True, eos=True, cropping=len(images) <= 2)
|
|
431
|
+
masked_tokenized_str = []
|
|
432
|
+
for token_index in tokenized_str:
|
|
433
|
+
if token_index != self.image_token_id:
|
|
434
|
+
masked_tokenized_str.append(token_index)
|
|
435
|
+
else:
|
|
436
|
+
masked_tokenized_str.append(self.ignore_id)
|
|
437
|
+
|
|
438
|
+
assert len(tokenized_str) == len(images_seq_mask) == len(masked_tokenized_str), \
|
|
439
|
+
(f"tokenized_str's length {len(tokenized_str)}, input_ids' length {len(masked_tokenized_str)}, "
|
|
440
|
+
f"imags_seq_mask's length {len(images_seq_mask)}, are not equal")
|
|
441
|
+
|
|
442
|
+
input_ids = torch.LongTensor(tokenized_str)
|
|
443
|
+
target_ids = torch.LongTensor(masked_tokenized_str)
|
|
444
|
+
images_seq_mask = torch.tensor(images_seq_mask, dtype=torch.bool)
|
|
445
|
+
|
|
446
|
+
# set input_ids < 0 | input_ids == self.image_token_id as ignore_id
|
|
447
|
+
target_ids[(input_ids < 0) | (input_ids == self.image_token_id)] = self.ignore_id
|
|
448
|
+
input_ids[input_ids < 0] = self.pad_id
|
|
449
|
+
|
|
450
|
+
if inference_mode:
|
|
451
|
+
# 去掉结尾的eos token
|
|
452
|
+
assert input_ids[-1] == self.eos_id
|
|
453
|
+
input_ids = input_ids[:-1]
|
|
454
|
+
target_ids = target_ids[:-1]
|
|
455
|
+
images_seq_mask = images_seq_mask[:-1]
|
|
456
|
+
|
|
457
|
+
if len(images_list) == 0:
|
|
458
|
+
images = torch.zeros((1, 3, self.image_size, self.image_size))
|
|
459
|
+
images_spatial_crop = torch.zeros((1, 2), dtype=torch.long)
|
|
460
|
+
else:
|
|
461
|
+
images = torch.stack(images_list, dim=0)
|
|
462
|
+
images_spatial_crop = torch.tensor(images_spatial_crop, dtype=torch.long)
|
|
463
|
+
|
|
464
|
+
prepare = VLChatProcessorOutput(
|
|
465
|
+
sft_format=sft_format,
|
|
466
|
+
input_ids=input_ids,
|
|
467
|
+
target_ids=target_ids,
|
|
468
|
+
images=images,
|
|
469
|
+
images_seq_mask=images_seq_mask,
|
|
470
|
+
images_spatial_crop=images_spatial_crop,
|
|
471
|
+
num_image_tokens=num_image_tokens
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
return prepare
|
|
475
|
+
|
|
476
|
+
def __call__(
|
|
477
|
+
self,
|
|
478
|
+
*,
|
|
479
|
+
prompt: str = None,
|
|
480
|
+
conversations: List[Dict[str, str]] = None,
|
|
481
|
+
images: List[Image.Image] = None,
|
|
482
|
+
apply_sft_format: bool = False,
|
|
483
|
+
force_batchify: bool = True,
|
|
484
|
+
inference_mode: bool = True,
|
|
485
|
+
system_prompt: str = "",
|
|
486
|
+
**kwargs,
|
|
487
|
+
):
|
|
488
|
+
"""
|
|
489
|
+
|
|
490
|
+
Args:
|
|
491
|
+
prompt (str): the formatted prompt;
|
|
492
|
+
conversations (List[Dict]): conversations with a list of messages;
|
|
493
|
+
images (List[ImageType]): the list of images;
|
|
494
|
+
apply_sft_format (bool): if prompt is not None, then apply the SFT format to prompt;
|
|
495
|
+
if conversations is not None, then it will always apply the SFT format to conversations;
|
|
496
|
+
force_batchify (bool): force batchify the inputs;
|
|
497
|
+
inference_mode (bool): if True, then remove the last eos token;
|
|
498
|
+
system_prompt (str): the system prompt;
|
|
499
|
+
**kwargs:
|
|
500
|
+
|
|
501
|
+
Returns:
|
|
502
|
+
outputs (BaseProcessorOutput): the output of the processor,
|
|
503
|
+
- input_ids (torch.LongTensor): [N + image tokens]
|
|
504
|
+
- images (torch.FloatTensor): [n_images, 3, H, W]
|
|
505
|
+
- image_id (int): the id of the image token
|
|
506
|
+
- num_image_tokens (List[int]): the number of image tokens
|
|
507
|
+
"""
|
|
508
|
+
|
|
509
|
+
prepare = self.process_one(
|
|
510
|
+
prompt=prompt,
|
|
511
|
+
conversations=conversations,
|
|
512
|
+
images=images,
|
|
513
|
+
apply_sft_format=apply_sft_format,
|
|
514
|
+
inference_mode=inference_mode,
|
|
515
|
+
system_prompt=system_prompt
|
|
516
|
+
)
|
|
517
|
+
|
|
518
|
+
if force_batchify:
|
|
519
|
+
prepare = self.batchify([prepare])
|
|
520
|
+
|
|
521
|
+
return prepare
|
|
522
|
+
|
|
523
|
+
def tokenize_with_images(
|
|
524
|
+
self,
|
|
525
|
+
conversation: str,
|
|
526
|
+
images: List[Image.Image],
|
|
527
|
+
bos: bool = True,
|
|
528
|
+
eos: bool = True,
|
|
529
|
+
cropping: bool = True,
|
|
530
|
+
):
|
|
531
|
+
"""Tokenize text with <image> tags."""
|
|
532
|
+
assert conversation.count(self.image_token) == len(images)
|
|
533
|
+
text_splits = conversation.split(self.image_token)
|
|
534
|
+
images_list, images_seq_mask, images_spatial_crop = [], [], []
|
|
535
|
+
num_image_tokens = []
|
|
536
|
+
tokenized_str = []
|
|
537
|
+
for text_sep, image in zip(text_splits, images):
|
|
538
|
+
"""encode text_sep"""
|
|
539
|
+
tokenized_sep = self.encode(text_sep, bos=False, eos=False)
|
|
540
|
+
tokenized_str += tokenized_sep
|
|
541
|
+
images_seq_mask += [False] * len(tokenized_sep)
|
|
542
|
+
|
|
543
|
+
"""select best resolution for anyres"""
|
|
544
|
+
if cropping:
|
|
545
|
+
best_width, best_height = select_best_resolution(image.size, self.candidate_resolutions)
|
|
546
|
+
else:
|
|
547
|
+
best_width, best_height = self.image_size, self.image_size
|
|
548
|
+
# print(image.size, (best_width, best_height)) # check the select_best_resolutions func
|
|
549
|
+
|
|
550
|
+
"""process the global view"""
|
|
551
|
+
global_view = ImageOps.pad(image, (self.image_size, self.image_size),
|
|
552
|
+
color=tuple(int(x * 255) for x in self.image_transform.mean))
|
|
553
|
+
images_list.append(self.image_transform(global_view))
|
|
554
|
+
|
|
555
|
+
"""process the local views"""
|
|
556
|
+
local_view = ImageOps.pad(image, (best_width, best_height),
|
|
557
|
+
color=tuple(int(x * 255) for x in self.image_transform.mean))
|
|
558
|
+
for i in range(0, best_height, self.image_size):
|
|
559
|
+
for j in range(0, best_width, self.image_size):
|
|
560
|
+
images_list.append(
|
|
561
|
+
self.image_transform(local_view.crop((j, i, j + self.image_size, i + self.image_size))))
|
|
562
|
+
|
|
563
|
+
"""record height / width crop num"""
|
|
564
|
+
num_width_tiles, num_height_tiles = best_width // self.image_size, best_height // self.image_size
|
|
565
|
+
images_spatial_crop.append([num_width_tiles, num_height_tiles])
|
|
566
|
+
|
|
567
|
+
"""add image tokens"""
|
|
568
|
+
h = w = math.ceil((self.image_size // self.patch_size) / self.downsample_ratio)
|
|
569
|
+
# global views tokens h * (w + 1), 1 is for line seperator
|
|
570
|
+
tokenized_image = [self.image_token_id] * h * (w + 1)
|
|
571
|
+
# add a seperator between global and local views
|
|
572
|
+
tokenized_image += [self.image_token_id]
|
|
573
|
+
# local views tokens, (num_height_tiles * h) * (num_width_tiles * w + 1)
|
|
574
|
+
tokenized_image += [self.image_token_id] * (num_height_tiles * h) * (num_width_tiles * w + 1)
|
|
575
|
+
|
|
576
|
+
tokenized_str += tokenized_image
|
|
577
|
+
images_seq_mask += [True] * len(tokenized_image)
|
|
578
|
+
num_image_tokens.append(len(tokenized_image))
|
|
579
|
+
# print(width_crop_num, height_crop_num, len(tokenized_image)) # test the correctness of the number of image-related tokens
|
|
580
|
+
|
|
581
|
+
"""process the last text split"""
|
|
582
|
+
tokenized_sep = self.encode(text_splits[-1], bos=False, eos=False)
|
|
583
|
+
tokenized_str += tokenized_sep
|
|
584
|
+
images_seq_mask += [False] * len(tokenized_sep)
|
|
585
|
+
|
|
586
|
+
"""add the bos and eos tokens"""
|
|
587
|
+
if bos:
|
|
588
|
+
tokenized_str = [self.bos_id] + tokenized_str
|
|
589
|
+
images_seq_mask = [False] + images_seq_mask
|
|
590
|
+
if eos:
|
|
591
|
+
tokenized_str = tokenized_str + [self.eos_id]
|
|
592
|
+
images_seq_mask = images_seq_mask + [False]
|
|
593
|
+
|
|
594
|
+
assert len(tokenized_str) == len(
|
|
595
|
+
images_seq_mask), f"tokenize_with_images func: tokenized_str's length {len(tokenized_str)} is not equal to imags_seq_mask's length {len(images_seq_mask)}"
|
|
596
|
+
|
|
597
|
+
return tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens
|
|
598
|
+
|
|
599
|
+
def batchify(
|
|
600
|
+
self,
|
|
601
|
+
sample_list: List[VLChatProcessorOutput],
|
|
602
|
+
padding: Literal["left", "right"] = "left"
|
|
603
|
+
) -> BatchCollateOutput:
|
|
604
|
+
"""
|
|
605
|
+
Preprocesses the inputs for multimodal inference.
|
|
606
|
+
|
|
607
|
+
Args:
|
|
608
|
+
sample_list (List[VLChatProcessorOutput]): A list of VLChatProcessorOutput.
|
|
609
|
+
padding (str): The padding method. Defaults to "left".
|
|
610
|
+
|
|
611
|
+
Returns:
|
|
612
|
+
BatchCollateOutput: A dictionary of the inputs to use for multimodal inference.
|
|
613
|
+
"""
|
|
614
|
+
|
|
615
|
+
batched_sft_format = [sample.sft_format for sample in sample_list]
|
|
616
|
+
batched_input_ids = [sample.input_ids for sample in sample_list]
|
|
617
|
+
batched_labels = [sample.target_ids for sample in sample_list]
|
|
618
|
+
batched_images_seq_mask = [sample["images_seq_mask"] for sample in sample_list]
|
|
619
|
+
seq_lens = [len(sample) for sample in sample_list]
|
|
620
|
+
|
|
621
|
+
"""padding input_ids and images_seq_mask"""
|
|
622
|
+
if padding == "left":
|
|
623
|
+
# the tokenizer is default to pad at left
|
|
624
|
+
## TODO, You're using a LlamaTokenizerFast tokenizer.
|
|
625
|
+
# Please note that with a fast tokenizer, using the `__call__` method is faster than
|
|
626
|
+
# using a method to encode the text followed by a call to the `pad` method to get a padded encoding.
|
|
627
|
+
padded_input_ids = self.tokenizer.pad({"input_ids": batched_input_ids})
|
|
628
|
+
batched_input_ids, batched_attention_mask = padded_input_ids["input_ids"], padded_input_ids[
|
|
629
|
+
"attention_mask"].bool()
|
|
630
|
+
batched_labels = self.tokenizer.pad({"input_ids": batched_labels})["input_ids"]
|
|
631
|
+
batched_labels[batched_labels == self.pad_id] = self.ignore_id # labels正常不会出现pad_id,无需额外保护
|
|
632
|
+
batched_images_seq_mask = self.tokenizer.pad({"input_ids": batched_images_seq_mask})["input_ids"]
|
|
633
|
+
batched_images_seq_mask[batched_images_seq_mask == self.pad_id] = False
|
|
634
|
+
else:
|
|
635
|
+
batched_input_ids = pad_sequence(batched_input_ids, batch_first=True, padding_value=self.pad_id)
|
|
636
|
+
batched_labels = pad_sequence(batched_labels, batch_first=True, padding_value=self.ignore_id)
|
|
637
|
+
batched_images_seq_mask = pad_sequence(batched_images_seq_mask, batch_first=True, padding_value=0)
|
|
638
|
+
batched_attention_mask = batched_input_ids != self.pad_id
|
|
639
|
+
|
|
640
|
+
"""padding images to max_patch_num"""
|
|
641
|
+
max_n_patches = max(sample["images"].shape[0] for sample in sample_list)
|
|
642
|
+
batched_images = []
|
|
643
|
+
for sample in sample_list:
|
|
644
|
+
images = sample["images"]
|
|
645
|
+
n_pads = max_n_patches - images.shape[0]
|
|
646
|
+
if n_pads > 0:
|
|
647
|
+
pad_images = torch.zeros((n_pads, *images.shape[1:]), dtype=images.dtype)
|
|
648
|
+
images = torch.cat([images, pad_images], dim=0)
|
|
649
|
+
batched_images.append(images)
|
|
650
|
+
batched_images = torch.stack(batched_images, dim=0)
|
|
651
|
+
|
|
652
|
+
"""padding images_spatial_crop to max_n_images"""
|
|
653
|
+
max_n_images = max(sample["images_spatial_crop"].shape[0] for sample in sample_list)
|
|
654
|
+
batched_images_spatial_crop = []
|
|
655
|
+
for sample in sample_list:
|
|
656
|
+
images_spatial_crop = sample["images_spatial_crop"]
|
|
657
|
+
n_pads = max_n_images - sample["images_spatial_crop"].shape[0]
|
|
658
|
+
if n_pads > 0:
|
|
659
|
+
pad_images_spatial_crop = torch.full((n_pads, 2), 0, dtype=images_spatial_crop.dtype)
|
|
660
|
+
images_spatial_crop = torch.cat([images_spatial_crop, pad_images_spatial_crop], dim=0)
|
|
661
|
+
batched_images_spatial_crop.append(images_spatial_crop)
|
|
662
|
+
batched_images_spatial_crop = torch.stack(batched_images_spatial_crop, dim=0)
|
|
663
|
+
|
|
664
|
+
batched_samples = BatchCollateOutput(
|
|
665
|
+
input_ids=batched_input_ids,
|
|
666
|
+
attention_mask=batched_attention_mask,
|
|
667
|
+
labels=batched_labels,
|
|
668
|
+
images=batched_images,
|
|
669
|
+
images_seq_mask=batched_images_seq_mask,
|
|
670
|
+
images_spatial_crop=batched_images_spatial_crop,
|
|
671
|
+
sft_format=batched_sft_format,
|
|
672
|
+
seq_lens=seq_lens
|
|
673
|
+
)
|
|
674
|
+
|
|
675
|
+
return batched_samples
|