xinference 0.9.3__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.

Files changed (64) hide show
  1. xinference/_version.py +3 -3
  2. xinference/api/oauth2/auth_service.py +47 -18
  3. xinference/api/oauth2/types.py +1 -0
  4. xinference/api/restful_api.py +16 -11
  5. xinference/client/restful/restful_client.py +12 -2
  6. xinference/conftest.py +13 -2
  7. xinference/constants.py +2 -0
  8. xinference/core/supervisor.py +32 -1
  9. xinference/core/worker.py +139 -20
  10. xinference/deploy/cmdline.py +119 -20
  11. xinference/model/llm/__init__.py +6 -0
  12. xinference/model/llm/llm_family.json +711 -10
  13. xinference/model/llm/llm_family_modelscope.json +557 -7
  14. xinference/model/llm/pytorch/chatglm.py +2 -1
  15. xinference/model/llm/pytorch/core.py +2 -0
  16. xinference/model/llm/pytorch/deepseek_vl.py +232 -0
  17. xinference/model/llm/pytorch/internlm2.py +2 -1
  18. xinference/model/llm/pytorch/omnilmm.py +153 -0
  19. xinference/model/llm/sglang/__init__.py +13 -0
  20. xinference/model/llm/sglang/core.py +365 -0
  21. xinference/model/llm/utils.py +46 -13
  22. xinference/model/llm/vllm/core.py +10 -0
  23. xinference/thirdparty/deepseek_vl/__init__.py +31 -0
  24. xinference/thirdparty/deepseek_vl/models/__init__.py +28 -0
  25. xinference/thirdparty/deepseek_vl/models/clip_encoder.py +242 -0
  26. xinference/thirdparty/deepseek_vl/models/image_processing_vlm.py +208 -0
  27. xinference/thirdparty/deepseek_vl/models/modeling_vlm.py +170 -0
  28. xinference/thirdparty/deepseek_vl/models/processing_vlm.py +390 -0
  29. xinference/thirdparty/deepseek_vl/models/projector.py +100 -0
  30. xinference/thirdparty/deepseek_vl/models/sam.py +593 -0
  31. xinference/thirdparty/deepseek_vl/models/siglip_vit.py +681 -0
  32. xinference/thirdparty/deepseek_vl/utils/__init__.py +18 -0
  33. xinference/thirdparty/deepseek_vl/utils/conversation.py +348 -0
  34. xinference/thirdparty/deepseek_vl/utils/io.py +78 -0
  35. xinference/thirdparty/omnilmm/__init__.py +0 -0
  36. xinference/thirdparty/omnilmm/chat.py +216 -0
  37. xinference/thirdparty/omnilmm/constants.py +4 -0
  38. xinference/thirdparty/omnilmm/conversation.py +332 -0
  39. xinference/thirdparty/omnilmm/model/__init__.py +1 -0
  40. xinference/thirdparty/omnilmm/model/omnilmm.py +594 -0
  41. xinference/thirdparty/omnilmm/model/resampler.py +166 -0
  42. xinference/thirdparty/omnilmm/model/utils.py +563 -0
  43. xinference/thirdparty/omnilmm/train/__init__.py +13 -0
  44. xinference/thirdparty/omnilmm/train/train_utils.py +150 -0
  45. xinference/thirdparty/omnilmm/utils.py +134 -0
  46. xinference/web/ui/build/asset-manifest.json +3 -3
  47. xinference/web/ui/build/index.html +1 -1
  48. xinference/web/ui/build/static/js/main.98516614.js +3 -0
  49. xinference/web/ui/build/static/js/main.98516614.js.map +1 -0
  50. xinference/web/ui/node_modules/.cache/babel-loader/139969fd25258eb7decc9505f30b779089bba50c402bb5c663008477c7bff73b.json +1 -0
  51. xinference/web/ui/node_modules/.cache/babel-loader/3f357ab57b8e7fade54c667f0e0ebf2787566f72bfdca0fea14e395b5c203753.json +1 -0
  52. xinference/web/ui/node_modules/.cache/babel-loader/9d7c49815d97539207e5aab2fb967591b5fed7791218a0762539efc9491f36af.json +1 -0
  53. xinference/web/ui/node_modules/.cache/babel-loader/d0d0b591d9adaf42b83ad6633f8b7c118541a4b80ea957c303d3bf9b86fbad0a.json +1 -0
  54. {xinference-0.9.3.dist-info → xinference-0.10.0.dist-info}/METADATA +21 -5
  55. {xinference-0.9.3.dist-info → xinference-0.10.0.dist-info}/RECORD +60 -31
  56. xinference/web/ui/build/static/js/main.66b1c4fb.js +0 -3
  57. xinference/web/ui/build/static/js/main.66b1c4fb.js.map +0 -1
  58. xinference/web/ui/node_modules/.cache/babel-loader/c2124cfe036b26befcbd386d1d17743b1a58d0b7a041a17bb67f9924400d63c3.json +0 -1
  59. xinference/web/ui/node_modules/.cache/babel-loader/fd4a8ae5d192331af1bedd1d2d70efcc569708ee6cc4cb479b225d059482aa81.json +0 -1
  60. /xinference/web/ui/build/static/js/{main.66b1c4fb.js.LICENSE.txt → main.98516614.js.LICENSE.txt} +0 -0
  61. {xinference-0.9.3.dist-info → xinference-0.10.0.dist-info}/LICENSE +0 -0
  62. {xinference-0.9.3.dist-info → xinference-0.10.0.dist-info}/WHEEL +0 -0
  63. {xinference-0.9.3.dist-info → xinference-0.10.0.dist-info}/entry_points.txt +0 -0
  64. {xinference-0.9.3.dist-info → xinference-0.10.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,242 @@
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 Dict, List, Literal, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+ import torchvision.transforms
25
+ from einops import rearrange
26
+
27
+ from .sam import create_sam_vit
28
+ from .siglip_vit import create_siglip_vit
29
+
30
+
31
+ class CLIPVisionTower(nn.Module):
32
+ def __init__(
33
+ self,
34
+ model_name: str = "siglip_large_patch16_384",
35
+ image_size: Union[Tuple[int, int], int] = 336,
36
+ select_feature: str = "patch",
37
+ select_layer: int = -2,
38
+ select_layers: list = None,
39
+ ckpt_path: str = "",
40
+ pixel_mean: Optional[List[float]] = None,
41
+ pixel_std: Optional[List[float]] = None,
42
+ **kwargs,
43
+ ):
44
+ super().__init__()
45
+
46
+ self.model_name = model_name
47
+ self.select_feature = select_feature
48
+ self.select_layer = select_layer
49
+ self.select_layers = select_layers
50
+
51
+ vision_tower_params = {
52
+ "model_name": model_name,
53
+ "image_size": image_size,
54
+ "ckpt_path": ckpt_path,
55
+ "select_layer": select_layer,
56
+ }
57
+ vision_tower_params.update(kwargs)
58
+ self.vision_tower, self.forward_kwargs = self.build_vision_tower(
59
+ vision_tower_params
60
+ )
61
+
62
+ if pixel_mean is not None and pixel_std is not None:
63
+ image_norm = torchvision.transforms.Normalize(
64
+ mean=pixel_mean, std=pixel_std
65
+ )
66
+ else:
67
+ image_norm = None
68
+
69
+ self.image_norm = image_norm
70
+
71
+ def build_vision_tower(self, vision_tower_params):
72
+ if self.model_name.startswith("siglip"):
73
+ self.select_feature = "same"
74
+ vision_tower = create_siglip_vit(**vision_tower_params)
75
+ forward_kwargs = dict()
76
+
77
+ elif self.model_name.startswith("sam"):
78
+ vision_tower = create_sam_vit(**vision_tower_params)
79
+ forward_kwargs = dict()
80
+
81
+ else: # huggingface
82
+ from transformers import CLIPVisionModel
83
+
84
+ vision_tower = CLIPVisionModel.from_pretrained(**vision_tower_params)
85
+ forward_kwargs = dict(output_hidden_states=True)
86
+
87
+ return vision_tower, forward_kwargs
88
+
89
+ def feature_select(self, image_forward_outs):
90
+ if isinstance(image_forward_outs, torch.Tensor):
91
+ # the output has been the self.select_layer"s features
92
+ image_features = image_forward_outs
93
+ else:
94
+ image_features = image_forward_outs.hidden_states[self.select_layer]
95
+
96
+ if self.select_feature == "patch":
97
+ # if the output has cls_token
98
+ image_features = image_features[:, 1:]
99
+ elif self.select_feature == "cls_patch":
100
+ image_features = image_features
101
+ elif self.select_feature == "same":
102
+ image_features = image_features
103
+
104
+ else:
105
+ raise ValueError(f"Unexpected select feature: {self.select_feature}")
106
+ return image_features
107
+
108
+ def forward(self, images):
109
+ """
110
+
111
+ Args:
112
+ images (torch.Tensor): [b, 3, H, W]
113
+
114
+ Returns:
115
+ image_features (torch.Tensor): [b, n_patch, d]
116
+ """
117
+
118
+ if self.image_norm is not None:
119
+ images = self.image_norm(images)
120
+
121
+ image_forward_outs = self.vision_tower(images, **self.forward_kwargs)
122
+ image_features = self.feature_select(image_forward_outs)
123
+ return image_features
124
+
125
+
126
+ class HybridVisionTower(nn.Module):
127
+ def __init__(
128
+ self,
129
+ high_res_cfg: Dict,
130
+ low_res_cfg: Dict,
131
+ freeze_high: bool = False,
132
+ freeze_low: bool = False,
133
+ concat_type: Literal["feature", "sequence", "add", "tuple"] = "tuple",
134
+ **ignore_kwargs,
135
+ ):
136
+ super().__init__()
137
+
138
+ self.vision_tower_high = CLIPVisionTower(**high_res_cfg)
139
+ self.vision_tower_low = CLIPVisionTower(**low_res_cfg)
140
+ self.low_res_size = low_res_cfg["image_size"]
141
+ self.concat_type = concat_type
142
+
143
+ self.high_layer_norm = nn.LayerNorm(high_res_cfg.get("output_dim", 1024))
144
+ self.low_layer_norm = nn.LayerNorm(low_res_cfg.get("output_dim", 1024))
145
+
146
+ if freeze_high:
147
+ for p_name, p in self.vision_tower_high.named_parameters():
148
+ p.requires_grad = False
149
+ self.vision_tower_high = self.vision_tower_high.eval()
150
+ else:
151
+ # train donwsamples and neck
152
+ for p_name, p in self.vision_tower_high.named_parameters():
153
+ if "downsamples" in p_name or "neck" in p_name:
154
+ p.requires_grad = True
155
+ else:
156
+ p.requires_grad = False
157
+
158
+ if freeze_low:
159
+ for p in self.vision_tower_low.parameters():
160
+ p.requires_grad = False
161
+ self.vision_tower_low = self.vision_tower_low.eval()
162
+
163
+ self.resize = torchvision.transforms.Resize(self.low_res_size, antialias=True)
164
+
165
+ def forward(self, images: torch.Tensor):
166
+ """
167
+
168
+ Args:
169
+ images (torch.Tensor): [bs, 3, H, W]
170
+
171
+ Returns:
172
+ res (torch.Tensor): [bs, t, c]
173
+ """
174
+
175
+ # [bs, c, h, w]
176
+ high_images = images
177
+
178
+ # [bs, c, h_low, w_low]
179
+ low_images = self.resize(images)
180
+
181
+ # separately run two vision towers
182
+ # run high_res vision tower
183
+ high_res = self.vision_tower_high(high_images)
184
+ # [bs, c, h, w] -> [bs, h*w, c]
185
+ high_res = rearrange(high_res, "b c h w -> b (h w) c")
186
+ # run low_res vision tower
187
+ low_res = self.vision_tower_low(low_images)
188
+
189
+ if self.concat_type == "feature":
190
+ images_features = torch.cat([high_res, low_res], dim=-1)
191
+ elif self.concat_type == "sequence":
192
+ images_features = torch.cat([high_res, low_res], dim=1)
193
+ elif self.concat_type == "add":
194
+ images_features = high_res + low_res
195
+ elif self.concat_type == "tuple":
196
+ images_features = (high_res, low_res)
197
+
198
+ else:
199
+ raise ValueError(
200
+ "Currently only support `feature`, `sequence`, `add` and `tuple` concat type."
201
+ )
202
+
203
+ return images_features
204
+
205
+
206
+ if __name__ == "__main__":
207
+ image_size = 1024
208
+ x = torch.zeros(2, 3, image_size, image_size).bfloat16().cuda()
209
+
210
+ high_res_cfg = dict(
211
+ model_name="sam_b_downsample",
212
+ select_feature="same",
213
+ image_size=image_size,
214
+ pixel_mean=(0.48145466, 0.4578275, 0.40821073),
215
+ pixel_std=(0.26862954, 0.26130258, 0.27577711),
216
+ select_layer=-1,
217
+ ckpt_path="",
218
+ )
219
+
220
+ low_res_cfg = dict(
221
+ model_name="siglip_large_patch16_384",
222
+ select_feature="same",
223
+ image_size=384,
224
+ pixel_mean=(0.5, 0.5, 0.5),
225
+ pixel_std=(0.5, 0.5, 0.5),
226
+ select_layer=-1,
227
+ ckpt_path="",
228
+ )
229
+
230
+ net = (
231
+ HybridVisionTower(
232
+ high_res_cfg=high_res_cfg,
233
+ low_res_cfg=low_res_cfg,
234
+ freeze_high=True,
235
+ freeze_low=True,
236
+ concat_type="tuple",
237
+ )
238
+ .bfloat16()
239
+ .cuda()
240
+ )
241
+ high_x, low_x = net(x)
242
+ print(x.shape, high_x.shape, low_x.shape)
@@ -0,0 +1,208 @@
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 List, Tuple, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+ import torchvision
25
+ import torchvision.transforms.functional
26
+ from PIL import Image
27
+ from transformers import AutoImageProcessor, PretrainedConfig
28
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
29
+ from transformers.image_utils import to_numpy_array
30
+ from transformers.utils import logging
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+ ImageType = Union[np.ndarray, torch.Tensor, Image.Image]
35
+ IMAGENET_MEAN = (0.48145466, 0.4578275, 0.40821073)
36
+ IMAGENET_STD = (0.26862954, 0.26130258, 0.27577711)
37
+ IMAGENET_INCEPTION_MEAN = (0.5, 0.5, 0.5)
38
+ IMAGENET_INCEPTION_STD = (0.5, 0.5, 0.5)
39
+
40
+
41
+ def expand2square(pil_img, background_color):
42
+ width, height = pil_img.size
43
+ if width == height:
44
+ return pil_img
45
+ elif width > height:
46
+ result = Image.new(pil_img.mode, (width, width), background_color)
47
+ result.paste(pil_img, (0, (width - height) // 2))
48
+ return result
49
+ else:
50
+ result = Image.new(pil_img.mode, (height, height), background_color)
51
+ result.paste(pil_img, ((height - width) // 2, 0))
52
+ return result
53
+
54
+
55
+ class VLMImageProcessorConfig(PretrainedConfig):
56
+ model_type = "deepseek_vlm"
57
+ image_size: int
58
+ min_size: int
59
+ image_mean: Union[Tuple[float, float, float], List[float]]
60
+ image_std: Union[Tuple[float, float, float], List[float]]
61
+ rescale_factor: float
62
+ do_normalize: bool
63
+
64
+ def __init__(
65
+ self,
66
+ image_size: int,
67
+ min_size: int = 14,
68
+ image_mean: Union[Tuple[float, float, float], List[float]] = (
69
+ 0.48145466,
70
+ 0.4578275,
71
+ 0.40821073,
72
+ ),
73
+ image_std: Union[Tuple[float, float, float], List[float]] = (
74
+ 0.26862954,
75
+ 0.26130258,
76
+ 0.27577711,
77
+ ),
78
+ rescale_factor: float = 1.0 / 255.0,
79
+ do_normalize: bool = True,
80
+ **kwargs,
81
+ ):
82
+ self.image_size = image_size
83
+ self.min_size = min_size
84
+ self.image_mean = image_mean
85
+ self.image_std = image_std
86
+ self.rescale_factor = rescale_factor
87
+ self.do_normalize = do_normalize
88
+
89
+ super().__init__(**kwargs)
90
+
91
+
92
+ class VLMImageProcessor(BaseImageProcessor):
93
+ model_input_names = ["pixel_values"]
94
+
95
+ def __init__(
96
+ self,
97
+ image_size: int,
98
+ min_size: int = 14,
99
+ image_mean: Union[Tuple[float, float, float], List[float]] = (
100
+ 0.48145466,
101
+ 0.4578275,
102
+ 0.40821073,
103
+ ),
104
+ image_std: Union[Tuple[float, float, float], List[float]] = (
105
+ 0.26862954,
106
+ 0.26130258,
107
+ 0.27577711,
108
+ ),
109
+ rescale_factor: float = 1.0 / 255.0,
110
+ do_normalize: bool = True,
111
+ **kwargs,
112
+ ):
113
+ super().__init__(**kwargs)
114
+
115
+ self.image_size = image_size
116
+ self.rescale_factor = rescale_factor
117
+ self.image_mean = image_mean
118
+ self.image_std = image_std
119
+ self.min_size = min_size
120
+ self.do_normalize = do_normalize
121
+
122
+ if image_mean is None:
123
+ self.background_color = (127, 127, 127)
124
+ else:
125
+ self.background_color = tuple([int(x * 255) for x in image_mean])
126
+
127
+ def resize(self, pil_img: Image) -> np.ndarray:
128
+ """
129
+
130
+ Args:
131
+ pil_img (PIL.Image): [H, W, 3] in PIL.Image in RGB
132
+
133
+ Returns:
134
+ x (np.ndarray): [3, self.image_size, self.image_size]
135
+ """
136
+
137
+ width, height = pil_img.size
138
+ max_size = max(width, height)
139
+
140
+ size = [
141
+ max(int(height / max_size * self.image_size), self.min_size),
142
+ max(int(width / max_size * self.image_size), self.min_size),
143
+ ]
144
+
145
+ if width <= 0 or height <= 0 or size[0] <= 0 or size[1] <= 0:
146
+ print(f"orig size = {pil_img.size}, new size = {size}")
147
+ raise ValueError("Invalid size!")
148
+
149
+ pil_img = torchvision.transforms.functional.resize(
150
+ pil_img,
151
+ size,
152
+ interpolation=torchvision.transforms.functional.InterpolationMode.BICUBIC,
153
+ antialias=True,
154
+ )
155
+
156
+ pil_img = expand2square(pil_img, self.background_color)
157
+ x = to_numpy_array(pil_img)
158
+
159
+ # [H, W, 3] -> [3, H, W]
160
+ x = np.transpose(x, (2, 0, 1))
161
+
162
+ return x
163
+
164
+ def preprocess(self, images, return_tensors: str = "pt", **kwargs) -> BatchFeature:
165
+ # resize and pad to [self.image_size, self.image_size]
166
+ # then convert from [H, W, 3] to [3, H, W]
167
+ images: List[np.ndarray] = [self.resize(image) for image in images]
168
+
169
+ # resacle from [0, 255] -> [0, 1]
170
+ images = [
171
+ self.rescale(
172
+ image=image,
173
+ scale=self.rescale_factor,
174
+ input_data_format="channels_first",
175
+ )
176
+ for image in images
177
+ ]
178
+
179
+ # normalize
180
+ if self.do_normalize:
181
+ images = [
182
+ self.normalize(
183
+ image=image,
184
+ mean=self.image_mean,
185
+ std=self.image_std,
186
+ input_data_format="channels_first",
187
+ )
188
+ for image in images
189
+ ]
190
+
191
+ data = {"pixel_values": images}
192
+ return BatchFeature(data=data, tensor_type=return_tensors)
193
+
194
+ @property
195
+ def default_shape(self):
196
+ return [3, self.image_size, self.image_size]
197
+
198
+
199
+ AutoImageProcessor.register(VLMImageProcessorConfig, VLMImageProcessor)
200
+
201
+
202
+ if __name__ == "__main__":
203
+ image_processor = VLMImageProcessor(
204
+ image_size=1024,
205
+ image_mean=IMAGENET_INCEPTION_MEAN,
206
+ image_std=IMAGENET_INCEPTION_STD,
207
+ do_normalize=True,
208
+ )
@@ -0,0 +1,170 @@
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
+ import torch
21
+ from attrdict import AttrDict
22
+ from einops import rearrange
23
+ from transformers import (
24
+ AutoConfig,
25
+ AutoModelForCausalLM,
26
+ LlamaConfig,
27
+ LlamaForCausalLM,
28
+ PreTrainedModel,
29
+ )
30
+ from transformers.configuration_utils import PretrainedConfig
31
+
32
+ from .clip_encoder import CLIPVisionTower, HybridVisionTower
33
+ from .projector import MlpProjector
34
+
35
+
36
+ def model_name_to_cls(cls_name):
37
+ if "MlpProjector" in cls_name:
38
+ cls = MlpProjector
39
+
40
+ elif "CLIPVisionTower" in cls_name:
41
+ cls = CLIPVisionTower
42
+
43
+ elif "HybridVisionTower" in cls_name:
44
+ cls = HybridVisionTower
45
+
46
+ else:
47
+ raise ValueError(f"class_name {cls_name} is invalid.")
48
+
49
+ return cls
50
+
51
+
52
+ class VisionConfig(PretrainedConfig):
53
+ model_type = "vision"
54
+ cls: str = ""
55
+ params: AttrDict = {}
56
+
57
+ def __init__(self, **kwargs):
58
+ super().__init__(**kwargs)
59
+
60
+ self.cls = kwargs.get("cls", "")
61
+ if not isinstance(self.cls, str):
62
+ self.cls = self.cls.__name__
63
+
64
+ self.params = AttrDict(kwargs.get("params", {}))
65
+
66
+
67
+ class AlignerConfig(PretrainedConfig):
68
+ model_type = "aligner"
69
+ cls: str = ""
70
+ params: AttrDict = {}
71
+
72
+ def __init__(self, **kwargs):
73
+ super().__init__(**kwargs)
74
+
75
+ self.cls = kwargs.get("cls", "")
76
+ if not isinstance(self.cls, str):
77
+ self.cls = self.cls.__name__
78
+
79
+ self.params = AttrDict(kwargs.get("params", {}))
80
+
81
+
82
+ class MultiModalityConfig(PretrainedConfig):
83
+ model_type = "multi_modality"
84
+ vision_config: VisionConfig
85
+ aligner_config: AlignerConfig
86
+ language_config: LlamaConfig
87
+
88
+ def __init__(self, **kwargs):
89
+ super().__init__(**kwargs)
90
+ vision_config = kwargs.get("vision_config", {})
91
+ self.vision_config = VisionConfig(**vision_config)
92
+
93
+ aligner_config = kwargs.get("aligner_config", {})
94
+ self.aligner_config = AlignerConfig(**aligner_config)
95
+
96
+ language_config = kwargs.get("language_config", {})
97
+ if isinstance(language_config, LlamaConfig):
98
+ self.language_config = language_config
99
+ else:
100
+ self.language_config = LlamaConfig(**language_config)
101
+
102
+
103
+ class MultiModalityPreTrainedModel(PreTrainedModel):
104
+ config_class = MultiModalityConfig
105
+ base_model_prefix = "multi_modality"
106
+ _no_split_modules = []
107
+ _skip_keys_device_placement = "past_key_values"
108
+
109
+
110
+ class MultiModalityCausalLM(MultiModalityPreTrainedModel):
111
+ def __init__(self, config: MultiModalityConfig):
112
+ super().__init__(config)
113
+
114
+ vision_config = config.vision_config
115
+ vision_cls = model_name_to_cls(vision_config.cls)
116
+ self.vision_model = vision_cls(**vision_config.params)
117
+
118
+ aligner_config = config.aligner_config
119
+ aligner_cls = model_name_to_cls(aligner_config.cls)
120
+ self.aligner = aligner_cls(aligner_config.params)
121
+
122
+ language_config = config.language_config
123
+ self.language_model = LlamaForCausalLM(language_config)
124
+
125
+ def prepare_inputs_embeds(
126
+ self,
127
+ input_ids: torch.LongTensor,
128
+ pixel_values: torch.FloatTensor,
129
+ images_seq_mask: torch.LongTensor,
130
+ images_emb_mask: torch.LongTensor,
131
+ **kwargs,
132
+ ):
133
+ """
134
+
135
+ Args:
136
+ input_ids (torch.LongTensor): [b, T]
137
+ pixel_values (torch.FloatTensor): [b, n_images, 3, h, w]
138
+ images_seq_mask (torch.BoolTensor): [b, T]
139
+ images_emb_mask (torch.BoolTensor): [b, n_images, n_image_tokens]
140
+
141
+ assert torch.sum(images_seq_mask) == torch.sum(images_emb_mask)
142
+
143
+ Returns:
144
+ input_embeds (torch.Tensor): [b, T, D]
145
+ """
146
+
147
+ bs, n = pixel_values.shape[0:2]
148
+ images = rearrange(pixel_values, "b n c h w -> (b n) c h w")
149
+ # [b x n, T2, D]
150
+ images_embeds = self.aligner(self.vision_model(images))
151
+
152
+ # [b x n, T2, D] -> [b, n x T2, D]
153
+ images_embeds = rearrange(images_embeds, "(b n) t d -> b (n t) d", b=bs, n=n)
154
+ # [b, n, T2] -> [b, n x T2]
155
+ images_emb_mask = rearrange(images_emb_mask, "b n t -> b (n t)")
156
+
157
+ # [b, T, D]
158
+ input_ids[input_ids < 0] = 0 # ignore the image embeddings
159
+ inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
160
+
161
+ # replace with the image embeddings
162
+ inputs_embeds[images_seq_mask] = images_embeds[images_emb_mask]
163
+
164
+ return inputs_embeds
165
+
166
+
167
+ AutoConfig.register("vision", VisionConfig)
168
+ AutoConfig.register("aligner", AlignerConfig)
169
+ AutoConfig.register("multi_modality", MultiModalityConfig)
170
+ AutoModelForCausalLM.register(MultiModalityConfig, MultiModalityCausalLM)