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.

Files changed (59) 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 +9 -1
  5. xinference/client/restful/restful_client.py +12 -2
  6. xinference/conftest.py +13 -2
  7. xinference/core/supervisor.py +32 -1
  8. xinference/core/worker.py +139 -20
  9. xinference/deploy/cmdline.py +119 -20
  10. xinference/model/llm/__init__.py +4 -0
  11. xinference/model/llm/llm_family.json +627 -0
  12. xinference/model/llm/llm_family_modelscope.json +471 -0
  13. xinference/model/llm/pytorch/core.py +2 -0
  14. xinference/model/llm/pytorch/deepseek_vl.py +232 -0
  15. xinference/model/llm/pytorch/omnilmm.py +153 -0
  16. xinference/model/llm/utils.py +11 -1
  17. xinference/model/llm/vllm/core.py +3 -0
  18. xinference/thirdparty/deepseek_vl/__init__.py +31 -0
  19. xinference/thirdparty/deepseek_vl/models/__init__.py +28 -0
  20. xinference/thirdparty/deepseek_vl/models/clip_encoder.py +242 -0
  21. xinference/thirdparty/deepseek_vl/models/image_processing_vlm.py +208 -0
  22. xinference/thirdparty/deepseek_vl/models/modeling_vlm.py +170 -0
  23. xinference/thirdparty/deepseek_vl/models/processing_vlm.py +390 -0
  24. xinference/thirdparty/deepseek_vl/models/projector.py +100 -0
  25. xinference/thirdparty/deepseek_vl/models/sam.py +593 -0
  26. xinference/thirdparty/deepseek_vl/models/siglip_vit.py +681 -0
  27. xinference/thirdparty/deepseek_vl/utils/__init__.py +18 -0
  28. xinference/thirdparty/deepseek_vl/utils/conversation.py +348 -0
  29. xinference/thirdparty/deepseek_vl/utils/io.py +78 -0
  30. xinference/thirdparty/omnilmm/__init__.py +0 -0
  31. xinference/thirdparty/omnilmm/chat.py +216 -0
  32. xinference/thirdparty/omnilmm/constants.py +4 -0
  33. xinference/thirdparty/omnilmm/conversation.py +332 -0
  34. xinference/thirdparty/omnilmm/model/__init__.py +1 -0
  35. xinference/thirdparty/omnilmm/model/omnilmm.py +594 -0
  36. xinference/thirdparty/omnilmm/model/resampler.py +166 -0
  37. xinference/thirdparty/omnilmm/model/utils.py +563 -0
  38. xinference/thirdparty/omnilmm/train/__init__.py +13 -0
  39. xinference/thirdparty/omnilmm/train/train_utils.py +150 -0
  40. xinference/thirdparty/omnilmm/utils.py +134 -0
  41. xinference/web/ui/build/asset-manifest.json +3 -3
  42. xinference/web/ui/build/index.html +1 -1
  43. xinference/web/ui/build/static/js/main.98516614.js +3 -0
  44. xinference/web/ui/build/static/js/main.98516614.js.map +1 -0
  45. xinference/web/ui/node_modules/.cache/babel-loader/139969fd25258eb7decc9505f30b779089bba50c402bb5c663008477c7bff73b.json +1 -0
  46. xinference/web/ui/node_modules/.cache/babel-loader/3f357ab57b8e7fade54c667f0e0ebf2787566f72bfdca0fea14e395b5c203753.json +1 -0
  47. xinference/web/ui/node_modules/.cache/babel-loader/9d7c49815d97539207e5aab2fb967591b5fed7791218a0762539efc9491f36af.json +1 -0
  48. xinference/web/ui/node_modules/.cache/babel-loader/d0d0b591d9adaf42b83ad6633f8b7c118541a4b80ea957c303d3bf9b86fbad0a.json +1 -0
  49. {xinference-0.9.4.dist-info → xinference-0.10.0.dist-info}/METADATA +18 -5
  50. {xinference-0.9.4.dist-info → xinference-0.10.0.dist-info}/RECORD +55 -28
  51. xinference/web/ui/build/static/js/main.66b1c4fb.js +0 -3
  52. xinference/web/ui/build/static/js/main.66b1c4fb.js.map +0 -1
  53. xinference/web/ui/node_modules/.cache/babel-loader/c2124cfe036b26befcbd386d1d17743b1a58d0b7a041a17bb67f9924400d63c3.json +0 -1
  54. xinference/web/ui/node_modules/.cache/babel-loader/fd4a8ae5d192331af1bedd1d2d70efcc569708ee6cc4cb479b225d059482aa81.json +0 -1
  55. /xinference/web/ui/build/static/js/{main.66b1c4fb.js.LICENSE.txt → main.98516614.js.LICENSE.txt} +0 -0
  56. {xinference-0.9.4.dist-info → xinference-0.10.0.dist-info}/LICENSE +0 -0
  57. {xinference-0.9.4.dist-info → xinference-0.10.0.dist-info}/WHEEL +0 -0
  58. {xinference-0.9.4.dist-info → xinference-0.10.0.dist-info}/entry_points.txt +0 -0
  59. {xinference-0.9.4.dist-info → xinference-0.10.0.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)