xinference 0.9.4__py3-none-any.whl → 0.10.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/_version.py +3 -3
- xinference/api/oauth2/auth_service.py +47 -18
- xinference/api/oauth2/types.py +1 -0
- xinference/api/restful_api.py +34 -7
- xinference/client/oscar/actor_client.py +4 -3
- xinference/client/restful/restful_client.py +20 -4
- xinference/conftest.py +13 -2
- xinference/core/supervisor.py +48 -1
- xinference/core/worker.py +139 -20
- xinference/deploy/cmdline.py +119 -20
- xinference/model/embedding/core.py +1 -2
- xinference/model/llm/__init__.py +4 -6
- xinference/model/llm/ggml/llamacpp.py +2 -10
- xinference/model/llm/llm_family.json +877 -13
- xinference/model/llm/llm_family.py +15 -0
- xinference/model/llm/llm_family_modelscope.json +571 -0
- xinference/model/llm/pytorch/chatglm.py +2 -0
- xinference/model/llm/pytorch/core.py +22 -26
- xinference/model/llm/pytorch/deepseek_vl.py +232 -0
- xinference/model/llm/pytorch/internlm2.py +2 -0
- xinference/model/llm/pytorch/omnilmm.py +153 -0
- xinference/model/llm/pytorch/qwen_vl.py +2 -0
- xinference/model/llm/pytorch/yi_vl.py +4 -2
- xinference/model/llm/utils.py +53 -5
- xinference/model/llm/vllm/core.py +54 -6
- xinference/model/rerank/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/types.py +15 -19
- xinference/web/ui/build/asset-manifest.json +3 -3
- xinference/web/ui/build/index.html +1 -1
- xinference/web/ui/build/static/js/main.76ef2b17.js +3 -0
- xinference/web/ui/build/static/js/main.76ef2b17.js.map +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/15e2cf8cd8d0989719b6349428ff576f9009ff4c2dcc52378be0bd938e82495e.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/35d0e4a317e5582cbb79d901302e9d706520ac53f8a734c2fd8bfde6eb5a4f02.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/3c2f277c93c5f1638e08db38df0d0fb4e58d1c5571aea03241a5c04ff4094704.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/3fa1f69162f9c6dc0f6a6e21b64d49d6b8e6fa8dfa59a82cf829931c5f97d99f.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/44774c783428f952d8e2e4ad0998a9c5bc16a57cd9c68b7c5ff18aaa5a41d65c.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/5393569d846332075b93b55656716a34f50e0a8c970be789502d7e6c49755fd7.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/59ce49eae0f486af4c5034d4d2f9ca77c3ec3a32ecc560085caf5ef482b5f4c9.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/62e257ed9016471035fa1a7da57c9e2a4250974ed566b4d1295873d747c68eb2.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/63a4c48f0326d071c7772c46598215c006ae41fd3d4ff3577fe717de66ad6e89.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/b9cbcb6d77ba21b22c6950b6fb5b305d23c19cf747f99f7d48b6b046f8f7b1b0.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/d06a96a3c9c32e42689094aa3aaad41c8125894e956b8f84a70fadce6e3f65b3.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/d076fd56cf3b15ed2433e3744b98c6b4e4410a19903d1db4de5bba0e1a1b3347.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/daad8131d91134f6d7aef895a0c9c32e1cb928277cb5aa66c01028126d215be0.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/de0299226173b0662b573f49e3992220f6611947073bd66ac079728a8bc8837d.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/e606671420d2937102c3c34b4b04056c11736408c1d3347b8cf42dfe61fb394b.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/e6eccc9aa641e7da833492e27846dc965f9750281420977dc84654ca6ed221e4.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/e9b52d171223bb59fb918316297a051cdfd42dd453e8260fd918e90bc0a4ebdf.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/f16aec63602a77bd561d0e67fa00b76469ac54b8033754bba114ec5eb3257964.json +1 -0
- {xinference-0.9.4.dist-info → xinference-0.10.1.dist-info}/METADATA +25 -12
- {xinference-0.9.4.dist-info → xinference-0.10.1.dist-info}/RECORD +79 -58
- xinference/model/llm/ggml/ctransformers.py +0 -281
- xinference/model/llm/ggml/ctransformers_util.py +0 -161
- 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/0bd70b1ecf307e2681318e864f4692305b6350c8683863007f4caf2f9ac33b6e.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/0db651c046ef908f45cde73af0dbea0a797d3e35bb57f4a0863b481502103a64.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/18e5d5422e2464abf4a3e6d38164570e2e426e0a921e9a2628bbae81b18da353.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/3d93bd9a74a1ab0cec85af40f9baa5f6a8e7384b9e18c409b95a81a7b45bb7e2.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/3e055de705e397e1d413d7f429589b1a98dd78ef378b97f0cdb462c5f2487d5e.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/4fd24800544873512b540544ae54601240a5bfefd9105ff647855c64f8ad828f.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/52aa27272b4b9968f62666262b47661cb1992336a2aff3b13994cc36877b3ec3.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/60c4b98d8ea7479fb0c94cfd19c8128f17bd7e27a1e73e6dd9adf6e9d88d18eb.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/7e094845f611802b024b57439cbf911038169d06cdf6c34a72a7277f35aa71a4.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/95c8cc049fadd23085d8623e1d43d70b614a4e52217676f186a417dca894aa09.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/98b7ef307f436affe13d75a4f265b27e828ccc2b10ffae6513abe2681bc11971.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/a8070ce4b780b4a044218536e158a9e7192a6c80ff593fdc126fee43f46296b5.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/b400cfc9db57fa6c70cd2bad055b73c5079fde0ed37974009d898083f6af8cd8.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/bd04667474fd9cac2983b03725c218908a6cc0ee9128a5953cd00d26d4877f60.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/c2124cfe036b26befcbd386d1d17743b1a58d0b7a041a17bb67f9924400d63c3.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/c230a727b8f68f0e62616a75e14a3d33026dc4164f2e325a9a8072d733850edb.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/d44a6eb6106e09082b691a315c9f6ce17fcfe25beb7547810e0d271ce3301cd2.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/e1d9b2ae4e1248658704bc6bfc5d6160dcd1a9e771ea4ae8c1fed0aaddeedd29.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/fd4a8ae5d192331af1bedd1d2d70efcc569708ee6cc4cb479b225d059482aa81.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/fe5db70859503a54cbe71f9637e5a314cda88b1f0eecb733b6e6f837697db1ef.json +0 -1
- /xinference/web/ui/build/static/js/{main.66b1c4fb.js.LICENSE.txt → main.76ef2b17.js.LICENSE.txt} +0 -0
- {xinference-0.9.4.dist-info → xinference-0.10.1.dist-info}/LICENSE +0 -0
- {xinference-0.9.4.dist-info → xinference-0.10.1.dist-info}/WHEEL +0 -0
- {xinference-0.9.4.dist-info → xinference-0.10.1.dist-info}/entry_points.txt +0 -0
- {xinference-0.9.4.dist-info → xinference-0.10.1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
2
|
+
# All rights reserved.
|
|
3
|
+
|
|
4
|
+
# This source code is licensed under the license found in the
|
|
5
|
+
# LICENSE file in the root directory of this source tree.
|
|
6
|
+
|
|
7
|
+
import copy
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from functools import partial
|
|
10
|
+
from typing import List, Optional, Tuple, Type, Union
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
import torch.nn as nn
|
|
14
|
+
import torch.nn.functional as F
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MLPBlock(nn.Module):
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
embedding_dim: int,
|
|
21
|
+
mlp_dim: int,
|
|
22
|
+
act: Type[nn.Module] = nn.GELU,
|
|
23
|
+
) -> None:
|
|
24
|
+
super().__init__()
|
|
25
|
+
self.lin1 = nn.Linear(embedding_dim, mlp_dim)
|
|
26
|
+
self.lin2 = nn.Linear(mlp_dim, embedding_dim)
|
|
27
|
+
self.act = act()
|
|
28
|
+
|
|
29
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
30
|
+
return self.lin2(self.act(self.lin1(x)))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
|
|
34
|
+
# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
|
|
35
|
+
class LayerNorm2d(nn.Module):
|
|
36
|
+
def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
|
|
37
|
+
super().__init__()
|
|
38
|
+
self.weight = nn.Parameter(torch.ones(num_channels))
|
|
39
|
+
self.bias = nn.Parameter(torch.zeros(num_channels))
|
|
40
|
+
self.eps = eps
|
|
41
|
+
|
|
42
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
43
|
+
u = x.mean(1, keepdim=True)
|
|
44
|
+
s = (x - u).pow(2).mean(1, keepdim=True)
|
|
45
|
+
x = (x - u) / torch.sqrt(s + self.eps)
|
|
46
|
+
x = self.weight[:, None, None] * x + self.bias[:, None, None]
|
|
47
|
+
return x
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
|
|
51
|
+
class ImageEncoderViT(nn.Module):
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
img_size: int = 1024,
|
|
55
|
+
patch_size: int = 16,
|
|
56
|
+
in_chans: int = 3,
|
|
57
|
+
embed_dim: int = 768,
|
|
58
|
+
depth: int = 12,
|
|
59
|
+
num_heads: int = 12,
|
|
60
|
+
mlp_ratio: float = 4.0,
|
|
61
|
+
out_chans: int = 256,
|
|
62
|
+
qkv_bias: bool = True,
|
|
63
|
+
norm_layer: Type[nn.Module] = nn.LayerNorm,
|
|
64
|
+
act_layer: Type[nn.Module] = nn.GELU,
|
|
65
|
+
use_abs_pos: bool = True,
|
|
66
|
+
use_rel_pos: bool = False,
|
|
67
|
+
rel_pos_zero_init: bool = True,
|
|
68
|
+
window_size: int = 0,
|
|
69
|
+
global_attn_indexes: Tuple[int, ...] = (),
|
|
70
|
+
downsample_channels: Tuple[int, ...] = (512, 1024),
|
|
71
|
+
) -> None:
|
|
72
|
+
"""
|
|
73
|
+
Args:
|
|
74
|
+
img_size (int): Input image size.
|
|
75
|
+
patch_size (int): Patch size.
|
|
76
|
+
in_chans (int): Number of input image channels.
|
|
77
|
+
embed_dim (int): Patch embedding dimension.
|
|
78
|
+
depth (int): Depth of ViT.
|
|
79
|
+
num_heads (int): Number of attention heads in each ViT block.
|
|
80
|
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
|
81
|
+
qkv_bias (bool): If True, add a learnable bias to query, key, value.
|
|
82
|
+
norm_layer (nn.Module): Normalization layer.
|
|
83
|
+
act_layer (nn.Module): Activation layer.
|
|
84
|
+
use_abs_pos (bool): If True, use absolute positional embeddings.
|
|
85
|
+
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
|
|
86
|
+
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
|
|
87
|
+
window_size (int): Window size for window attention blocks.
|
|
88
|
+
global_attn_indexes (list): Indexes for blocks using global attention.
|
|
89
|
+
downsample_channels (list): Channels for downsampling layers.
|
|
90
|
+
"""
|
|
91
|
+
super().__init__()
|
|
92
|
+
self.img_size = img_size
|
|
93
|
+
|
|
94
|
+
self.patch_embed = PatchEmbed(
|
|
95
|
+
kernel_size=(patch_size, patch_size),
|
|
96
|
+
stride=(patch_size, patch_size),
|
|
97
|
+
in_chans=in_chans,
|
|
98
|
+
embed_dim=embed_dim,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
self.pos_embed: Optional[nn.Parameter] = None
|
|
102
|
+
if use_abs_pos:
|
|
103
|
+
# Initialize absolute positional embedding with pretrain image size.
|
|
104
|
+
self.pos_embed = nn.Parameter(
|
|
105
|
+
torch.zeros(
|
|
106
|
+
1, img_size // patch_size, img_size // patch_size, embed_dim
|
|
107
|
+
)
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
self.blocks = nn.ModuleList()
|
|
111
|
+
for i in range(depth):
|
|
112
|
+
block = Block(
|
|
113
|
+
dim=embed_dim,
|
|
114
|
+
num_heads=num_heads,
|
|
115
|
+
mlp_ratio=mlp_ratio,
|
|
116
|
+
qkv_bias=qkv_bias,
|
|
117
|
+
norm_layer=norm_layer,
|
|
118
|
+
act_layer=act_layer,
|
|
119
|
+
use_rel_pos=use_rel_pos,
|
|
120
|
+
rel_pos_zero_init=rel_pos_zero_init,
|
|
121
|
+
window_size=window_size if i not in global_attn_indexes else 0,
|
|
122
|
+
input_size=(img_size // patch_size, img_size // patch_size),
|
|
123
|
+
)
|
|
124
|
+
self.blocks.append(block)
|
|
125
|
+
|
|
126
|
+
self.neck = nn.Sequential(
|
|
127
|
+
nn.Conv2d(
|
|
128
|
+
embed_dim,
|
|
129
|
+
out_chans,
|
|
130
|
+
kernel_size=1,
|
|
131
|
+
bias=False,
|
|
132
|
+
),
|
|
133
|
+
LayerNorm2d(out_chans),
|
|
134
|
+
nn.Conv2d(
|
|
135
|
+
out_chans,
|
|
136
|
+
out_chans,
|
|
137
|
+
kernel_size=3,
|
|
138
|
+
padding=1,
|
|
139
|
+
bias=False,
|
|
140
|
+
),
|
|
141
|
+
LayerNorm2d(out_chans),
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
in_channels = out_chans
|
|
145
|
+
downsamples = []
|
|
146
|
+
for i in range(len(downsample_channels)):
|
|
147
|
+
out_channels = downsample_channels[i]
|
|
148
|
+
downsamples.append(
|
|
149
|
+
nn.Conv2d(
|
|
150
|
+
in_channels,
|
|
151
|
+
out_channels,
|
|
152
|
+
kernel_size=3,
|
|
153
|
+
stride=2,
|
|
154
|
+
padding=1,
|
|
155
|
+
bias=False,
|
|
156
|
+
)
|
|
157
|
+
)
|
|
158
|
+
in_channels = out_channels
|
|
159
|
+
self.downsamples = nn.Sequential(*downsamples)
|
|
160
|
+
|
|
161
|
+
self.sam_hd = True
|
|
162
|
+
if self.sam_hd:
|
|
163
|
+
self.hd_alpha_downsamples = nn.Parameter(torch.zeros(1))
|
|
164
|
+
# self.neck_hd = nn.Linear(embed_dim, embed_dim)
|
|
165
|
+
self.neck_hd = copy.deepcopy(self.neck)
|
|
166
|
+
# self.downsamples_hd = copy.deepcopy(self.downsamples)
|
|
167
|
+
|
|
168
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
169
|
+
x = self.patch_embed(x)
|
|
170
|
+
if self.pos_embed is not None:
|
|
171
|
+
x = x + self.pos_embed
|
|
172
|
+
|
|
173
|
+
global_features = []
|
|
174
|
+
for i, blk in enumerate(self.blocks):
|
|
175
|
+
x = blk(x)
|
|
176
|
+
if self.sam_hd and blk.window_size == 0:
|
|
177
|
+
global_features.append(x)
|
|
178
|
+
|
|
179
|
+
x = self.neck(x.permute(0, 3, 1, 2))
|
|
180
|
+
x_dtype = x.dtype
|
|
181
|
+
x = F.interpolate(
|
|
182
|
+
x.float(), size=(96, 96), mode="bilinear", align_corners=False
|
|
183
|
+
).to(x_dtype)
|
|
184
|
+
x = self.downsamples(x)
|
|
185
|
+
|
|
186
|
+
if self.sam_hd:
|
|
187
|
+
first_global_feature = self.neck_hd(global_features[0].permute(0, 3, 1, 2))
|
|
188
|
+
x_dtype = first_global_feature.dtype
|
|
189
|
+
first_global_feature = F.interpolate(
|
|
190
|
+
first_global_feature.float(),
|
|
191
|
+
size=(96, 96),
|
|
192
|
+
mode="bilinear",
|
|
193
|
+
align_corners=False,
|
|
194
|
+
)
|
|
195
|
+
first_global_feature = self.downsamples(first_global_feature.to(x_dtype))
|
|
196
|
+
x = x + first_global_feature * self.hd_alpha_downsamples
|
|
197
|
+
|
|
198
|
+
return x
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class Block(nn.Module):
|
|
202
|
+
"""Transformer blocks with support of window attention and residual propagation blocks"""
|
|
203
|
+
|
|
204
|
+
def __init__(
|
|
205
|
+
self,
|
|
206
|
+
dim: int,
|
|
207
|
+
num_heads: int,
|
|
208
|
+
mlp_ratio: float = 4.0,
|
|
209
|
+
qkv_bias: bool = True,
|
|
210
|
+
norm_layer: Type[nn.Module] = nn.LayerNorm,
|
|
211
|
+
act_layer: Type[nn.Module] = nn.GELU,
|
|
212
|
+
use_rel_pos: bool = False,
|
|
213
|
+
rel_pos_zero_init: bool = True,
|
|
214
|
+
window_size: int = 0,
|
|
215
|
+
input_size: Optional[Tuple[int, int]] = None,
|
|
216
|
+
) -> None:
|
|
217
|
+
"""
|
|
218
|
+
Args:
|
|
219
|
+
dim (int): Number of input channels.
|
|
220
|
+
num_heads (int): Number of attention heads in each ViT block.
|
|
221
|
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
|
222
|
+
qkv_bias (bool): If True, add a learnable bias to query, key, value.
|
|
223
|
+
norm_layer (nn.Module): Normalization layer.
|
|
224
|
+
act_layer (nn.Module): Activation layer.
|
|
225
|
+
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
|
|
226
|
+
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
|
|
227
|
+
window_size (int): Window size for window attention blocks. If it equals 0, then
|
|
228
|
+
use global attention.
|
|
229
|
+
input_size (tuple(int, int) or None): Input resolution for calculating the relative
|
|
230
|
+
positional parameter size.
|
|
231
|
+
"""
|
|
232
|
+
super().__init__()
|
|
233
|
+
self.norm1 = norm_layer(dim)
|
|
234
|
+
self.attn = Attention(
|
|
235
|
+
dim,
|
|
236
|
+
num_heads=num_heads,
|
|
237
|
+
qkv_bias=qkv_bias,
|
|
238
|
+
use_rel_pos=use_rel_pos,
|
|
239
|
+
rel_pos_zero_init=rel_pos_zero_init,
|
|
240
|
+
input_size=input_size if window_size == 0 else (window_size, window_size),
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
self.norm2 = norm_layer(dim)
|
|
244
|
+
self.mlp = MLPBlock(
|
|
245
|
+
embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
self.window_size = window_size
|
|
249
|
+
|
|
250
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
251
|
+
shortcut = x
|
|
252
|
+
x = self.norm1(x)
|
|
253
|
+
# Window partition
|
|
254
|
+
if self.window_size > 0:
|
|
255
|
+
H, W = x.shape[1], x.shape[2]
|
|
256
|
+
x, pad_hw = window_partition(x, self.window_size)
|
|
257
|
+
|
|
258
|
+
x = self.attn(x)
|
|
259
|
+
# Reverse window partition
|
|
260
|
+
if self.window_size > 0:
|
|
261
|
+
x = window_unpartition(x, self.window_size, pad_hw, (H, W))
|
|
262
|
+
|
|
263
|
+
x = shortcut + x
|
|
264
|
+
x = x + self.mlp(self.norm2(x))
|
|
265
|
+
|
|
266
|
+
return x
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class Attention(nn.Module):
|
|
270
|
+
"""Multi-head Attention block with relative position embeddings."""
|
|
271
|
+
|
|
272
|
+
def __init__(
|
|
273
|
+
self,
|
|
274
|
+
dim: int,
|
|
275
|
+
num_heads: int = 8,
|
|
276
|
+
qkv_bias: bool = True,
|
|
277
|
+
use_rel_pos: bool = False,
|
|
278
|
+
rel_pos_zero_init: bool = True,
|
|
279
|
+
input_size: Optional[Tuple[int, int]] = None,
|
|
280
|
+
) -> None:
|
|
281
|
+
"""
|
|
282
|
+
Args:
|
|
283
|
+
dim (int): Number of input channels.
|
|
284
|
+
num_heads (int): Number of attention heads.
|
|
285
|
+
qkv_bias (bool): If True, add a learnable bias to query, key, value.
|
|
286
|
+
rel_pos (bool): If True, add relative positional embeddings to the attention map.
|
|
287
|
+
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
|
|
288
|
+
input_size (tuple(int, int) or None): Input resolution for calculating the relative
|
|
289
|
+
positional parameter size.
|
|
290
|
+
"""
|
|
291
|
+
super().__init__()
|
|
292
|
+
self.num_heads = num_heads
|
|
293
|
+
head_dim = dim // num_heads
|
|
294
|
+
self.scale = head_dim**-0.5
|
|
295
|
+
|
|
296
|
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
|
297
|
+
self.proj = nn.Linear(dim, dim)
|
|
298
|
+
|
|
299
|
+
self.use_rel_pos = use_rel_pos
|
|
300
|
+
if self.use_rel_pos:
|
|
301
|
+
assert (
|
|
302
|
+
input_size is not None
|
|
303
|
+
), "Input size must be provided if using relative positional encoding."
|
|
304
|
+
# initialize relative positional embeddings
|
|
305
|
+
self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
|
|
306
|
+
self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
|
|
307
|
+
|
|
308
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
309
|
+
B, H, W, _ = x.shape
|
|
310
|
+
# qkv with shape (3, B, nHead, H * W, C)
|
|
311
|
+
qkv = (
|
|
312
|
+
self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
|
|
313
|
+
)
|
|
314
|
+
# q, k, v with shape (B * nHead, H * W, C)
|
|
315
|
+
q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
|
|
316
|
+
|
|
317
|
+
def do_attention(q, k, v):
|
|
318
|
+
attn = (q * self.scale) @ k.transpose(-2, -1)
|
|
319
|
+
if self.use_rel_pos:
|
|
320
|
+
attn = add_decomposed_rel_pos(
|
|
321
|
+
attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
attn = attn.softmax(dim=-1)
|
|
325
|
+
x = (
|
|
326
|
+
(attn @ v)
|
|
327
|
+
.view(B, self.num_heads, H, W, -1)
|
|
328
|
+
.permute(0, 2, 3, 1, 4)
|
|
329
|
+
.reshape(B, H, W, -1)
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
return x
|
|
333
|
+
|
|
334
|
+
# from haiscale.utils import on_demand_checkpoint
|
|
335
|
+
# x = on_demand_checkpoint(do_attention, q, k, v)
|
|
336
|
+
x = do_attention(q, k, v)
|
|
337
|
+
x = self.proj(x)
|
|
338
|
+
|
|
339
|
+
return x
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def window_partition(
|
|
343
|
+
x: torch.Tensor, window_size: int
|
|
344
|
+
) -> Tuple[torch.Tensor, Tuple[int, int]]:
|
|
345
|
+
"""
|
|
346
|
+
Partition into non-overlapping windows with padding if needed.
|
|
347
|
+
Args:
|
|
348
|
+
x (tensor): input tokens with [B, H, W, C].
|
|
349
|
+
window_size (int): window size.
|
|
350
|
+
|
|
351
|
+
Returns:
|
|
352
|
+
windows: windows after partition with [B * num_windows, window_size, window_size, C].
|
|
353
|
+
(Hp, Wp): padded height and width before partition
|
|
354
|
+
"""
|
|
355
|
+
B, H, W, C = x.shape
|
|
356
|
+
|
|
357
|
+
pad_h = (window_size - H % window_size) % window_size
|
|
358
|
+
pad_w = (window_size - W % window_size) % window_size
|
|
359
|
+
if pad_h > 0 or pad_w > 0:
|
|
360
|
+
x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
|
|
361
|
+
Hp, Wp = H + pad_h, W + pad_w
|
|
362
|
+
|
|
363
|
+
x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
|
|
364
|
+
windows = (
|
|
365
|
+
x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
|
|
366
|
+
)
|
|
367
|
+
return windows, (Hp, Wp)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def window_unpartition(
|
|
371
|
+
windows: torch.Tensor,
|
|
372
|
+
window_size: int,
|
|
373
|
+
pad_hw: Tuple[int, int],
|
|
374
|
+
hw: Tuple[int, int],
|
|
375
|
+
) -> torch.Tensor:
|
|
376
|
+
"""
|
|
377
|
+
Window unpartition into original sequences and removing padding.
|
|
378
|
+
Args:
|
|
379
|
+
windows (tensor): input tokens with [B * num_windows, window_size, window_size, C].
|
|
380
|
+
window_size (int): window size.
|
|
381
|
+
pad_hw (Tuple): padded height and width (Hp, Wp).
|
|
382
|
+
hw (Tuple): original height and width (H, W) before padding.
|
|
383
|
+
|
|
384
|
+
Returns:
|
|
385
|
+
x: unpartitioned sequences with [B, H, W, C].
|
|
386
|
+
"""
|
|
387
|
+
Hp, Wp = pad_hw
|
|
388
|
+
H, W = hw
|
|
389
|
+
B = windows.shape[0] // (Hp * Wp // window_size // window_size)
|
|
390
|
+
x = windows.view(
|
|
391
|
+
B, Hp // window_size, Wp // window_size, window_size, window_size, -1
|
|
392
|
+
)
|
|
393
|
+
x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
|
|
394
|
+
|
|
395
|
+
if Hp > H or Wp > W:
|
|
396
|
+
x = x[:, :H, :W, :].contiguous()
|
|
397
|
+
return x
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
|
|
401
|
+
"""
|
|
402
|
+
Get relative positional embeddings according to the relative positions of
|
|
403
|
+
query and key sizes.
|
|
404
|
+
Args:
|
|
405
|
+
q_size (int): size of query q.
|
|
406
|
+
k_size (int): size of key k.
|
|
407
|
+
rel_pos (Tensor): relative position embeddings (L, C).
|
|
408
|
+
|
|
409
|
+
Returns:
|
|
410
|
+
Extracted positional embeddings according to relative positions.
|
|
411
|
+
"""
|
|
412
|
+
max_rel_dist = int(2 * max(q_size, k_size) - 1)
|
|
413
|
+
# Interpolate rel pos if needed.
|
|
414
|
+
if rel_pos.shape[0] != max_rel_dist:
|
|
415
|
+
# Interpolate rel pos.
|
|
416
|
+
rel_pos_resized = F.interpolate(
|
|
417
|
+
rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
|
|
418
|
+
size=max_rel_dist,
|
|
419
|
+
mode="linear",
|
|
420
|
+
)
|
|
421
|
+
rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
|
|
422
|
+
else:
|
|
423
|
+
rel_pos_resized = rel_pos
|
|
424
|
+
|
|
425
|
+
# Scale the coords with short length if shapes for q and k are different.
|
|
426
|
+
q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
|
|
427
|
+
k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
|
|
428
|
+
relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
|
|
429
|
+
|
|
430
|
+
return rel_pos_resized[relative_coords.long()]
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def add_decomposed_rel_pos(
|
|
434
|
+
attn: torch.Tensor,
|
|
435
|
+
q: torch.Tensor,
|
|
436
|
+
rel_pos_h: torch.Tensor,
|
|
437
|
+
rel_pos_w: torch.Tensor,
|
|
438
|
+
q_size: Tuple[int, int],
|
|
439
|
+
k_size: Tuple[int, int],
|
|
440
|
+
) -> torch.Tensor:
|
|
441
|
+
"""
|
|
442
|
+
Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
|
|
443
|
+
https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950
|
|
444
|
+
Args:
|
|
445
|
+
attn (Tensor): attention map.
|
|
446
|
+
q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C).
|
|
447
|
+
rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis.
|
|
448
|
+
rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis.
|
|
449
|
+
q_size (Tuple): spatial sequence size of query q with (q_h, q_w).
|
|
450
|
+
k_size (Tuple): spatial sequence size of key k with (k_h, k_w).
|
|
451
|
+
|
|
452
|
+
Returns:
|
|
453
|
+
attn (Tensor): attention map with added relative positional embeddings.
|
|
454
|
+
"""
|
|
455
|
+
q_h, q_w = q_size
|
|
456
|
+
k_h, k_w = k_size
|
|
457
|
+
Rh = get_rel_pos(q_h, k_h, rel_pos_h)
|
|
458
|
+
Rw = get_rel_pos(q_w, k_w, rel_pos_w)
|
|
459
|
+
|
|
460
|
+
B, _, dim = q.shape
|
|
461
|
+
r_q = q.reshape(B, q_h, q_w, dim)
|
|
462
|
+
rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)
|
|
463
|
+
rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)
|
|
464
|
+
|
|
465
|
+
attn = (
|
|
466
|
+
attn.view(B, q_h, q_w, k_h, k_w)
|
|
467
|
+
+ rel_h[:, :, :, :, None]
|
|
468
|
+
+ rel_w[:, :, :, None, :]
|
|
469
|
+
).view(B, q_h * q_w, k_h * k_w)
|
|
470
|
+
|
|
471
|
+
return attn
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
class PatchEmbed(nn.Module):
|
|
475
|
+
"""
|
|
476
|
+
Image to Patch Embedding.
|
|
477
|
+
"""
|
|
478
|
+
|
|
479
|
+
def __init__(
|
|
480
|
+
self,
|
|
481
|
+
kernel_size: Tuple[int, int] = (16, 16),
|
|
482
|
+
stride: Tuple[int, int] = (16, 16),
|
|
483
|
+
padding: Tuple[int, int] = (0, 0),
|
|
484
|
+
in_chans: int = 3,
|
|
485
|
+
embed_dim: int = 768,
|
|
486
|
+
) -> None:
|
|
487
|
+
"""
|
|
488
|
+
Args:
|
|
489
|
+
kernel_size (Tuple): kernel size of the projection layer.
|
|
490
|
+
stride (Tuple): stride of the projection layer.
|
|
491
|
+
padding (Tuple): padding size of the projection layer.
|
|
492
|
+
in_chans (int): Number of input image channels.
|
|
493
|
+
embed_dim (int): Patch embedding dimension.
|
|
494
|
+
"""
|
|
495
|
+
super().__init__()
|
|
496
|
+
|
|
497
|
+
self.proj = nn.Conv2d(
|
|
498
|
+
in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
|
|
499
|
+
)
|
|
500
|
+
|
|
501
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
502
|
+
x = self.proj(x)
|
|
503
|
+
# B C H W -> B H W C
|
|
504
|
+
x = x.permute(0, 2, 3, 1)
|
|
505
|
+
return x
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
@dataclass
|
|
509
|
+
class SAMViTCfg:
|
|
510
|
+
image_size: Union[Tuple[int, int], int] = 1024
|
|
511
|
+
width: int = 1024
|
|
512
|
+
layers: int = 23
|
|
513
|
+
heads: int = 16
|
|
514
|
+
patch_size: int = 16
|
|
515
|
+
window_size: int = 14
|
|
516
|
+
prompt_embed_dim: int = 256
|
|
517
|
+
global_attn_indexes: Union[List[int], Tuple[int]] = (5, 11, 17, 23)
|
|
518
|
+
downsample_channels: Union[List[int], Tuple[int]] = (512, 1024)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
SAM_MODEL_CONFIG = {
|
|
522
|
+
"sam_vit_b": {
|
|
523
|
+
"width": 768,
|
|
524
|
+
"layers": 12,
|
|
525
|
+
"heads": 12,
|
|
526
|
+
"global_attn_indexes": [2, 5, 8, 11],
|
|
527
|
+
"downsample_channels": (),
|
|
528
|
+
},
|
|
529
|
+
"sam_b_downsample": {
|
|
530
|
+
"width": 768,
|
|
531
|
+
"layers": 12,
|
|
532
|
+
"heads": 12,
|
|
533
|
+
"global_attn_indexes": [2, 5, 8, 11],
|
|
534
|
+
"downsample_channels": (512, 1024),
|
|
535
|
+
},
|
|
536
|
+
"sam_vit_l": {
|
|
537
|
+
"width": 1024,
|
|
538
|
+
"layers": 24,
|
|
539
|
+
"heads": 16,
|
|
540
|
+
"global_attn_indexes": [5, 11, 17, 23],
|
|
541
|
+
"downsample_channels": (),
|
|
542
|
+
},
|
|
543
|
+
"sam_vit_h": {
|
|
544
|
+
"width": 1280,
|
|
545
|
+
"layers": 32,
|
|
546
|
+
"heads": 16,
|
|
547
|
+
"global_attn_indexes": [7, 15, 23, 31],
|
|
548
|
+
"downsample_channels": (),
|
|
549
|
+
},
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def create_sam_vit(
|
|
554
|
+
model_name: str = "sam_b_downsample",
|
|
555
|
+
image_size: int = 1024,
|
|
556
|
+
ckpt_path: str = "",
|
|
557
|
+
**kwargs,
|
|
558
|
+
):
|
|
559
|
+
assert (
|
|
560
|
+
model_name in SAM_MODEL_CONFIG.keys()
|
|
561
|
+
), f"model name: {model_name} should be in {SAM_MODEL_CONFIG.keys()}"
|
|
562
|
+
|
|
563
|
+
sam_cfg = SAMViTCfg(**SAM_MODEL_CONFIG[model_name])
|
|
564
|
+
image_encoder = ImageEncoderViT(
|
|
565
|
+
depth=sam_cfg.layers,
|
|
566
|
+
embed_dim=sam_cfg.width,
|
|
567
|
+
img_size=image_size,
|
|
568
|
+
mlp_ratio=4,
|
|
569
|
+
norm_layer=partial(torch.nn.LayerNorm, eps=1e-6),
|
|
570
|
+
num_heads=sam_cfg.heads,
|
|
571
|
+
patch_size=sam_cfg.patch_size,
|
|
572
|
+
qkv_bias=True,
|
|
573
|
+
use_rel_pos=True,
|
|
574
|
+
global_attn_indexes=sam_cfg.global_attn_indexes,
|
|
575
|
+
window_size=14,
|
|
576
|
+
out_chans=sam_cfg.prompt_embed_dim,
|
|
577
|
+
downsample_channels=sam_cfg.downsample_channels,
|
|
578
|
+
)
|
|
579
|
+
|
|
580
|
+
if ckpt_path:
|
|
581
|
+
state_dict = torch.load(ckpt_path)
|
|
582
|
+
image_encoder.load_state_dict(state_dict, strict=False)
|
|
583
|
+
print(f"SAM-ViT restores from {ckpt_path}")
|
|
584
|
+
|
|
585
|
+
return image_encoder
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
if __name__ == "__main__":
|
|
589
|
+
x = torch.zeros(2, 3, 1024, 1024).bfloat16()
|
|
590
|
+
# x.permute(0, 3, 1, 2)
|
|
591
|
+
net = create_sam_vit().bfloat16()
|
|
592
|
+
out = net(x)
|
|
593
|
+
print(x.shape, out.shape)
|