xinference 0.9.4__py3-none-any.whl → 0.10.0__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/_version.py +3 -3
- xinference/api/oauth2/auth_service.py +47 -18
- xinference/api/oauth2/types.py +1 -0
- xinference/api/restful_api.py +9 -1
- xinference/client/restful/restful_client.py +12 -2
- xinference/conftest.py +13 -2
- xinference/core/supervisor.py +32 -1
- xinference/core/worker.py +139 -20
- xinference/deploy/cmdline.py +119 -20
- xinference/model/llm/__init__.py +4 -0
- xinference/model/llm/llm_family.json +627 -0
- xinference/model/llm/llm_family_modelscope.json +471 -0
- xinference/model/llm/pytorch/core.py +2 -0
- xinference/model/llm/pytorch/deepseek_vl.py +232 -0
- xinference/model/llm/pytorch/omnilmm.py +153 -0
- xinference/model/llm/utils.py +11 -1
- xinference/model/llm/vllm/core.py +3 -0
- xinference/thirdparty/deepseek_vl/__init__.py +31 -0
- xinference/thirdparty/deepseek_vl/models/__init__.py +28 -0
- xinference/thirdparty/deepseek_vl/models/clip_encoder.py +242 -0
- xinference/thirdparty/deepseek_vl/models/image_processing_vlm.py +208 -0
- xinference/thirdparty/deepseek_vl/models/modeling_vlm.py +170 -0
- xinference/thirdparty/deepseek_vl/models/processing_vlm.py +390 -0
- xinference/thirdparty/deepseek_vl/models/projector.py +100 -0
- xinference/thirdparty/deepseek_vl/models/sam.py +593 -0
- xinference/thirdparty/deepseek_vl/models/siglip_vit.py +681 -0
- xinference/thirdparty/deepseek_vl/utils/__init__.py +18 -0
- xinference/thirdparty/deepseek_vl/utils/conversation.py +348 -0
- xinference/thirdparty/deepseek_vl/utils/io.py +78 -0
- xinference/thirdparty/omnilmm/__init__.py +0 -0
- xinference/thirdparty/omnilmm/chat.py +216 -0
- xinference/thirdparty/omnilmm/constants.py +4 -0
- xinference/thirdparty/omnilmm/conversation.py +332 -0
- xinference/thirdparty/omnilmm/model/__init__.py +1 -0
- xinference/thirdparty/omnilmm/model/omnilmm.py +594 -0
- xinference/thirdparty/omnilmm/model/resampler.py +166 -0
- xinference/thirdparty/omnilmm/model/utils.py +563 -0
- xinference/thirdparty/omnilmm/train/__init__.py +13 -0
- xinference/thirdparty/omnilmm/train/train_utils.py +150 -0
- xinference/thirdparty/omnilmm/utils.py +134 -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.98516614.js +3 -0
- xinference/web/ui/build/static/js/main.98516614.js.map +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/139969fd25258eb7decc9505f30b779089bba50c402bb5c663008477c7bff73b.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/3f357ab57b8e7fade54c667f0e0ebf2787566f72bfdca0fea14e395b5c203753.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/9d7c49815d97539207e5aab2fb967591b5fed7791218a0762539efc9491f36af.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/d0d0b591d9adaf42b83ad6633f8b7c118541a4b80ea957c303d3bf9b86fbad0a.json +1 -0
- {xinference-0.9.4.dist-info → xinference-0.10.0.dist-info}/METADATA +18 -5
- {xinference-0.9.4.dist-info → xinference-0.10.0.dist-info}/RECORD +55 -28
- xinference/web/ui/build/static/js/main.66b1c4fb.js +0 -3
- xinference/web/ui/build/static/js/main.66b1c4fb.js.map +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/c2124cfe036b26befcbd386d1d17743b1a58d0b7a041a17bb67f9924400d63c3.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/fd4a8ae5d192331af1bedd1d2d70efcc569708ee6cc4cb479b225d059482aa81.json +0 -1
- /xinference/web/ui/build/static/js/{main.66b1c4fb.js.LICENSE.txt → main.98516614.js.LICENSE.txt} +0 -0
- {xinference-0.9.4.dist-info → xinference-0.10.0.dist-info}/LICENSE +0 -0
- {xinference-0.9.4.dist-info → xinference-0.10.0.dist-info}/WHEEL +0 -0
- {xinference-0.9.4.dist-info → xinference-0.10.0.dist-info}/entry_points.txt +0 -0
- {xinference-0.9.4.dist-info → xinference-0.10.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,390 @@
|
|
|
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, List
|
|
22
|
+
|
|
23
|
+
import torch
|
|
24
|
+
from PIL.Image import Image
|
|
25
|
+
from transformers import LlamaTokenizerFast
|
|
26
|
+
from transformers.processing_utils import ProcessorMixin
|
|
27
|
+
|
|
28
|
+
from .image_processing_vlm import VLMImageProcessor
|
|
29
|
+
from ..utils.conversation import get_conv_template
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class DictOutput(object):
|
|
33
|
+
def keys(self):
|
|
34
|
+
return self.__dict__.keys()
|
|
35
|
+
|
|
36
|
+
def __getitem__(self, item):
|
|
37
|
+
return self.__dict__[item]
|
|
38
|
+
|
|
39
|
+
def __setitem__(self, key, value):
|
|
40
|
+
self.__dict__[key] = value
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class VLChatProcessorOutput(DictOutput):
|
|
45
|
+
sft_format: str
|
|
46
|
+
input_ids: torch.Tensor
|
|
47
|
+
pixel_values: torch.Tensor
|
|
48
|
+
num_image_tokens: torch.IntTensor
|
|
49
|
+
|
|
50
|
+
def __len__(self):
|
|
51
|
+
return len(self.input_ids)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class BatchedVLChatProcessorOutput(DictOutput):
|
|
56
|
+
sft_format: List[str]
|
|
57
|
+
input_ids: torch.Tensor
|
|
58
|
+
pixel_values: torch.Tensor
|
|
59
|
+
attention_mask: torch.Tensor
|
|
60
|
+
images_seq_mask: torch.BoolTensor
|
|
61
|
+
images_emb_mask: torch.BoolTensor
|
|
62
|
+
|
|
63
|
+
def to(self, device, dtype=torch.bfloat16):
|
|
64
|
+
self.input_ids = self.input_ids.to(device)
|
|
65
|
+
self.attention_mask = self.attention_mask.to(device)
|
|
66
|
+
self.images_seq_mask = self.images_seq_mask.to(device)
|
|
67
|
+
self.images_emb_mask = self.images_emb_mask.to(device)
|
|
68
|
+
self.pixel_values = self.pixel_values.to(device=device, dtype=dtype)
|
|
69
|
+
return self
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class VLChatProcessor(ProcessorMixin):
|
|
73
|
+
image_processor_class = "AutoImageProcessor"
|
|
74
|
+
tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")
|
|
75
|
+
|
|
76
|
+
attributes = ["image_processor", "tokenizer"]
|
|
77
|
+
|
|
78
|
+
system_prompt = (
|
|
79
|
+
"You are a helpful language and vision assistant. "
|
|
80
|
+
"You are able to understand the visual content that the user provides, "
|
|
81
|
+
"and assist the user with a variety of tasks using natural language."
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
image_processor: VLMImageProcessor,
|
|
87
|
+
tokenizer: LlamaTokenizerFast,
|
|
88
|
+
image_tag: str = "<image_placeholder>",
|
|
89
|
+
num_image_tokens: int = 576,
|
|
90
|
+
add_special_token: bool = False,
|
|
91
|
+
sft_format: str = "deepseek",
|
|
92
|
+
mask_prompt: bool = True,
|
|
93
|
+
ignore_id: int = -100,
|
|
94
|
+
**kwargs,
|
|
95
|
+
):
|
|
96
|
+
self.image_processor = image_processor
|
|
97
|
+
self.tokenizer = tokenizer
|
|
98
|
+
|
|
99
|
+
image_id = self.tokenizer.vocab.get(image_tag)
|
|
100
|
+
if image_id is None:
|
|
101
|
+
special_tokens = [image_tag]
|
|
102
|
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
|
103
|
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
|
104
|
+
print(f"Add image tag = {image_tag} to the tokenizer")
|
|
105
|
+
|
|
106
|
+
self.image_tag = image_tag
|
|
107
|
+
self.num_image_tokens = num_image_tokens
|
|
108
|
+
self.add_special_token = add_special_token
|
|
109
|
+
self.sft_format = sft_format
|
|
110
|
+
self.mask_prompt = mask_prompt
|
|
111
|
+
self.ignore_id = ignore_id
|
|
112
|
+
|
|
113
|
+
super().__init__(
|
|
114
|
+
image_processor,
|
|
115
|
+
tokenizer,
|
|
116
|
+
image_tag,
|
|
117
|
+
num_image_tokens,
|
|
118
|
+
add_special_token,
|
|
119
|
+
sft_format,
|
|
120
|
+
mask_prompt,
|
|
121
|
+
ignore_id,
|
|
122
|
+
**kwargs,
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def new_chat_template(self):
|
|
126
|
+
conv = get_conv_template(self.sft_format)
|
|
127
|
+
conv.set_system_message(self.system_prompt)
|
|
128
|
+
return conv
|
|
129
|
+
|
|
130
|
+
def apply_sft_template_for_multi_turn_prompts(
|
|
131
|
+
self,
|
|
132
|
+
conversations: List[Dict[str, str]],
|
|
133
|
+
sft_format: str = "deepseek",
|
|
134
|
+
system_prompt: str = "",
|
|
135
|
+
):
|
|
136
|
+
"""
|
|
137
|
+
Applies the SFT template to conversation.
|
|
138
|
+
|
|
139
|
+
An example of conversation:
|
|
140
|
+
conversation = [
|
|
141
|
+
{
|
|
142
|
+
"role": "User",
|
|
143
|
+
"content": "<image_placeholder> is Figure 1.\n<image_placeholder> is Figure 2.\nWhich image is brighter?",
|
|
144
|
+
"images": [
|
|
145
|
+
"./multi-images/attribute_comparison_1.png",
|
|
146
|
+
"./multi-images/attribute_comparison_2.png"
|
|
147
|
+
]
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
"role": "Assistant",
|
|
151
|
+
"content": ""
|
|
152
|
+
}
|
|
153
|
+
]
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
conversations (List[Dict]): A conversation with a List of Dict[str, str] text.
|
|
157
|
+
sft_format (str, optional): The format of the SFT template to use. Defaults to "deepseek".
|
|
158
|
+
system_prompt (str, optional): The system prompt to use in the SFT template. Defaults to "".
|
|
159
|
+
|
|
160
|
+
Returns:
|
|
161
|
+
sft_prompt (str): The formatted text.
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
conv = get_conv_template(sft_format)
|
|
165
|
+
conv.set_system_message(system_prompt)
|
|
166
|
+
for message in conversations:
|
|
167
|
+
conv.append_message(message["role"], message["content"].strip())
|
|
168
|
+
sft_prompt = conv.get_prompt().strip()
|
|
169
|
+
|
|
170
|
+
return sft_prompt
|
|
171
|
+
|
|
172
|
+
@property
|
|
173
|
+
def image_token(self):
|
|
174
|
+
return self.image_tag
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def image_id(self):
|
|
178
|
+
image_id = self.tokenizer.vocab.get(self.image_tag)
|
|
179
|
+
return image_id
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def pad_id(self):
|
|
183
|
+
pad_id = self.tokenizer.pad_token_id
|
|
184
|
+
if pad_id is None:
|
|
185
|
+
pad_id = self.tokenizer.eos_token_id
|
|
186
|
+
|
|
187
|
+
return pad_id
|
|
188
|
+
|
|
189
|
+
def add_image_token(
|
|
190
|
+
self,
|
|
191
|
+
image_indices: List[int],
|
|
192
|
+
input_ids: torch.LongTensor,
|
|
193
|
+
):
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
Args:
|
|
197
|
+
image_indices (List[int]): [index_0, index_1, ..., index_j]
|
|
198
|
+
input_ids (torch.LongTensor): [N]
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
input_ids (torch.LongTensor): [N + image tokens]
|
|
202
|
+
num_image_tokens (torch.IntTensor): [n_images]
|
|
203
|
+
"""
|
|
204
|
+
|
|
205
|
+
input_slices = []
|
|
206
|
+
|
|
207
|
+
start = 0
|
|
208
|
+
for index in image_indices:
|
|
209
|
+
if self.add_special_token:
|
|
210
|
+
end = index + 1
|
|
211
|
+
else:
|
|
212
|
+
end = index
|
|
213
|
+
|
|
214
|
+
# original text tokens
|
|
215
|
+
input_slices.append(input_ids[start:end])
|
|
216
|
+
|
|
217
|
+
# add image tokens, and set the mask as False
|
|
218
|
+
input_slices.append(
|
|
219
|
+
self.image_id * torch.ones((self.num_image_tokens,), dtype=torch.long)
|
|
220
|
+
)
|
|
221
|
+
start = index + 1
|
|
222
|
+
|
|
223
|
+
# the left part
|
|
224
|
+
input_slices.append(input_ids[start:])
|
|
225
|
+
|
|
226
|
+
# concat all slices
|
|
227
|
+
input_ids = torch.cat(input_slices, dim=0)
|
|
228
|
+
num_image_tokens = torch.IntTensor([self.num_image_tokens] * len(image_indices))
|
|
229
|
+
|
|
230
|
+
return input_ids, num_image_tokens
|
|
231
|
+
|
|
232
|
+
def process_one(
|
|
233
|
+
self,
|
|
234
|
+
prompt: str = None,
|
|
235
|
+
conversations: List[Dict[str, str]] = None,
|
|
236
|
+
images: List[Image] = None,
|
|
237
|
+
**kwargs,
|
|
238
|
+
):
|
|
239
|
+
"""
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
prompt (str): the formatted prompt;
|
|
243
|
+
conversations (List[Dict]): conversations with a list of messages;
|
|
244
|
+
images (List[ImageType]): the list of images;
|
|
245
|
+
**kwargs:
|
|
246
|
+
|
|
247
|
+
Returns:
|
|
248
|
+
outputs (BaseProcessorOutput): the output of the processor,
|
|
249
|
+
- input_ids (torch.LongTensor): [N + image tokens]
|
|
250
|
+
- target_ids (torch.LongTensor): [N + image tokens]
|
|
251
|
+
- images (torch.FloatTensor): [n_images, 3, H, W]
|
|
252
|
+
- image_id (int): the id of the image token
|
|
253
|
+
- num_image_tokens (List[int]): the number of image tokens
|
|
254
|
+
"""
|
|
255
|
+
|
|
256
|
+
assert (
|
|
257
|
+
prompt is None or conversations is None
|
|
258
|
+
), "prompt and conversations cannot be used at the same time."
|
|
259
|
+
|
|
260
|
+
if prompt is None:
|
|
261
|
+
# apply sft format
|
|
262
|
+
sft_format = self.apply_sft_template_for_multi_turn_prompts(
|
|
263
|
+
conversations=conversations,
|
|
264
|
+
sft_format=self.sft_format,
|
|
265
|
+
system_prompt=self.system_prompt,
|
|
266
|
+
)
|
|
267
|
+
else:
|
|
268
|
+
sft_format = prompt
|
|
269
|
+
|
|
270
|
+
# tokenize
|
|
271
|
+
input_ids = self.tokenizer.encode(sft_format)
|
|
272
|
+
input_ids = torch.LongTensor(input_ids)
|
|
273
|
+
|
|
274
|
+
# add image tokens to the input_ids
|
|
275
|
+
image_token_mask: torch.BoolTensor = input_ids == self.image_id
|
|
276
|
+
image_indices = image_token_mask.nonzero()
|
|
277
|
+
input_ids, num_image_tokens = self.add_image_token(
|
|
278
|
+
image_indices=image_indices,
|
|
279
|
+
input_ids=input_ids,
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
# load images
|
|
283
|
+
images_outputs = self.image_processor(images, return_tensors="pt")
|
|
284
|
+
|
|
285
|
+
prepare = VLChatProcessorOutput(
|
|
286
|
+
sft_format=sft_format,
|
|
287
|
+
input_ids=input_ids,
|
|
288
|
+
pixel_values=images_outputs.pixel_values,
|
|
289
|
+
num_image_tokens=num_image_tokens,
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
return prepare
|
|
293
|
+
|
|
294
|
+
def __call__(
|
|
295
|
+
self,
|
|
296
|
+
*,
|
|
297
|
+
prompt: str = None,
|
|
298
|
+
conversations: List[Dict[str, str]] = None,
|
|
299
|
+
images: List[Image] = None,
|
|
300
|
+
force_batchify: bool = True,
|
|
301
|
+
**kwargs,
|
|
302
|
+
):
|
|
303
|
+
"""
|
|
304
|
+
|
|
305
|
+
Args:
|
|
306
|
+
prompt (str): the formatted prompt;
|
|
307
|
+
conversations (List[Dict]): conversations with a list of messages;
|
|
308
|
+
images (List[ImageType]): the list of images;
|
|
309
|
+
force_batchify (bool): force batchify the inputs;
|
|
310
|
+
**kwargs:
|
|
311
|
+
|
|
312
|
+
Returns:
|
|
313
|
+
outputs (BaseProcessorOutput): the output of the processor,
|
|
314
|
+
- input_ids (torch.LongTensor): [N + image tokens]
|
|
315
|
+
- images (torch.FloatTensor): [n_images, 3, H, W]
|
|
316
|
+
- image_id (int): the id of the image token
|
|
317
|
+
- num_image_tokens (List[int]): the number of image tokens
|
|
318
|
+
"""
|
|
319
|
+
|
|
320
|
+
prepare = self.process_one(
|
|
321
|
+
prompt=prompt, conversations=conversations, images=images
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
if force_batchify:
|
|
325
|
+
prepare = self.batchify([prepare])
|
|
326
|
+
|
|
327
|
+
return prepare
|
|
328
|
+
|
|
329
|
+
def batchify(
|
|
330
|
+
self, prepare_list: List[VLChatProcessorOutput]
|
|
331
|
+
) -> BatchedVLChatProcessorOutput:
|
|
332
|
+
"""
|
|
333
|
+
Preprocesses the inputs for multimodal inference.
|
|
334
|
+
|
|
335
|
+
Args:
|
|
336
|
+
prepare_list (List[VLChatProcessorOutput]): A list of VLChatProcessorOutput.
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
BatchedVLChatProcessorOutput: A dictionary of the inputs to use for multimodal inference.
|
|
340
|
+
"""
|
|
341
|
+
|
|
342
|
+
batch_size = len(prepare_list)
|
|
343
|
+
sft_format = []
|
|
344
|
+
n_images = []
|
|
345
|
+
seq_lens = []
|
|
346
|
+
for prepare in prepare_list:
|
|
347
|
+
n_images.append(len(prepare.num_image_tokens))
|
|
348
|
+
seq_lens.append(len(prepare))
|
|
349
|
+
|
|
350
|
+
input_token_max_len = max(seq_lens)
|
|
351
|
+
max_n_images = max(1, max(n_images))
|
|
352
|
+
|
|
353
|
+
batched_input_ids = torch.full(
|
|
354
|
+
(batch_size, input_token_max_len), self.pad_id
|
|
355
|
+
).long() # FIXME
|
|
356
|
+
batched_attention_mask = torch.zeros((batch_size, input_token_max_len)).long()
|
|
357
|
+
batched_pixel_values = torch.zeros(
|
|
358
|
+
(batch_size, max_n_images, *self.image_processor.default_shape)
|
|
359
|
+
).float()
|
|
360
|
+
batched_images_seq_mask = torch.zeros((batch_size, input_token_max_len)).bool()
|
|
361
|
+
batched_images_emb_mask = torch.zeros(
|
|
362
|
+
(batch_size, max_n_images, self.num_image_tokens)
|
|
363
|
+
).bool()
|
|
364
|
+
|
|
365
|
+
for i, prepare in enumerate(prepare_list):
|
|
366
|
+
input_ids = prepare.input_ids
|
|
367
|
+
seq_len = len(prepare)
|
|
368
|
+
n_image = len(prepare.num_image_tokens)
|
|
369
|
+
# left-padding
|
|
370
|
+
batched_attention_mask[i, -seq_len:] = 1
|
|
371
|
+
batched_input_ids[i, -seq_len:] = torch.LongTensor(input_ids)
|
|
372
|
+
batched_images_seq_mask[i, -seq_len:] = input_ids == self.image_id
|
|
373
|
+
|
|
374
|
+
if n_image > 0:
|
|
375
|
+
batched_pixel_values[i, :n_image] = prepare.pixel_values
|
|
376
|
+
for j, n_image_tokens in enumerate(prepare.num_image_tokens):
|
|
377
|
+
batched_images_emb_mask[i, j, :n_image_tokens] = True
|
|
378
|
+
|
|
379
|
+
sft_format.append(prepare.sft_format)
|
|
380
|
+
|
|
381
|
+
batched_prepares = BatchedVLChatProcessorOutput(
|
|
382
|
+
input_ids=batched_input_ids,
|
|
383
|
+
attention_mask=batched_attention_mask,
|
|
384
|
+
pixel_values=batched_pixel_values,
|
|
385
|
+
images_seq_mask=batched_images_seq_mask,
|
|
386
|
+
images_emb_mask=batched_images_emb_mask,
|
|
387
|
+
sft_format=sft_format,
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
return batched_prepares
|
|
@@ -0,0 +1,100 @@
|
|
|
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 typing import Tuple, Union
|
|
21
|
+
|
|
22
|
+
import torch
|
|
23
|
+
import torch.nn as nn
|
|
24
|
+
from attrdict import AttrDict
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class MlpProjector(nn.Module):
|
|
28
|
+
def __init__(self, cfg):
|
|
29
|
+
super().__init__()
|
|
30
|
+
|
|
31
|
+
self.cfg = cfg
|
|
32
|
+
|
|
33
|
+
if cfg.projector_type == "identity":
|
|
34
|
+
modules = nn.Identity()
|
|
35
|
+
|
|
36
|
+
elif cfg.projector_type == "linear":
|
|
37
|
+
modules = nn.Linear(cfg.input_dim, cfg.n_embed)
|
|
38
|
+
|
|
39
|
+
elif cfg.projector_type == "mlp_gelu":
|
|
40
|
+
mlp_depth = cfg.get("depth", 1)
|
|
41
|
+
modules = [nn.Linear(cfg.input_dim, cfg.n_embed)]
|
|
42
|
+
for _ in range(1, mlp_depth):
|
|
43
|
+
modules.append(nn.GELU())
|
|
44
|
+
modules.append(nn.Linear(cfg.n_embed, cfg.n_embed))
|
|
45
|
+
modules = nn.Sequential(*modules)
|
|
46
|
+
|
|
47
|
+
elif cfg.projector_type == "low_high_hybrid_split_mlp_gelu":
|
|
48
|
+
mlp_depth = cfg.get("depth", 1)
|
|
49
|
+
self.high_up_proj = nn.Linear(cfg.input_dim, cfg.n_embed // 2)
|
|
50
|
+
self.low_up_proj = nn.Linear(cfg.input_dim, cfg.n_embed // 2)
|
|
51
|
+
|
|
52
|
+
modules = []
|
|
53
|
+
for _ in range(1, mlp_depth):
|
|
54
|
+
modules.append(nn.GELU())
|
|
55
|
+
modules.append(nn.Linear(cfg.n_embed, cfg.n_embed))
|
|
56
|
+
modules = nn.Sequential(*modules)
|
|
57
|
+
|
|
58
|
+
else:
|
|
59
|
+
raise ValueError(f"Unknown projector type: {cfg.projector_type}")
|
|
60
|
+
|
|
61
|
+
self.layers = modules
|
|
62
|
+
|
|
63
|
+
def forward(
|
|
64
|
+
self, x_or_tuple: Union[Tuple[torch.Tensor, torch.Tensor], torch.Tensor]
|
|
65
|
+
):
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
x_or_tuple (Union[Tuple[torch.Tensor, torch.Tensor], torch.Tensor]: if it is a tuple of torch.Tensor,
|
|
70
|
+
then it comes from the hybrid vision encoder, and x = high_res_x, low_res_x);
|
|
71
|
+
otherwise it is the feature from the single vision encoder.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
x (torch.Tensor): [b, s, c]
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
if isinstance(x_or_tuple, tuple):
|
|
78
|
+
# self.cfg.projector_type == "low_high_hybrid_split_mlp_gelu":
|
|
79
|
+
high_x, low_x = x_or_tuple
|
|
80
|
+
high_x = self.high_up_proj(high_x)
|
|
81
|
+
low_x = self.low_up_proj(low_x)
|
|
82
|
+
x = torch.concat([high_x, low_x], dim=-1)
|
|
83
|
+
else:
|
|
84
|
+
x = x_or_tuple
|
|
85
|
+
|
|
86
|
+
return self.layers(x)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
if __name__ == "__main__":
|
|
90
|
+
cfg = AttrDict(
|
|
91
|
+
input_dim=1024,
|
|
92
|
+
n_embed=2048,
|
|
93
|
+
depth=2,
|
|
94
|
+
projector_type="low_high_hybrid_split_mlp_gelu",
|
|
95
|
+
)
|
|
96
|
+
inputs = (torch.rand(4, 576, 1024), torch.rand(4, 576, 1024))
|
|
97
|
+
|
|
98
|
+
m = MlpProjector(cfg)
|
|
99
|
+
out = m(inputs)
|
|
100
|
+
print(out.shape)
|