liuqingquan commited on
Commit
5be526b
·
verified ·
1 Parent(s): 81d9bf4

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. models/RMBG/BEN/BEN_Base.pth +3 -0
  3. models/RMBG/BEN/gitattributes +35 -0
  4. models/RMBG/BEN/model.py +951 -0
  5. models/RMBG/BEN2/BEN2.py +1401 -0
  6. models/RMBG/BEN2/BEN2_Base.pth +3 -0
  7. models/RMBG/BEN2/gitattributes +35 -0
  8. models/RMBG/BiRefNet-HR/BiRefNet_config.py +11 -0
  9. models/RMBG/BiRefNet-HR/birefnet.py +2248 -0
  10. models/RMBG/BiRefNet-HR/config.json +20 -0
  11. models/RMBG/BiRefNet-HR/gitattributes +35 -0
  12. models/RMBG/BiRefNet-HR/model.safetensors +3 -0
  13. models/RMBG/BiRefNet/BiRefNet-HR-matting.safetensors +3 -0
  14. models/RMBG/BiRefNet/BiRefNet-HR.safetensors +3 -0
  15. models/RMBG/BiRefNet/BiRefNet-general.safetensors +3 -0
  16. models/RMBG/BiRefNet/BiRefNet-matting.safetensors +3 -0
  17. models/RMBG/BiRefNet/BiRefNet-portrait.safetensors +3 -0
  18. models/RMBG/BiRefNet/BiRefNet_512x512.safetensors +3 -0
  19. models/RMBG/BiRefNet/BiRefNet_config.py +11 -0
  20. models/RMBG/BiRefNet/BiRefNet_lite-2K.safetensors +3 -0
  21. models/RMBG/BiRefNet/BiRefNet_lite.safetensors +3 -0
  22. models/RMBG/BiRefNet/birefnet.py +2248 -0
  23. models/RMBG/BiRefNet/birefnet_lite.py +2248 -0
  24. models/RMBG/BiRefNet/config.json +20 -0
  25. models/RMBG/BiRefNet/gitattributes +35 -0
  26. models/RMBG/INSPYRENET/gitattributes +35 -0
  27. models/RMBG/INSPYRENET/inspyrenet.pth +3 -0
  28. models/RMBG/INSPYRENET/inspyrenet.safetensors +3 -0
  29. models/RMBG/RMBG-2.0/BiRefNet_config.py +11 -0
  30. models/RMBG/RMBG-2.0/__pycache__/BiRefNet_config.cpython-310.pyc +0 -0
  31. models/RMBG/RMBG-2.0/birefnet.py +2244 -0
  32. models/RMBG/RMBG-2.0/config.json +20 -0
  33. models/RMBG/RMBG-2.0/gitattributes +35 -0
  34. models/RMBG/RMBG-2.0/model.safetensors +3 -0
  35. models/RMBG/SAM/Moonlit Serenade.mp3 +3 -0
  36. models/RMBG/SAM/README.md +0 -0
  37. models/RMBG/SAM/gitattributes +35 -0
  38. models/RMBG/SAM/mobile_sam.pt +3 -0
  39. models/RMBG/SAM/mobile_sam.safetensors +3 -0
  40. models/RMBG/SAM/sam_hq_vit_b.pth +3 -0
  41. models/RMBG/SAM/sam_hq_vit_h.pth +3 -0
  42. models/RMBG/SAM/sam_hq_vit_l.pth +3 -0
  43. models/RMBG/SAM/sam_vit_b.pth +3 -0
  44. models/RMBG/SAM/sam_vit_h.pth +3 -0
  45. models/RMBG/SAM/sam_vit_l.pth +3 -0
  46. models/RMBG/grounding-dino/GroundingDINO_SwinB.cfg.py +43 -0
  47. models/RMBG/grounding-dino/GroundingDINO_SwinT_OGC.cfg.py +43 -0
  48. models/RMBG/grounding-dino/gitattributes +35 -0
  49. models/RMBG/grounding-dino/groundingdino_swinb_cogcoor.pth +3 -0
  50. models/RMBG/grounding-dino/groundingdino_swint_ogc.pth +3 -0
.gitattributes CHANGED
@@ -341,3 +341,4 @@ models/sapiens/depth/sapiens_1b_render_people_epoch_88_torchscript.pt2 filter=lf
341
  models/sapiens/normal/sapiens_1b_normal_render_people_epoch_115_torchscript.pt2 filter=lfs diff=lfs merge=lfs -text
342
  models/sapiens/pose/sapiens_1b_goliath_best_goliath_AP_639_torchscript.pt2 filter=lfs diff=lfs merge=lfs -text
343
  models/sapiens/seg/sapiens_1b_goliath_best_goliath_mIoU_7994_epoch_151_torchscript.pt2 filter=lfs diff=lfs merge=lfs -text
 
 
341
  models/sapiens/normal/sapiens_1b_normal_render_people_epoch_115_torchscript.pt2 filter=lfs diff=lfs merge=lfs -text
342
  models/sapiens/pose/sapiens_1b_goliath_best_goliath_AP_639_torchscript.pt2 filter=lfs diff=lfs merge=lfs -text
343
  models/sapiens/seg/sapiens_1b_goliath_best_goliath_mIoU_7994_epoch_151_torchscript.pt2 filter=lfs diff=lfs merge=lfs -text
344
+ models/RMBG/SAM/Moonlit[[:space:]]Serenade.mp3 filter=lfs diff=lfs merge=lfs -text
models/RMBG/BEN/BEN_Base.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f00a5804c96afed6e19be09dbbbe56ccaf82cff3d751f44aadb9626b77facfa
3
+ size 1134588350
models/RMBG/BEN/gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
models/RMBG/BEN/model.py ADDED
@@ -0,0 +1,951 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import torch.utils.checkpoint as checkpoint
7
+ from einops import rearrange
8
+ from PIL import Image, ImageFilter, ImageOps
9
+ from timm.layers import DropPath, to_2tuple, trunc_normal_
10
+ from torchvision import transforms
11
+
12
+ class Mlp(nn.Module):
13
+ """ Multilayer perceptron."""
14
+
15
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
16
+ super().__init__()
17
+ out_features = out_features or in_features
18
+ hidden_features = hidden_features or in_features
19
+ self.fc1 = nn.Linear(in_features, hidden_features)
20
+ self.act = act_layer()
21
+ self.fc2 = nn.Linear(hidden_features, out_features)
22
+ self.drop = nn.Dropout(drop)
23
+
24
+ def forward(self, x):
25
+ x = self.fc1(x)
26
+ x = self.act(x)
27
+ x = self.drop(x)
28
+ x = self.fc2(x)
29
+ x = self.drop(x)
30
+ return x
31
+
32
+
33
+ def window_partition(x, window_size):
34
+ """
35
+ Args:
36
+ x: (B, H, W, C)
37
+ window_size (int): window size
38
+ Returns:
39
+ windows: (num_windows*B, window_size, window_size, C)
40
+ """
41
+ B, H, W, C = x.shape
42
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
43
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
44
+ return windows
45
+
46
+
47
+ def window_reverse(windows, window_size, H, W):
48
+ """
49
+ Args:
50
+ windows: (num_windows*B, window_size, window_size, C)
51
+ window_size (int): Window size
52
+ H (int): Height of image
53
+ W (int): Width of image
54
+ Returns:
55
+ x: (B, H, W, C)
56
+ """
57
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
58
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
59
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
60
+ return x
61
+
62
+
63
+ class WindowAttention(nn.Module):
64
+ """ Window based multi-head self attention (W-MSA) module with relative position bias.
65
+ It supports both of shifted and non-shifted window.
66
+ Args:
67
+ dim (int): Number of input channels.
68
+ window_size (tuple[int]): The height and width of the window.
69
+ num_heads (int): Number of attention heads.
70
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
71
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
72
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
73
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
74
+ """
75
+
76
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
77
+
78
+ super().__init__()
79
+ self.dim = dim
80
+ self.window_size = window_size # Wh, Ww
81
+ self.num_heads = num_heads
82
+ head_dim = dim // num_heads
83
+ self.scale = qk_scale or head_dim ** -0.5
84
+
85
+ # define a parameter table of relative position bias
86
+ self.relative_position_bias_table = nn.Parameter(
87
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
88
+
89
+ # get pair-wise relative position index for each token inside the window
90
+ coords_h = torch.arange(self.window_size[0])
91
+ coords_w = torch.arange(self.window_size[1])
92
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
93
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
94
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
95
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
96
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
97
+ relative_coords[:, :, 1] += self.window_size[1] - 1
98
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
99
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
100
+ self.register_buffer("relative_position_index", relative_position_index)
101
+
102
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
103
+ self.attn_drop = nn.Dropout(attn_drop)
104
+ self.proj = nn.Linear(dim, dim)
105
+ self.proj_drop = nn.Dropout(proj_drop)
106
+
107
+ trunc_normal_(self.relative_position_bias_table, std=.02)
108
+ self.softmax = nn.Softmax(dim=-1)
109
+
110
+ def forward(self, x, mask=None):
111
+ """ Forward function.
112
+ Args:
113
+ x: input features with shape of (num_windows*B, N, C)
114
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
115
+ """
116
+ B_, N, C = x.shape
117
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
118
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
119
+
120
+ q = q * self.scale
121
+ attn = (q @ k.transpose(-2, -1))
122
+
123
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
124
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
125
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
126
+ attn = attn + relative_position_bias.unsqueeze(0)
127
+
128
+ if mask is not None:
129
+ nW = mask.shape[0]
130
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
131
+ attn = attn.view(-1, self.num_heads, N, N)
132
+ attn = self.softmax(attn)
133
+ else:
134
+ attn = self.softmax(attn)
135
+
136
+ attn = self.attn_drop(attn)
137
+
138
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
139
+ x = self.proj(x)
140
+ x = self.proj_drop(x)
141
+ return x
142
+
143
+
144
+ class SwinTransformerBlock(nn.Module):
145
+ """ Swin Transformer Block.
146
+ Args:
147
+ dim (int): Number of input channels.
148
+ num_heads (int): Number of attention heads.
149
+ window_size (int): Window size.
150
+ shift_size (int): Shift size for SW-MSA.
151
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
152
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
153
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
154
+ drop (float, optional): Dropout rate. Default: 0.0
155
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
156
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
157
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
158
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
159
+ """
160
+
161
+ def __init__(self, dim, num_heads, window_size=7, shift_size=0,
162
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
163
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
164
+ super().__init__()
165
+ self.dim = dim
166
+ self.num_heads = num_heads
167
+ self.window_size = window_size
168
+ self.shift_size = shift_size
169
+ self.mlp_ratio = mlp_ratio
170
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
171
+
172
+ self.norm1 = norm_layer(dim)
173
+ self.attn = WindowAttention(
174
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
175
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
176
+
177
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
178
+ self.norm2 = norm_layer(dim)
179
+ mlp_hidden_dim = int(dim * mlp_ratio)
180
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
181
+
182
+ self.H = None
183
+ self.W = None
184
+
185
+ def forward(self, x, mask_matrix):
186
+ """ Forward function.
187
+ Args:
188
+ x: Input feature, tensor size (B, H*W, C).
189
+ H, W: Spatial resolution of the input feature.
190
+ mask_matrix: Attention mask for cyclic shift.
191
+ """
192
+ B, L, C = x.shape
193
+ H, W = self.H, self.W
194
+ assert L == H * W, "input feature has wrong size"
195
+
196
+ shortcut = x
197
+ x = self.norm1(x)
198
+ x = x.view(B, H, W, C)
199
+
200
+ # pad feature maps to multiples of window size
201
+ pad_l = pad_t = 0
202
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
203
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
204
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
205
+ _, Hp, Wp, _ = x.shape
206
+
207
+ # cyclic shift
208
+ if self.shift_size > 0:
209
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
210
+ attn_mask = mask_matrix
211
+ else:
212
+ shifted_x = x
213
+ attn_mask = None
214
+
215
+ # partition windows
216
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
217
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
218
+
219
+ # W-MSA/SW-MSA
220
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
221
+
222
+ # merge windows
223
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
224
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
225
+
226
+ # reverse cyclic shift
227
+ if self.shift_size > 0:
228
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
229
+ else:
230
+ x = shifted_x
231
+
232
+ if pad_r > 0 or pad_b > 0:
233
+ x = x[:, :H, :W, :].contiguous()
234
+
235
+ x = x.view(B, H * W, C)
236
+
237
+ # FFN
238
+ x = shortcut + self.drop_path(x)
239
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
240
+
241
+ return x
242
+
243
+
244
+ class PatchMerging(nn.Module):
245
+ """ Patch Merging Layer
246
+ Args:
247
+ dim (int): Number of input channels.
248
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
249
+ """
250
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
251
+ super().__init__()
252
+ self.dim = dim
253
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
254
+ self.norm = norm_layer(4 * dim)
255
+
256
+ def forward(self, x, H, W):
257
+ """ Forward function.
258
+ Args:
259
+ x: Input feature, tensor size (B, H*W, C).
260
+ H, W: Spatial resolution of the input feature.
261
+ """
262
+ B, L, C = x.shape
263
+ assert L == H * W, "input feature has wrong size"
264
+
265
+ x = x.view(B, H, W, C)
266
+
267
+ # padding
268
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
269
+ if pad_input:
270
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
271
+
272
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
273
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
274
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
275
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
276
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
277
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
278
+
279
+ x = self.norm(x)
280
+ x = self.reduction(x)
281
+
282
+ return x
283
+
284
+
285
+ class BasicLayer(nn.Module):
286
+ """ A basic Swin Transformer layer for one stage.
287
+ Args:
288
+ dim (int): Number of feature channels
289
+ depth (int): Depths of this stage.
290
+ num_heads (int): Number of attention head.
291
+ window_size (int): Local window size. Default: 7.
292
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
293
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
294
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
295
+ drop (float, optional): Dropout rate. Default: 0.0
296
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
297
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
298
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
299
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
300
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
301
+ """
302
+
303
+ def __init__(self,
304
+ dim,
305
+ depth,
306
+ num_heads,
307
+ window_size=7,
308
+ mlp_ratio=4.,
309
+ qkv_bias=True,
310
+ qk_scale=None,
311
+ drop=0.,
312
+ attn_drop=0.,
313
+ drop_path=0.,
314
+ norm_layer=nn.LayerNorm,
315
+ downsample=None,
316
+ use_checkpoint=False):
317
+ super().__init__()
318
+ self.window_size = window_size
319
+ self.shift_size = window_size // 2
320
+ self.depth = depth
321
+ self.use_checkpoint = use_checkpoint
322
+
323
+ # build blocks
324
+ self.blocks = nn.ModuleList([
325
+ SwinTransformerBlock(
326
+ dim=dim,
327
+ num_heads=num_heads,
328
+ window_size=window_size,
329
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
330
+ mlp_ratio=mlp_ratio,
331
+ qkv_bias=qkv_bias,
332
+ qk_scale=qk_scale,
333
+ drop=drop,
334
+ attn_drop=attn_drop,
335
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
336
+ norm_layer=norm_layer)
337
+ for i in range(depth)])
338
+
339
+ # patch merging layer
340
+ if downsample is not None:
341
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
342
+ else:
343
+ self.downsample = None
344
+
345
+ def forward(self, x, H, W):
346
+ """ Forward function.
347
+ Args:
348
+ x: Input feature, tensor size (B, H*W, C).
349
+ H, W: Spatial resolution of the input feature.
350
+ """
351
+
352
+ # calculate attention mask for SW-MSA
353
+ Hp = int(np.ceil(H / self.window_size)) * self.window_size
354
+ Wp = int(np.ceil(W / self.window_size)) * self.window_size
355
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
356
+ h_slices = (slice(0, -self.window_size),
357
+ slice(-self.window_size, -self.shift_size),
358
+ slice(-self.shift_size, None))
359
+ w_slices = (slice(0, -self.window_size),
360
+ slice(-self.window_size, -self.shift_size),
361
+ slice(-self.shift_size, None))
362
+ cnt = 0
363
+ for h in h_slices:
364
+ for w in w_slices:
365
+ img_mask[:, h, w, :] = cnt
366
+ cnt += 1
367
+
368
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
369
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
370
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
371
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
372
+
373
+ for blk in self.blocks:
374
+ blk.H, blk.W = H, W
375
+ if self.use_checkpoint:
376
+ x = checkpoint.checkpoint(blk, x, attn_mask)
377
+ else:
378
+ x = blk(x, attn_mask)
379
+ if self.downsample is not None:
380
+ x_down = self.downsample(x, H, W)
381
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
382
+ return x, H, W, x_down, Wh, Ww
383
+ else:
384
+ return x, H, W, x, H, W
385
+
386
+
387
+ class PatchEmbed(nn.Module):
388
+ """ Image to Patch Embedding
389
+ Args:
390
+ patch_size (int): Patch token size. Default: 4.
391
+ in_chans (int): Number of input image channels. Default: 3.
392
+ embed_dim (int): Number of linear projection output channels. Default: 96.
393
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
394
+ """
395
+
396
+ def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
397
+ super().__init__()
398
+ patch_size = to_2tuple(patch_size)
399
+ self.patch_size = patch_size
400
+
401
+ self.in_chans = in_chans
402
+ self.embed_dim = embed_dim
403
+
404
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
405
+ if norm_layer is not None:
406
+ self.norm = norm_layer(embed_dim)
407
+ else:
408
+ self.norm = None
409
+
410
+ def forward(self, x):
411
+ """Forward function."""
412
+ # padding
413
+ _, _, H, W = x.size()
414
+ if W % self.patch_size[1] != 0:
415
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
416
+ if H % self.patch_size[0] != 0:
417
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
418
+
419
+ x = self.proj(x) # B C Wh Ww
420
+ if self.norm is not None:
421
+ Wh, Ww = x.size(2), x.size(3)
422
+ x = x.flatten(2).transpose(1, 2)
423
+ x = self.norm(x)
424
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
425
+
426
+ return x
427
+
428
+
429
+ class SwinTransformer(nn.Module):
430
+ """ Swin Transformer backbone.
431
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
432
+ https://arxiv.org/pdf/2103.14030
433
+ Args:
434
+ pretrain_img_size (int): Input image size for training the pretrained model,
435
+ used in absolute postion embedding. Default 224.
436
+ patch_size (int | tuple(int)): Patch size. Default: 4.
437
+ in_chans (int): Number of input image channels. Default: 3.
438
+ embed_dim (int): Number of linear projection output channels. Default: 96.
439
+ depths (tuple[int]): Depths of each Swin Transformer stage.
440
+ num_heads (tuple[int]): Number of attention head of each stage.
441
+ window_size (int): Window size. Default: 7.
442
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
443
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
444
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
445
+ drop_rate (float): Dropout rate.
446
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
447
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
448
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
449
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
450
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
451
+ out_indices (Sequence[int]): Output from which stages.
452
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
453
+ -1 means not freezing any parameters.
454
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
455
+ """
456
+
457
+ def __init__(self,
458
+ pretrain_img_size=224,
459
+ patch_size=4,
460
+ in_chans=3,
461
+ embed_dim=96,
462
+ depths=[2, 2, 6, 2],
463
+ num_heads=[3, 6, 12, 24],
464
+ window_size=7,
465
+ mlp_ratio=4.,
466
+ qkv_bias=True,
467
+ qk_scale=None,
468
+ drop_rate=0.,
469
+ attn_drop_rate=0.,
470
+ drop_path_rate=0.2,
471
+ norm_layer=nn.LayerNorm,
472
+ ape=False,
473
+ patch_norm=True,
474
+ out_indices=(0, 1, 2, 3),
475
+ frozen_stages=-1,
476
+ use_checkpoint=False):
477
+ super().__init__()
478
+
479
+ self.pretrain_img_size = pretrain_img_size
480
+ self.num_layers = len(depths)
481
+ self.embed_dim = embed_dim
482
+ self.ape = ape
483
+ self.patch_norm = patch_norm
484
+ self.out_indices = out_indices
485
+ self.frozen_stages = frozen_stages
486
+
487
+ # split image into non-overlapping patches
488
+ self.patch_embed = PatchEmbed(
489
+ patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
490
+ norm_layer=norm_layer if self.patch_norm else None)
491
+
492
+ # absolute position embedding
493
+ if self.ape:
494
+ pretrain_img_size = to_2tuple(pretrain_img_size)
495
+ patch_size = to_2tuple(patch_size)
496
+ patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
497
+
498
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
499
+ trunc_normal_(self.absolute_pos_embed, std=.02)
500
+
501
+ self.pos_drop = nn.Dropout(p=drop_rate)
502
+
503
+ # stochastic depth
504
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
505
+
506
+ # build layers
507
+ self.layers = nn.ModuleList()
508
+ for i_layer in range(self.num_layers):
509
+ layer = BasicLayer(
510
+ dim=int(embed_dim * 2 ** i_layer),
511
+ depth=depths[i_layer],
512
+ num_heads=num_heads[i_layer],
513
+ window_size=window_size,
514
+ mlp_ratio=mlp_ratio,
515
+ qkv_bias=qkv_bias,
516
+ qk_scale=qk_scale,
517
+ drop=drop_rate,
518
+ attn_drop=attn_drop_rate,
519
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
520
+ norm_layer=norm_layer,
521
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
522
+ use_checkpoint=use_checkpoint)
523
+ self.layers.append(layer)
524
+
525
+ num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
526
+ self.num_features = num_features
527
+
528
+ # add a norm layer for each output
529
+ for i_layer in out_indices:
530
+ layer = norm_layer(num_features[i_layer])
531
+ layer_name = f'norm{i_layer}'
532
+ self.add_module(layer_name, layer)
533
+
534
+ self._freeze_stages()
535
+
536
+ def _freeze_stages(self):
537
+ if self.frozen_stages >= 0:
538
+ self.patch_embed.eval()
539
+ for param in self.patch_embed.parameters():
540
+ param.requires_grad = False
541
+
542
+ if self.frozen_stages >= 1 and self.ape:
543
+ self.absolute_pos_embed.requires_grad = False
544
+
545
+ if self.frozen_stages >= 2:
546
+ self.pos_drop.eval()
547
+ for i in range(0, self.frozen_stages - 1):
548
+ m = self.layers[i]
549
+ m.eval()
550
+ for param in m.parameters():
551
+ param.requires_grad = False
552
+
553
+
554
+ def forward(self, x):
555
+
556
+ x = self.patch_embed(x)
557
+
558
+ Wh, Ww = x.size(2), x.size(3)
559
+ if self.ape:
560
+ # interpolate the position embedding to the corresponding size
561
+ absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
562
+ x = (x + absolute_pos_embed) # B Wh*Ww C
563
+
564
+ outs = [x.contiguous()]
565
+ x = x.flatten(2).transpose(1, 2)
566
+ x = self.pos_drop(x)
567
+
568
+
569
+ for i in range(self.num_layers):
570
+ layer = self.layers[i]
571
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
572
+
573
+
574
+ if i in self.out_indices:
575
+ norm_layer = getattr(self, f'norm{i}')
576
+ x_out = norm_layer(x_out)
577
+
578
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
579
+ outs.append(out)
580
+
581
+
582
+
583
+ return tuple(outs)
584
+
585
+
586
+
587
+
588
+
589
+
590
+
591
+ def get_activation_fn(activation):
592
+ """Return an activation function given a string"""
593
+ if activation == "gelu":
594
+ return F.gelu
595
+
596
+ raise RuntimeError(F"activation should be gelu, not {activation}.")
597
+
598
+
599
+ def make_cbr(in_dim, out_dim):
600
+ return nn.Sequential(nn.Conv2d(in_dim, out_dim, kernel_size=3, padding=1), nn.InstanceNorm2d(out_dim), nn.GELU())
601
+
602
+
603
+ def make_cbg(in_dim, out_dim):
604
+ return nn.Sequential(nn.Conv2d(in_dim, out_dim, kernel_size=3, padding=1), nn.InstanceNorm2d(out_dim), nn.GELU())
605
+
606
+
607
+ def rescale_to(x, scale_factor: float = 2, interpolation='nearest'):
608
+ return F.interpolate(x, scale_factor=scale_factor, mode=interpolation)
609
+
610
+
611
+ def resize_as(x, y, interpolation='bilinear'):
612
+ return F.interpolate(x, size=y.shape[-2:], mode=interpolation)
613
+
614
+
615
+ def image2patches(x):
616
+ """b c (hg h) (wg w) -> (hg wg b) c h w"""
617
+ x = rearrange(x, 'b c (hg h) (wg w) -> (hg wg b) c h w', hg=2, wg=2)
618
+ return x
619
+
620
+
621
+ def patches2image(x):
622
+ """(hg wg b) c h w -> b c (hg h) (wg w)"""
623
+ x = rearrange(x, '(hg wg b) c h w -> b c (hg h) (wg w)', hg=2, wg=2)
624
+ return x
625
+ class PositionEmbeddingSine:
626
+ def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
627
+ super().__init__()
628
+ self.num_pos_feats = num_pos_feats
629
+ self.temperature = temperature
630
+ self.normalize = normalize
631
+ if scale is not None and normalize is False:
632
+ raise ValueError("normalize should be True if scale is passed")
633
+ if scale is None:
634
+ scale = 2 * math.pi
635
+ self.scale = scale
636
+ self.dim_t = torch.arange(0, self.num_pos_feats, dtype=torch.float32)
637
+
638
+ def __call__(self, b, h, w):
639
+ device = self.dim_t.device
640
+ mask = torch.zeros([b, h, w], dtype=torch.bool, device=device)
641
+ assert mask is not None
642
+ not_mask = ~mask
643
+ y_embed = not_mask.cumsum(dim=1, dtype=torch.float32)
644
+ x_embed = not_mask.cumsum(dim=2, dtype=torch.float32)
645
+ if self.normalize:
646
+ eps = 1e-6
647
+ y_embed = (y_embed - 0.5) / (y_embed[:, -1:, :] + eps) * self.scale
648
+ x_embed = (x_embed - 0.5) / (x_embed[:, :, -1:] + eps) * self.scale
649
+
650
+ dim_t = self.temperature ** (2 * (self.dim_t.to(device) // 2) / self.num_pos_feats)
651
+ pos_x = x_embed[:, :, :, None] / dim_t
652
+ pos_y = y_embed[:, :, :, None] / dim_t
653
+
654
+ pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
655
+ pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
656
+
657
+ return torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
658
+
659
+
660
+ class MCLM(nn.Module):
661
+ def __init__(self, d_model, num_heads, pool_ratios=[1, 4, 8]):
662
+ super(MCLM, self).__init__()
663
+ self.attention = nn.ModuleList([
664
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
665
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
666
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
667
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
668
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1)
669
+ ])
670
+
671
+ self.linear1 = nn.Linear(d_model, d_model * 2)
672
+ self.linear2 = nn.Linear(d_model * 2, d_model)
673
+ self.linear3 = nn.Linear(d_model, d_model * 2)
674
+ self.linear4 = nn.Linear(d_model * 2, d_model)
675
+ self.norm1 = nn.LayerNorm(d_model)
676
+ self.norm2 = nn.LayerNorm(d_model)
677
+ self.dropout = nn.Dropout(0.1)
678
+ self.dropout1 = nn.Dropout(0.1)
679
+ self.dropout2 = nn.Dropout(0.1)
680
+ self.activation = get_activation_fn('gelu')
681
+ self.pool_ratios = pool_ratios
682
+ self.p_poses = []
683
+ self.g_pos = None
684
+ self.positional_encoding = PositionEmbeddingSine(num_pos_feats=d_model // 2, normalize=True)
685
+
686
+ def forward(self, l, g):
687
+ """
688
+ l: 4,c,h,w
689
+ g: 1,c,h,w
690
+ """
691
+ b, c, h, w = l.size()
692
+ # 4,c,h,w -> 1,c,2h,2w
693
+ concated_locs = rearrange(l, '(hg wg b) c h w -> b c (hg h) (wg w)', hg=2, wg=2)
694
+
695
+ pools = []
696
+ for pool_ratio in self.pool_ratios:
697
+ # b,c,h,w
698
+ tgt_hw = (round(h / pool_ratio), round(w / pool_ratio))
699
+ pool = F.adaptive_avg_pool2d(concated_locs, tgt_hw)
700
+ pools.append(rearrange(pool, 'b c h w -> (h w) b c'))
701
+ if self.g_pos is None:
702
+ pos_emb = self.positional_encoding(pool.shape[0], pool.shape[2], pool.shape[3])
703
+ pos_emb = rearrange(pos_emb, 'b c h w -> (h w) b c')
704
+ self.p_poses.append(pos_emb)
705
+ pools = torch.cat(pools, 0)
706
+ if self.g_pos is None:
707
+ self.p_poses = torch.cat(self.p_poses, dim=0)
708
+ pos_emb = self.positional_encoding(g.shape[0], g.shape[2], g.shape[3])
709
+ self.g_pos = rearrange(pos_emb, 'b c h w -> (h w) b c')
710
+
711
+ device = pools.device
712
+ self.p_poses = self.p_poses.to(device)
713
+ self.g_pos = self.g_pos.to(device)
714
+
715
+
716
+ # attention between glb (q) & multisensory concated-locs (k,v)
717
+ g_hw_b_c = rearrange(g, 'b c h w -> (h w) b c')
718
+
719
+
720
+ g_hw_b_c = g_hw_b_c + self.dropout1(self.attention[0](g_hw_b_c + self.g_pos, pools + self.p_poses, pools)[0])
721
+ g_hw_b_c = self.norm1(g_hw_b_c)
722
+ g_hw_b_c = g_hw_b_c + self.dropout2(self.linear2(self.dropout(self.activation(self.linear1(g_hw_b_c)).clone())))
723
+ g_hw_b_c = self.norm2(g_hw_b_c)
724
+
725
+ # attention between origin locs (q) & freashed glb (k,v)
726
+ l_hw_b_c = rearrange(l, "b c h w -> (h w) b c")
727
+ _g_hw_b_c = rearrange(g_hw_b_c, '(h w) b c -> h w b c', h=h, w=w)
728
+ _g_hw_b_c = rearrange(_g_hw_b_c, "(ng h) (nw w) b c -> (h w) (ng nw b) c", ng=2, nw=2)
729
+ outputs_re = []
730
+ for i, (_l, _g) in enumerate(zip(l_hw_b_c.chunk(4, dim=1), _g_hw_b_c.chunk(4, dim=1))):
731
+ outputs_re.append(self.attention[i + 1](_l, _g, _g)[0]) # (h w) 1 c
732
+ outputs_re = torch.cat(outputs_re, 1) # (h w) 4 c
733
+
734
+ l_hw_b_c = l_hw_b_c + self.dropout1(outputs_re)
735
+ l_hw_b_c = self.norm1(l_hw_b_c)
736
+ l_hw_b_c = l_hw_b_c + self.dropout2(self.linear4(self.dropout(self.activation(self.linear3(l_hw_b_c)).clone())))
737
+ l_hw_b_c = self.norm2(l_hw_b_c)
738
+
739
+ l = torch.cat((l_hw_b_c, g_hw_b_c), 1) # hw,b(5),c
740
+ return rearrange(l, "(h w) b c -> b c h w", h=h, w=w) ## (5,c,h*w)
741
+
742
+
743
+
744
+
745
+
746
+
747
+
748
+
749
+
750
+ class MCRM(nn.Module):
751
+ def __init__(self, d_model, num_heads, pool_ratios=[4, 8, 16], h=None):
752
+ super(MCRM, self).__init__()
753
+ self.attention = nn.ModuleList([
754
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
755
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
756
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
757
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1)
758
+ ])
759
+ self.linear3 = nn.Linear(d_model, d_model * 2)
760
+ self.linear4 = nn.Linear(d_model * 2, d_model)
761
+ self.norm1 = nn.LayerNorm(d_model)
762
+ self.norm2 = nn.LayerNorm(d_model)
763
+ self.dropout = nn.Dropout(0.1)
764
+ self.dropout1 = nn.Dropout(0.1)
765
+ self.dropout2 = nn.Dropout(0.1)
766
+ self.sigmoid = nn.Sigmoid()
767
+ self.activation = get_activation_fn('gelu')
768
+ self.sal_conv = nn.Conv2d(d_model, 1, 1)
769
+ self.pool_ratios = pool_ratios
770
+
771
+ def forward(self, x):
772
+ device = x.device
773
+ b, c, h, w = x.size()
774
+ loc, glb = x.split([4, 1], dim=0) # 4,c,h,w; 1,c,h,w
775
+
776
+ patched_glb = rearrange(glb, 'b c (hg h) (wg w) -> (hg wg b) c h w', hg=2, wg=2)
777
+
778
+ token_attention_map = self.sigmoid(self.sal_conv(glb))
779
+ token_attention_map = F.interpolate(token_attention_map, size=patches2image(loc).shape[-2:], mode='nearest')
780
+ loc = loc * rearrange(token_attention_map, 'b c (hg h) (wg w) -> (hg wg b) c h w', hg=2, wg=2)
781
+
782
+ pools = []
783
+ for pool_ratio in self.pool_ratios:
784
+ tgt_hw = (round(h / pool_ratio), round(w / pool_ratio))
785
+ pool = F.adaptive_avg_pool2d(patched_glb, tgt_hw)
786
+ pools.append(rearrange(pool, 'nl c h w -> nl c (h w)')) # nl(4),c,hw
787
+
788
+ pools = rearrange(torch.cat(pools, 2), "nl c nphw -> nl nphw 1 c")
789
+ loc_ = rearrange(loc, 'nl c h w -> nl (h w) 1 c')
790
+
791
+ outputs = []
792
+ for i, q in enumerate(loc_.unbind(dim=0)): # traverse all local patches
793
+ v = pools[i]
794
+ k = v
795
+ outputs.append(self.attention[i](q, k, v)[0])
796
+
797
+ outputs = torch.cat(outputs, 1)
798
+ src = loc.view(4, c, -1).permute(2, 0, 1) + self.dropout1(outputs)
799
+ src = self.norm1(src)
800
+ src = src + self.dropout2(self.linear4(self.dropout(self.activation(self.linear3(src)).clone())))
801
+ src = self.norm2(src)
802
+ src = src.permute(1, 2, 0).reshape(4, c, h, w) # freshed loc
803
+ glb = glb + F.interpolate(patches2image(src), size=glb.shape[-2:], mode='nearest') # freshed glb
804
+
805
+ return torch.cat((src, glb), 0), token_attention_map
806
+
807
+
808
+ class BEN_Base(nn.Module):
809
+ def __init__(self):
810
+ super().__init__()
811
+
812
+ self.backbone = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
813
+ emb_dim = 128
814
+ self.sideout5 = nn.Sequential(nn.Conv2d(emb_dim, 1, kernel_size=3, padding=1))
815
+ self.sideout4 = nn.Sequential(nn.Conv2d(emb_dim, 1, kernel_size=3, padding=1))
816
+ self.sideout3 = nn.Sequential(nn.Conv2d(emb_dim, 1, kernel_size=3, padding=1))
817
+ self.sideout2 = nn.Sequential(nn.Conv2d(emb_dim, 1, kernel_size=3, padding=1))
818
+ self.sideout1 = nn.Sequential(nn.Conv2d(emb_dim, 1, kernel_size=3, padding=1))
819
+
820
+ self.output5 = make_cbr(1024, emb_dim)
821
+ self.output4 = make_cbr(512, emb_dim)
822
+ self.output3 = make_cbr(256, emb_dim)
823
+ self.output2 = make_cbr(128, emb_dim)
824
+ self.output1 = make_cbr(128, emb_dim)
825
+
826
+ self.multifieldcrossatt = MCLM(emb_dim, 1, [1, 4, 8])
827
+ self.conv1 = make_cbr(emb_dim, emb_dim)
828
+ self.conv2 = make_cbr(emb_dim, emb_dim)
829
+ self.conv3 = make_cbr(emb_dim, emb_dim)
830
+ self.conv4 = make_cbr(emb_dim, emb_dim)
831
+ self.dec_blk1 = MCRM(emb_dim, 1, [2, 4, 8])
832
+ self.dec_blk2 = MCRM(emb_dim, 1, [2, 4, 8])
833
+ self.dec_blk3 = MCRM(emb_dim, 1, [2, 4, 8])
834
+ self.dec_blk4 = MCRM(emb_dim, 1, [2, 4, 8])
835
+
836
+ self.insmask_head = nn.Sequential(
837
+ nn.Conv2d(emb_dim, 384, kernel_size=3, padding=1),
838
+ nn.InstanceNorm2d(384),
839
+ nn.GELU(),
840
+ nn.Conv2d(384, 384, kernel_size=3, padding=1),
841
+ nn.InstanceNorm2d(384),
842
+ nn.GELU(),
843
+ nn.Conv2d(384, emb_dim, kernel_size=3, padding=1)
844
+ )
845
+
846
+ self.shallow = nn.Sequential(nn.Conv2d(3, emb_dim, kernel_size=3, padding=1))
847
+ self.upsample1 = make_cbg(emb_dim, emb_dim)
848
+ self.upsample2 = make_cbg(emb_dim, emb_dim)
849
+ self.output = nn.Sequential(nn.Conv2d(emb_dim, 1, kernel_size=3, padding=1))
850
+
851
+ for m in self.modules():
852
+ if isinstance(m, nn.GELU) or isinstance(m, nn.Dropout):
853
+ m.inplace = True
854
+
855
+ def forward(self, x):
856
+ device = x.device
857
+ shallow = self.shallow(x)
858
+ glb = rescale_to(x, scale_factor=0.5, interpolation='bilinear')
859
+ loc = image2patches(x)
860
+ input = torch.cat((loc, glb), dim=0)
861
+ feature = self.backbone(input)
862
+ e5 = self.output5(feature[4]) # (5,128,16,16)
863
+ e4 = self.output4(feature[3]) # (5,128,32,32)
864
+ e3 = self.output3(feature[2]) # (5,128,64,64)
865
+ e2 = self.output2(feature[1]) # (5,128,128,128)
866
+ e1 = self.output1(feature[0]) # (5,128,128,128)
867
+ loc_e5, glb_e5 = e5.split([4, 1], dim=0)
868
+ e5 = self.multifieldcrossatt(loc_e5, glb_e5) # (4,128,16,16)
869
+
870
+ e4, tokenattmap4 = self.dec_blk4(e4 + resize_as(e5, e4))
871
+ e4 = self.conv4(e4)
872
+ e3, tokenattmap3 = self.dec_blk3(e3 + resize_as(e4, e3))
873
+ e3 = self.conv3(e3)
874
+ e2, tokenattmap2 = self.dec_blk2(e2 + resize_as(e3, e2))
875
+ e2 = self.conv2(e2)
876
+ e1, tokenattmap1 = self.dec_blk1(e1 + resize_as(e2, e1))
877
+ e1 = self.conv1(e1)
878
+ loc_e1, glb_e1 = e1.split([4, 1], dim=0)
879
+ output1_cat = patches2image(loc_e1) # (1,128,256,256)
880
+ output1_cat = output1_cat + resize_as(glb_e1, output1_cat)
881
+ final_output = self.insmask_head(output1_cat) # (1,128,256,256)
882
+ final_output = final_output + resize_as(shallow, final_output)
883
+ final_output = self.upsample1(rescale_to(final_output))
884
+ final_output = rescale_to(final_output + resize_as(shallow, final_output))
885
+ final_output = self.upsample2(final_output)
886
+ final_output = self.output(final_output)
887
+
888
+ return final_output.sigmoid()
889
+
890
+ @torch.no_grad()
891
+ def inference(self,image):
892
+ image, h, w,original_image = rgb_loader_refiner(image)
893
+
894
+ img_tensor = img_transform(image).unsqueeze(0).to(next(self.parameters()).device)
895
+
896
+ res = self.forward(img_tensor)
897
+
898
+ pred_array = postprocess_image(res, im_size=[w, h])
899
+
900
+ mask_image = Image.fromarray(pred_array, mode='L')
901
+
902
+ blurred_mask = mask_image.filter(ImageFilter.GaussianBlur(radius=1))
903
+
904
+ original_image_rgba = original_image.convert("RGBA")
905
+
906
+ foreground = original_image_rgba.copy()
907
+
908
+ foreground.putalpha(blurred_mask)
909
+
910
+ return blurred_mask, foreground
911
+
912
+ def loadcheckpoints(self,model_path):
913
+ model_dict = torch.load(model_path, map_location="cpu", weights_only=True)
914
+ self.load_state_dict(model_dict['model_state_dict'], strict=True)
915
+ del model_path
916
+
917
+
918
+
919
+
920
+ def rgb_loader_refiner( original_image):
921
+ h, w = original_image.size
922
+ # # Apply EXIF orientation
923
+ image = ImageOps.exif_transpose(original_image)
924
+ # Convert to RGB if necessary
925
+ if image.mode != 'RGB':
926
+ image = image.convert('RGB')
927
+
928
+ # Resize the image
929
+ image = image.resize((1024, 1024), resample=Image.LANCZOS)
930
+
931
+ return image.convert('RGB'), h, w,original_image
932
+
933
+ # Define the image transformation
934
+ img_transform = transforms.Compose([
935
+ transforms.ToTensor(),
936
+ transforms.ConvertImageDtype(torch.float32),
937
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
938
+ ])
939
+
940
+ def postprocess_image(result: torch.Tensor, im_size: list) -> np.ndarray:
941
+ result = torch.squeeze(F.interpolate(result, size=im_size, mode='bilinear'), 0)
942
+ ma = torch.max(result)
943
+ mi = torch.min(result)
944
+ result = (result - mi) / (ma - mi)
945
+ im_array = (result * 255).permute(1, 2, 0).cpu().data.numpy().astype(np.uint8)
946
+ im_array = np.squeeze(im_array)
947
+ return im_array
948
+
949
+
950
+
951
+
models/RMBG/BEN2/BEN2.py ADDED
@@ -0,0 +1,1401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import math
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from einops import rearrange
7
+ import torch.utils.checkpoint as checkpoint
8
+ import numpy as np
9
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
10
+ from PIL import Image, ImageOps
11
+ from torchvision import transforms
12
+ import numpy as np
13
+ import random
14
+ import cv2
15
+ import os
16
+ import subprocess
17
+ import time
18
+ import tempfile
19
+
20
+
21
+
22
+
23
+ def set_random_seed(seed):
24
+ random.seed(seed)
25
+ np.random.seed(seed)
26
+ torch.manual_seed(seed)
27
+ torch.cuda.manual_seed(seed)
28
+ torch.cuda.manual_seed_all(seed)
29
+ torch.backends.cudnn.deterministic = True
30
+ torch.backends.cudnn.benchmark = False
31
+ set_random_seed(9)
32
+
33
+
34
+ torch.set_float32_matmul_precision('highest')
35
+
36
+
37
+
38
+ class Mlp(nn.Module):
39
+ """ Multilayer perceptron."""
40
+
41
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
42
+ super().__init__()
43
+ out_features = out_features or in_features
44
+ hidden_features = hidden_features or in_features
45
+ self.fc1 = nn.Linear(in_features, hidden_features)
46
+ self.act = act_layer()
47
+ self.fc2 = nn.Linear(hidden_features, out_features)
48
+ self.drop = nn.Dropout(drop)
49
+
50
+ def forward(self, x):
51
+ x = self.fc1(x)
52
+ x = self.act(x)
53
+ x = self.drop(x)
54
+ x = self.fc2(x)
55
+ x = self.drop(x)
56
+ return x
57
+
58
+
59
+ def window_partition(x, window_size):
60
+ """
61
+ Args:
62
+ x: (B, H, W, C)
63
+ window_size (int): window size
64
+ Returns:
65
+ windows: (num_windows*B, window_size, window_size, C)
66
+ """
67
+ B, H, W, C = x.shape
68
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
69
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
70
+ return windows
71
+
72
+
73
+ def window_reverse(windows, window_size, H, W):
74
+ """
75
+ Args:
76
+ windows: (num_windows*B, window_size, window_size, C)
77
+ window_size (int): Window size
78
+ H (int): Height of image
79
+ W (int): Width of image
80
+ Returns:
81
+ x: (B, H, W, C)
82
+ """
83
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
84
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
85
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
86
+ return x
87
+
88
+
89
+ class WindowAttention(nn.Module):
90
+ """ Window based multi-head self attention (W-MSA) module with relative position bias.
91
+ It supports both of shifted and non-shifted window.
92
+ Args:
93
+ dim (int): Number of input channels.
94
+ window_size (tuple[int]): The height and width of the window.
95
+ num_heads (int): Number of attention heads.
96
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
97
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
98
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
99
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
100
+ """
101
+
102
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
103
+
104
+ super().__init__()
105
+ self.dim = dim
106
+ self.window_size = window_size # Wh, Ww
107
+ self.num_heads = num_heads
108
+ head_dim = dim // num_heads
109
+ self.scale = qk_scale or head_dim ** -0.5
110
+
111
+ # define a parameter table of relative position bias
112
+ self.relative_position_bias_table = nn.Parameter(
113
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
114
+
115
+ # get pair-wise relative position index for each token inside the window
116
+ coords_h = torch.arange(self.window_size[0])
117
+ coords_w = torch.arange(self.window_size[1])
118
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
119
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
120
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
121
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
122
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
123
+ relative_coords[:, :, 1] += self.window_size[1] - 1
124
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
125
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
126
+ self.register_buffer("relative_position_index", relative_position_index)
127
+
128
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
129
+ self.attn_drop = nn.Dropout(attn_drop)
130
+ self.proj = nn.Linear(dim, dim)
131
+ self.proj_drop = nn.Dropout(proj_drop)
132
+
133
+ trunc_normal_(self.relative_position_bias_table, std=.02)
134
+ self.softmax = nn.Softmax(dim=-1)
135
+
136
+ def forward(self, x, mask=None):
137
+ """ Forward function.
138
+ Args:
139
+ x: input features with shape of (num_windows*B, N, C)
140
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
141
+ """
142
+ B_, N, C = x.shape
143
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
144
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
145
+
146
+ q = q * self.scale
147
+ attn = (q @ k.transpose(-2, -1))
148
+
149
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
150
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
151
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
152
+ attn = attn + relative_position_bias.unsqueeze(0)
153
+
154
+ if mask is not None:
155
+ nW = mask.shape[0]
156
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
157
+ attn = attn.view(-1, self.num_heads, N, N)
158
+ attn = self.softmax(attn)
159
+ else:
160
+ attn = self.softmax(attn)
161
+
162
+ attn = self.attn_drop(attn)
163
+
164
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
165
+ x = self.proj(x)
166
+ x = self.proj_drop(x)
167
+ return x
168
+
169
+
170
+ class SwinTransformerBlock(nn.Module):
171
+ """ Swin Transformer Block.
172
+ Args:
173
+ dim (int): Number of input channels.
174
+ num_heads (int): Number of attention heads.
175
+ window_size (int): Window size.
176
+ shift_size (int): Shift size for SW-MSA.
177
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
178
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
179
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
180
+ drop (float, optional): Dropout rate. Default: 0.0
181
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
182
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
183
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
184
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
185
+ """
186
+
187
+ def __init__(self, dim, num_heads, window_size=7, shift_size=0,
188
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
189
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
190
+ super().__init__()
191
+ self.dim = dim
192
+ self.num_heads = num_heads
193
+ self.window_size = window_size
194
+ self.shift_size = shift_size
195
+ self.mlp_ratio = mlp_ratio
196
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
197
+
198
+ self.norm1 = norm_layer(dim)
199
+ self.attn = WindowAttention(
200
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
201
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
202
+
203
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
204
+ self.norm2 = norm_layer(dim)
205
+ mlp_hidden_dim = int(dim * mlp_ratio)
206
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
207
+
208
+ self.H = None
209
+ self.W = None
210
+
211
+ def forward(self, x, mask_matrix):
212
+ """ Forward function.
213
+ Args:
214
+ x: Input feature, tensor size (B, H*W, C).
215
+ H, W: Spatial resolution of the input feature.
216
+ mask_matrix: Attention mask for cyclic shift.
217
+ """
218
+ B, L, C = x.shape
219
+ H, W = self.H, self.W
220
+ assert L == H * W, "input feature has wrong size"
221
+
222
+ shortcut = x
223
+ x = self.norm1(x)
224
+ x = x.view(B, H, W, C)
225
+
226
+ # pad feature maps to multiples of window size
227
+ pad_l = pad_t = 0
228
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
229
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
230
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
231
+ _, Hp, Wp, _ = x.shape
232
+
233
+ # cyclic shift
234
+ if self.shift_size > 0:
235
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
236
+ attn_mask = mask_matrix
237
+ else:
238
+ shifted_x = x
239
+ attn_mask = None
240
+
241
+ # partition windows
242
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
243
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
244
+
245
+ # W-MSA/SW-MSA
246
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
247
+
248
+ # merge windows
249
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
250
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
251
+
252
+ # reverse cyclic shift
253
+ if self.shift_size > 0:
254
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
255
+ else:
256
+ x = shifted_x
257
+
258
+ if pad_r > 0 or pad_b > 0:
259
+ x = x[:, :H, :W, :].contiguous()
260
+
261
+ x = x.view(B, H * W, C)
262
+
263
+ # FFN
264
+ x = shortcut + self.drop_path(x)
265
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
266
+
267
+ return x
268
+
269
+
270
+ class PatchMerging(nn.Module):
271
+ """ Patch Merging Layer
272
+ Args:
273
+ dim (int): Number of input channels.
274
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
275
+ """
276
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
277
+ super().__init__()
278
+ self.dim = dim
279
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
280
+ self.norm = norm_layer(4 * dim)
281
+
282
+ def forward(self, x, H, W):
283
+ """ Forward function.
284
+ Args:
285
+ x: Input feature, tensor size (B, H*W, C).
286
+ H, W: Spatial resolution of the input feature.
287
+ """
288
+ B, L, C = x.shape
289
+ assert L == H * W, "input feature has wrong size"
290
+
291
+ x = x.view(B, H, W, C)
292
+
293
+ # padding
294
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
295
+ if pad_input:
296
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
297
+
298
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
299
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
300
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
301
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
302
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
303
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
304
+
305
+ x = self.norm(x)
306
+ x = self.reduction(x)
307
+
308
+ return x
309
+
310
+
311
+ class BasicLayer(nn.Module):
312
+ """ A basic Swin Transformer layer for one stage.
313
+ Args:
314
+ dim (int): Number of feature channels
315
+ depth (int): Depths of this stage.
316
+ num_heads (int): Number of attention head.
317
+ window_size (int): Local window size. Default: 7.
318
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
319
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
320
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
321
+ drop (float, optional): Dropout rate. Default: 0.0
322
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
323
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
324
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
325
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
326
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
327
+ """
328
+
329
+ def __init__(self,
330
+ dim,
331
+ depth,
332
+ num_heads,
333
+ window_size=7,
334
+ mlp_ratio=4.,
335
+ qkv_bias=True,
336
+ qk_scale=None,
337
+ drop=0.,
338
+ attn_drop=0.,
339
+ drop_path=0.,
340
+ norm_layer=nn.LayerNorm,
341
+ downsample=None,
342
+ use_checkpoint=False):
343
+ super().__init__()
344
+ self.window_size = window_size
345
+ self.shift_size = window_size // 2
346
+ self.depth = depth
347
+ self.use_checkpoint = use_checkpoint
348
+
349
+ # build blocks
350
+ self.blocks = nn.ModuleList([
351
+ SwinTransformerBlock(
352
+ dim=dim,
353
+ num_heads=num_heads,
354
+ window_size=window_size,
355
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
356
+ mlp_ratio=mlp_ratio,
357
+ qkv_bias=qkv_bias,
358
+ qk_scale=qk_scale,
359
+ drop=drop,
360
+ attn_drop=attn_drop,
361
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
362
+ norm_layer=norm_layer)
363
+ for i in range(depth)])
364
+
365
+ # patch merging layer
366
+ if downsample is not None:
367
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
368
+ else:
369
+ self.downsample = None
370
+
371
+ def forward(self, x, H, W):
372
+ """ Forward function.
373
+ Args:
374
+ x: Input feature, tensor size (B, H*W, C).
375
+ H, W: Spatial resolution of the input feature.
376
+ """
377
+
378
+ # calculate attention mask for SW-MSA
379
+ Hp = int(np.ceil(H / self.window_size)) * self.window_size
380
+ Wp = int(np.ceil(W / self.window_size)) * self.window_size
381
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
382
+ h_slices = (slice(0, -self.window_size),
383
+ slice(-self.window_size, -self.shift_size),
384
+ slice(-self.shift_size, None))
385
+ w_slices = (slice(0, -self.window_size),
386
+ slice(-self.window_size, -self.shift_size),
387
+ slice(-self.shift_size, None))
388
+ cnt = 0
389
+ for h in h_slices:
390
+ for w in w_slices:
391
+ img_mask[:, h, w, :] = cnt
392
+ cnt += 1
393
+
394
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
395
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
396
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
397
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
398
+
399
+ for blk in self.blocks:
400
+ blk.H, blk.W = H, W
401
+ if self.use_checkpoint:
402
+ x = checkpoint.checkpoint(blk, x, attn_mask)
403
+ else:
404
+ x = blk(x, attn_mask)
405
+ if self.downsample is not None:
406
+ x_down = self.downsample(x, H, W)
407
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
408
+ return x, H, W, x_down, Wh, Ww
409
+ else:
410
+ return x, H, W, x, H, W
411
+
412
+
413
+ class PatchEmbed(nn.Module):
414
+ """ Image to Patch Embedding
415
+ Args:
416
+ patch_size (int): Patch token size. Default: 4.
417
+ in_chans (int): Number of input image channels. Default: 3.
418
+ embed_dim (int): Number of linear projection output channels. Default: 96.
419
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
420
+ """
421
+
422
+ def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
423
+ super().__init__()
424
+ patch_size = to_2tuple(patch_size)
425
+ self.patch_size = patch_size
426
+
427
+ self.in_chans = in_chans
428
+ self.embed_dim = embed_dim
429
+
430
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
431
+ if norm_layer is not None:
432
+ self.norm = norm_layer(embed_dim)
433
+ else:
434
+ self.norm = None
435
+
436
+ def forward(self, x):
437
+ """Forward function."""
438
+ # padding
439
+ _, _, H, W = x.size()
440
+ if W % self.patch_size[1] != 0:
441
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
442
+ if H % self.patch_size[0] != 0:
443
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
444
+
445
+ x = self.proj(x) # B C Wh Ww
446
+ if self.norm is not None:
447
+ Wh, Ww = x.size(2), x.size(3)
448
+ x = x.flatten(2).transpose(1, 2)
449
+ x = self.norm(x)
450
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
451
+
452
+ return x
453
+
454
+
455
+ class SwinTransformer(nn.Module):
456
+ """ Swin Transformer backbone.
457
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
458
+ https://arxiv.org/pdf/2103.14030
459
+ Args:
460
+ pretrain_img_size (int): Input image size for training the pretrained model,
461
+ used in absolute postion embedding. Default 224.
462
+ patch_size (int | tuple(int)): Patch size. Default: 4.
463
+ in_chans (int): Number of input image channels. Default: 3.
464
+ embed_dim (int): Number of linear projection output channels. Default: 96.
465
+ depths (tuple[int]): Depths of each Swin Transformer stage.
466
+ num_heads (tuple[int]): Number of attention head of each stage.
467
+ window_size (int): Window size. Default: 7.
468
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
469
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
470
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
471
+ drop_rate (float): Dropout rate.
472
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
473
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
474
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
475
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
476
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
477
+ out_indices (Sequence[int]): Output from which stages.
478
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
479
+ -1 means not freezing any parameters.
480
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
481
+ """
482
+
483
+ def __init__(self,
484
+ pretrain_img_size=224,
485
+ patch_size=4,
486
+ in_chans=3,
487
+ embed_dim=96,
488
+ depths=[2, 2, 6, 2],
489
+ num_heads=[3, 6, 12, 24],
490
+ window_size=7,
491
+ mlp_ratio=4.,
492
+ qkv_bias=True,
493
+ qk_scale=None,
494
+ drop_rate=0.,
495
+ attn_drop_rate=0.,
496
+ drop_path_rate=0.2,
497
+ norm_layer=nn.LayerNorm,
498
+ ape=False,
499
+ patch_norm=True,
500
+ out_indices=(0, 1, 2, 3),
501
+ frozen_stages=-1,
502
+ use_checkpoint=False):
503
+ super().__init__()
504
+
505
+ self.pretrain_img_size = pretrain_img_size
506
+ self.num_layers = len(depths)
507
+ self.embed_dim = embed_dim
508
+ self.ape = ape
509
+ self.patch_norm = patch_norm
510
+ self.out_indices = out_indices
511
+ self.frozen_stages = frozen_stages
512
+
513
+ # split image into non-overlapping patches
514
+ self.patch_embed = PatchEmbed(
515
+ patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
516
+ norm_layer=norm_layer if self.patch_norm else None)
517
+
518
+ # absolute position embedding
519
+ if self.ape:
520
+ pretrain_img_size = to_2tuple(pretrain_img_size)
521
+ patch_size = to_2tuple(patch_size)
522
+ patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
523
+
524
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
525
+ trunc_normal_(self.absolute_pos_embed, std=.02)
526
+
527
+ self.pos_drop = nn.Dropout(p=drop_rate)
528
+
529
+ # stochastic depth
530
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
531
+
532
+ # build layers
533
+ self.layers = nn.ModuleList()
534
+ for i_layer in range(self.num_layers):
535
+ layer = BasicLayer(
536
+ dim=int(embed_dim * 2 ** i_layer),
537
+ depth=depths[i_layer],
538
+ num_heads=num_heads[i_layer],
539
+ window_size=window_size,
540
+ mlp_ratio=mlp_ratio,
541
+ qkv_bias=qkv_bias,
542
+ qk_scale=qk_scale,
543
+ drop=drop_rate,
544
+ attn_drop=attn_drop_rate,
545
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
546
+ norm_layer=norm_layer,
547
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
548
+ use_checkpoint=use_checkpoint)
549
+ self.layers.append(layer)
550
+
551
+ num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
552
+ self.num_features = num_features
553
+
554
+ # add a norm layer for each output
555
+ for i_layer in out_indices:
556
+ layer = norm_layer(num_features[i_layer])
557
+ layer_name = f'norm{i_layer}'
558
+ self.add_module(layer_name, layer)
559
+
560
+ self._freeze_stages()
561
+
562
+ def _freeze_stages(self):
563
+ if self.frozen_stages >= 0:
564
+ self.patch_embed.eval()
565
+ for param in self.patch_embed.parameters():
566
+ param.requires_grad = False
567
+
568
+ if self.frozen_stages >= 1 and self.ape:
569
+ self.absolute_pos_embed.requires_grad = False
570
+
571
+ if self.frozen_stages >= 2:
572
+ self.pos_drop.eval()
573
+ for i in range(0, self.frozen_stages - 1):
574
+ m = self.layers[i]
575
+ m.eval()
576
+ for param in m.parameters():
577
+ param.requires_grad = False
578
+
579
+
580
+ def forward(self, x):
581
+
582
+ x = self.patch_embed(x)
583
+
584
+ Wh, Ww = x.size(2), x.size(3)
585
+ if self.ape:
586
+ # interpolate the position embedding to the corresponding size
587
+ absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
588
+ x = (x + absolute_pos_embed) # B Wh*Ww C
589
+
590
+ outs = [x.contiguous()]
591
+ x = x.flatten(2).transpose(1, 2)
592
+ x = self.pos_drop(x)
593
+
594
+
595
+ for i in range(self.num_layers):
596
+ layer = self.layers[i]
597
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
598
+
599
+
600
+ if i in self.out_indices:
601
+ norm_layer = getattr(self, f'norm{i}')
602
+ x_out = norm_layer(x_out)
603
+
604
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
605
+ outs.append(out)
606
+
607
+
608
+
609
+ return tuple(outs)
610
+
611
+
612
+
613
+
614
+
615
+
616
+
617
+
618
+ def get_activation_fn(activation):
619
+ """Return an activation function given a string"""
620
+ if activation == "gelu":
621
+ return F.gelu
622
+
623
+ raise RuntimeError(F"activation should be gelu, not {activation}.")
624
+
625
+
626
+ def make_cbr(in_dim, out_dim):
627
+ return nn.Sequential(nn.Conv2d(in_dim, out_dim, kernel_size=3, padding=1), nn.InstanceNorm2d(out_dim), nn.GELU())
628
+
629
+
630
+ def make_cbg(in_dim, out_dim):
631
+ return nn.Sequential(nn.Conv2d(in_dim, out_dim, kernel_size=3, padding=1), nn.InstanceNorm2d(out_dim), nn.GELU())
632
+
633
+
634
+ def rescale_to(x, scale_factor: float = 2, interpolation='nearest'):
635
+ return F.interpolate(x, scale_factor=scale_factor, mode=interpolation)
636
+
637
+
638
+ def resize_as(x, y, interpolation='bilinear'):
639
+ return F.interpolate(x, size=y.shape[-2:], mode=interpolation)
640
+
641
+
642
+ def image2patches(x):
643
+ """b c (hg h) (wg w) -> (hg wg b) c h w"""
644
+ x = rearrange(x, 'b c (hg h) (wg w) -> (hg wg b) c h w', hg=2, wg=2 )
645
+ return x
646
+
647
+
648
+ def patches2image(x):
649
+ """(hg wg b) c h w -> b c (hg h) (wg w)"""
650
+ x = rearrange(x, '(hg wg b) c h w -> b c (hg h) (wg w)', hg=2, wg=2)
651
+ return x
652
+
653
+
654
+
655
+ class PositionEmbeddingSine:
656
+ def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
657
+ super().__init__()
658
+ self.num_pos_feats = num_pos_feats
659
+ self.temperature = temperature
660
+ self.normalize = normalize
661
+ if scale is not None and normalize is False:
662
+ raise ValueError("normalize should be True if scale is passed")
663
+ if scale is None:
664
+ scale = 2 * math.pi
665
+ self.scale = scale
666
+ self.dim_t = torch.arange(0, self.num_pos_feats, dtype=torch.float32)
667
+
668
+ def __call__(self, b, h, w):
669
+ device = self.dim_t.device
670
+ mask = torch.zeros([b, h, w], dtype=torch.bool, device=device)
671
+ assert mask is not None
672
+ not_mask = ~mask
673
+ y_embed = not_mask.cumsum(dim=1, dtype=torch.float32)
674
+ x_embed = not_mask.cumsum(dim=2, dtype=torch.float32)
675
+ if self.normalize:
676
+ eps = 1e-6
677
+ y_embed = (y_embed - 0.5) / (y_embed[:, -1:, :] + eps) * self.scale
678
+ x_embed = (x_embed - 0.5) / (x_embed[:, :, -1:] + eps) * self.scale
679
+
680
+ dim_t = self.temperature ** (2 * (self.dim_t.to(device) // 2) / self.num_pos_feats)
681
+ pos_x = x_embed[:, :, :, None] / dim_t
682
+ pos_y = y_embed[:, :, :, None] / dim_t
683
+
684
+ pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
685
+ pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
686
+
687
+ return torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
688
+
689
+
690
+
691
+ class PositionEmbeddingSine:
692
+ def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
693
+ super().__init__()
694
+ self.num_pos_feats = num_pos_feats
695
+ self.temperature = temperature
696
+ self.normalize = normalize
697
+ if scale is not None and normalize is False:
698
+ raise ValueError("normalize should be True if scale is passed")
699
+ if scale is None:
700
+ scale = 2 * math.pi
701
+ self.scale = scale
702
+ self.dim_t = torch.arange(0, self.num_pos_feats, dtype=torch.float32)
703
+
704
+ def __call__(self, b, h, w):
705
+ device = self.dim_t.device
706
+ mask = torch.zeros([b, h, w], dtype=torch.bool, device=device)
707
+ assert mask is not None
708
+ not_mask = ~mask
709
+ y_embed = not_mask.cumsum(dim=1, dtype=torch.float32)
710
+ x_embed = not_mask.cumsum(dim=2, dtype=torch.float32)
711
+ if self.normalize:
712
+ eps = 1e-6
713
+ y_embed = (y_embed - 0.5) / (y_embed[:, -1:, :] + eps) * self.scale
714
+ x_embed = (x_embed - 0.5) / (x_embed[:, :, -1:] + eps) * self.scale
715
+
716
+ dim_t = self.temperature ** (2 * (self.dim_t.to(device) // 2) / self.num_pos_feats)
717
+ pos_x = x_embed[:, :, :, None] / dim_t
718
+ pos_y = y_embed[:, :, :, None] / dim_t
719
+
720
+ pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
721
+ pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
722
+
723
+ return torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
724
+
725
+
726
+ class MCLM(nn.Module):
727
+ def __init__(self, d_model, num_heads, pool_ratios=[1, 4, 8]):
728
+ super(MCLM, self).__init__()
729
+ self.attention = nn.ModuleList([
730
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
731
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
732
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
733
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
734
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1)
735
+ ])
736
+
737
+ self.linear1 = nn.Linear(d_model, d_model * 2)
738
+ self.linear2 = nn.Linear(d_model * 2, d_model)
739
+ self.linear3 = nn.Linear(d_model, d_model * 2)
740
+ self.linear4 = nn.Linear(d_model * 2, d_model)
741
+ self.norm1 = nn.LayerNorm(d_model)
742
+ self.norm2 = nn.LayerNorm(d_model)
743
+ self.dropout = nn.Dropout(0.1)
744
+ self.dropout1 = nn.Dropout(0.1)
745
+ self.dropout2 = nn.Dropout(0.1)
746
+ self.activation = get_activation_fn('gelu')
747
+ self.pool_ratios = pool_ratios
748
+ self.p_poses = []
749
+ self.g_pos = None
750
+ self.positional_encoding = PositionEmbeddingSine(num_pos_feats=d_model // 2, normalize=True)
751
+
752
+ def forward(self, l, g):
753
+ """
754
+ l: 4,c,h,w
755
+ g: 1,c,h,w
756
+ """
757
+ self.p_poses = []
758
+ self.g_pos = None
759
+ b, c, h, w = l.size()
760
+ # 4,c,h,w -> 1,c,2h,2w
761
+ concated_locs = rearrange(l, '(hg wg b) c h w -> b c (hg h) (wg w)', hg=2, wg=2)
762
+
763
+ pools = []
764
+ for pool_ratio in self.pool_ratios:
765
+ # b,c,h,w
766
+ tgt_hw = (round(h / pool_ratio), round(w / pool_ratio))
767
+ pool = F.adaptive_avg_pool2d(concated_locs, tgt_hw)
768
+ pools.append(rearrange(pool, 'b c h w -> (h w) b c'))
769
+ if self.g_pos is None:
770
+ pos_emb = self.positional_encoding(pool.shape[0], pool.shape[2], pool.shape[3])
771
+ pos_emb = rearrange(pos_emb, 'b c h w -> (h w) b c')
772
+ self.p_poses.append(pos_emb)
773
+ pools = torch.cat(pools, 0)
774
+ if self.g_pos is None:
775
+ self.p_poses = torch.cat(self.p_poses, dim=0)
776
+ pos_emb = self.positional_encoding(g.shape[0], g.shape[2], g.shape[3])
777
+ self.g_pos = rearrange(pos_emb, 'b c h w -> (h w) b c')
778
+
779
+ device = pools.device
780
+ self.p_poses = self.p_poses.to(device)
781
+ self.g_pos = self.g_pos.to(device)
782
+
783
+
784
+ # attention between glb (q) & multisensory concated-locs (k,v)
785
+ g_hw_b_c = rearrange(g, 'b c h w -> (h w) b c')
786
+
787
+
788
+ g_hw_b_c = g_hw_b_c + self.dropout1(self.attention[0](g_hw_b_c + self.g_pos, pools + self.p_poses, pools)[0])
789
+ g_hw_b_c = self.norm1(g_hw_b_c)
790
+ g_hw_b_c = g_hw_b_c + self.dropout2(self.linear2(self.dropout(self.activation(self.linear1(g_hw_b_c)).clone())))
791
+ g_hw_b_c = self.norm2(g_hw_b_c)
792
+
793
+ # attention between origin locs (q) & freashed glb (k,v)
794
+ l_hw_b_c = rearrange(l, "b c h w -> (h w) b c")
795
+ _g_hw_b_c = rearrange(g_hw_b_c, '(h w) b c -> h w b c', h=h, w=w)
796
+ _g_hw_b_c = rearrange(_g_hw_b_c, "(ng h) (nw w) b c -> (h w) (ng nw b) c", ng=2, nw=2)
797
+ outputs_re = []
798
+ for i, (_l, _g) in enumerate(zip(l_hw_b_c.chunk(4, dim=1), _g_hw_b_c.chunk(4, dim=1))):
799
+ outputs_re.append(self.attention[i + 1](_l, _g, _g)[0]) # (h w) 1 c
800
+ outputs_re = torch.cat(outputs_re, 1) # (h w) 4 c
801
+
802
+ l_hw_b_c = l_hw_b_c + self.dropout1(outputs_re)
803
+ l_hw_b_c = self.norm1(l_hw_b_c)
804
+ l_hw_b_c = l_hw_b_c + self.dropout2(self.linear4(self.dropout(self.activation(self.linear3(l_hw_b_c)).clone())))
805
+ l_hw_b_c = self.norm2(l_hw_b_c)
806
+
807
+ l = torch.cat((l_hw_b_c, g_hw_b_c), 1) # hw,b(5),c
808
+ return rearrange(l, "(h w) b c -> b c h w", h=h, w=w) ## (5,c,h*w)
809
+
810
+
811
+
812
+
813
+
814
+
815
+
816
+
817
+
818
+ class MCRM(nn.Module):
819
+ def __init__(self, d_model, num_heads, pool_ratios=[4, 8, 16], h=None):
820
+ super(MCRM, self).__init__()
821
+ self.attention = nn.ModuleList([
822
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
823
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
824
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1),
825
+ nn.MultiheadAttention(d_model, num_heads, dropout=0.1)
826
+ ])
827
+ self.linear3 = nn.Linear(d_model, d_model * 2)
828
+ self.linear4 = nn.Linear(d_model * 2, d_model)
829
+ self.norm1 = nn.LayerNorm(d_model)
830
+ self.norm2 = nn.LayerNorm(d_model)
831
+ self.dropout = nn.Dropout(0.1)
832
+ self.dropout1 = nn.Dropout(0.1)
833
+ self.dropout2 = nn.Dropout(0.1)
834
+ self.sigmoid = nn.Sigmoid()
835
+ self.activation = get_activation_fn('gelu')
836
+ self.sal_conv = nn.Conv2d(d_model, 1, 1)
837
+ self.pool_ratios = pool_ratios
838
+
839
+ def forward(self, x):
840
+ device = x.device
841
+ b, c, h, w = x.size()
842
+ loc, glb = x.split([4, 1], dim=0) # 4,c,h,w; 1,c,h,w
843
+
844
+ patched_glb = rearrange(glb, 'b c (hg h) (wg w) -> (hg wg b) c h w', hg=2, wg=2)
845
+
846
+ token_attention_map = self.sigmoid(self.sal_conv(glb))
847
+ token_attention_map = F.interpolate(token_attention_map, size=patches2image(loc).shape[-2:], mode='nearest')
848
+ loc = loc * rearrange(token_attention_map, 'b c (hg h) (wg w) -> (hg wg b) c h w', hg=2, wg=2)
849
+
850
+ pools = []
851
+ for pool_ratio in self.pool_ratios:
852
+ tgt_hw = (round(h / pool_ratio), round(w / pool_ratio))
853
+ pool = F.adaptive_avg_pool2d(patched_glb, tgt_hw)
854
+ pools.append(rearrange(pool, 'nl c h w -> nl c (h w)')) # nl(4),c,hw
855
+
856
+ pools = rearrange(torch.cat(pools, 2), "nl c nphw -> nl nphw 1 c")
857
+ loc_ = rearrange(loc, 'nl c h w -> nl (h w) 1 c')
858
+
859
+ outputs = []
860
+ for i, q in enumerate(loc_.unbind(dim=0)): # traverse all local patches
861
+ v = pools[i]
862
+ k = v
863
+ outputs.append(self.attention[i](q, k, v)[0])
864
+
865
+ outputs = torch.cat(outputs, 1)
866
+ src = loc.view(4, c, -1).permute(2, 0, 1) + self.dropout1(outputs)
867
+ src = self.norm1(src)
868
+ src = src + self.dropout2(self.linear4(self.dropout(self.activation(self.linear3(src)).clone())))
869
+ src = self.norm2(src)
870
+ src = src.permute(1, 2, 0).reshape(4, c, h, w) # freshed loc
871
+ glb = glb + F.interpolate(patches2image(src), size=glb.shape[-2:], mode='nearest') # freshed glb
872
+
873
+ return torch.cat((src, glb), 0), token_attention_map
874
+
875
+
876
+
877
+ class BEN_Base(nn.Module):
878
+ def __init__(self):
879
+ super().__init__()
880
+
881
+ self.backbone = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
882
+ emb_dim = 128
883
+ self.sideout5 = nn.Sequential(nn.Conv2d(emb_dim, 1, kernel_size=3, padding=1))
884
+ self.sideout4 = nn.Sequential(nn.Conv2d(emb_dim, 1, kernel_size=3, padding=1))
885
+ self.sideout3 = nn.Sequential(nn.Conv2d(emb_dim, 1, kernel_size=3, padding=1))
886
+ self.sideout2 = nn.Sequential(nn.Conv2d(emb_dim, 1, kernel_size=3, padding=1))
887
+ self.sideout1 = nn.Sequential(nn.Conv2d(emb_dim, 1, kernel_size=3, padding=1))
888
+
889
+ self.output5 = make_cbr(1024, emb_dim)
890
+ self.output4 = make_cbr(512, emb_dim)
891
+ self.output3 = make_cbr(256, emb_dim)
892
+ self.output2 = make_cbr(128, emb_dim)
893
+ self.output1 = make_cbr(128, emb_dim)
894
+
895
+ self.multifieldcrossatt = MCLM(emb_dim, 1, [1, 4, 8])
896
+ self.conv1 = make_cbr(emb_dim, emb_dim)
897
+ self.conv2 = make_cbr(emb_dim, emb_dim)
898
+ self.conv3 = make_cbr(emb_dim, emb_dim)
899
+ self.conv4 = make_cbr(emb_dim, emb_dim)
900
+ self.dec_blk1 = MCRM(emb_dim, 1, [2, 4, 8])
901
+ self.dec_blk2 = MCRM(emb_dim, 1, [2, 4, 8])
902
+ self.dec_blk3 = MCRM(emb_dim, 1, [2, 4, 8])
903
+ self.dec_blk4 = MCRM(emb_dim, 1, [2, 4, 8])
904
+
905
+ self.insmask_head = nn.Sequential(
906
+ nn.Conv2d(emb_dim, 384, kernel_size=3, padding=1),
907
+ nn.InstanceNorm2d(384),
908
+ nn.GELU(),
909
+ nn.Conv2d(384, 384, kernel_size=3, padding=1),
910
+ nn.InstanceNorm2d(384),
911
+ nn.GELU(),
912
+ nn.Conv2d(384, emb_dim, kernel_size=3, padding=1)
913
+ )
914
+
915
+ self.shallow = nn.Sequential(nn.Conv2d(3, emb_dim, kernel_size=3, padding=1))
916
+ self.upsample1 = make_cbg(emb_dim, emb_dim)
917
+ self.upsample2 = make_cbg(emb_dim, emb_dim)
918
+ self.output = nn.Sequential(nn.Conv2d(emb_dim, 1, kernel_size=3, padding=1))
919
+
920
+ for m in self.modules():
921
+ if isinstance(m, nn.GELU) or isinstance(m, nn.Dropout):
922
+ m.inplace = True
923
+
924
+
925
+
926
+ @torch.inference_mode()
927
+ @torch.autocast(device_type="cuda",dtype=torch.float16)
928
+ def forward(self, x):
929
+ real_batch = x.size(0)
930
+
931
+ shallow_batch = self.shallow(x)
932
+ glb_batch = rescale_to(x, scale_factor=0.5, interpolation='bilinear')
933
+
934
+
935
+
936
+ final_input = None
937
+ for i in range(real_batch):
938
+ start = i * 4
939
+ end = (i + 1) * 4
940
+ loc_batch = image2patches(x[i,:,:,:].unsqueeze(dim=0))
941
+ input_ = torch.cat((loc_batch, glb_batch[i,:,:,:].unsqueeze(dim=0)), dim=0)
942
+
943
+
944
+ if final_input == None:
945
+ final_input= input_
946
+ else: final_input = torch.cat((final_input, input_), dim=0)
947
+
948
+ features = self.backbone(final_input)
949
+ outputs = []
950
+
951
+ for i in range(real_batch):
952
+
953
+ start = i * 5
954
+ end = (i + 1) * 5
955
+
956
+ f4 = features[4][start:end, :, :, :] # shape: [5, C, H, W]
957
+ f3 = features[3][start:end, :, :, :]
958
+ f2 = features[2][start:end, :, :, :]
959
+ f1 = features[1][start:end, :, :, :]
960
+ f0 = features[0][start:end, :, :, :]
961
+ e5 = self.output5(f4)
962
+ e4 = self.output4(f3)
963
+ e3 = self.output3(f2)
964
+ e2 = self.output2(f1)
965
+ e1 = self.output1(f0)
966
+ loc_e5, glb_e5 = e5.split([4, 1], dim=0)
967
+ e5 = self.multifieldcrossatt(loc_e5, glb_e5) # (4,128,16,16)
968
+
969
+
970
+ e4, tokenattmap4 = self.dec_blk4(e4 + resize_as(e5, e4))
971
+ e4 = self.conv4(e4)
972
+ e3, tokenattmap3 = self.dec_blk3(e3 + resize_as(e4, e3))
973
+ e3 = self.conv3(e3)
974
+ e2, tokenattmap2 = self.dec_blk2(e2 + resize_as(e3, e2))
975
+ e2 = self.conv2(e2)
976
+ e1, tokenattmap1 = self.dec_blk1(e1 + resize_as(e2, e1))
977
+ e1 = self.conv1(e1)
978
+
979
+ loc_e1, glb_e1 = e1.split([4, 1], dim=0)
980
+
981
+ output1_cat = patches2image(loc_e1) # (1,128,256,256)
982
+
983
+ # add glb feat in
984
+ output1_cat = output1_cat + resize_as(glb_e1, output1_cat)
985
+ # merge
986
+ final_output = self.insmask_head(output1_cat) # (1,128,256,256)
987
+ # shallow feature merge
988
+ shallow = shallow_batch[i,:,:,:].unsqueeze(dim=0)
989
+ final_output = final_output + resize_as(shallow, final_output)
990
+ final_output = self.upsample1(rescale_to(final_output))
991
+ final_output = rescale_to(final_output + resize_as(shallow, final_output))
992
+ final_output = self.upsample2(final_output)
993
+ final_output = self.output(final_output)
994
+ mask = final_output.sigmoid()
995
+ outputs.append(mask)
996
+
997
+ return torch.cat(outputs, dim=0)
998
+
999
+
1000
+
1001
+
1002
+ def loadcheckpoints(self,model_path):
1003
+ model_dict = torch.load(model_path, map_location="cpu", weights_only=True)
1004
+ self.load_state_dict(model_dict['model_state_dict'], strict=True)
1005
+ del model_path
1006
+
1007
+ def inference(self,image,refine_foreground=False):
1008
+
1009
+ set_random_seed(9)
1010
+ # image = ImageOps.exif_transpose(image)
1011
+ if isinstance(image, Image.Image):
1012
+ image, h, w,original_image = rgb_loader_refiner(image)
1013
+ if torch.cuda.is_available():
1014
+
1015
+ img_tensor = img_transform(image).unsqueeze(0).to(next(self.parameters()).device)
1016
+ else:
1017
+ img_tensor = img_transform32(image).unsqueeze(0).to(next(self.parameters()).device)
1018
+
1019
+
1020
+ with torch.no_grad():
1021
+ res = self.forward(img_tensor)
1022
+
1023
+ # Show Results
1024
+ if refine_foreground == True:
1025
+
1026
+ pred_pil = transforms.ToPILImage()(res.squeeze())
1027
+ image_masked = refine_foreground_process(original_image, pred_pil)
1028
+
1029
+ image_masked.putalpha(pred_pil.resize(original_image.size))
1030
+ return image_masked
1031
+
1032
+ else:
1033
+ alpha = postprocess_image(res, im_size=[w,h])
1034
+ pred_pil = transforms.ToPILImage()(alpha)
1035
+ mask = pred_pil.resize(original_image.size)
1036
+ original_image.putalpha(mask)
1037
+ # mask = Image.fromarray(alpha)
1038
+
1039
+ return original_image
1040
+
1041
+
1042
+ else:
1043
+ foregrounds = []
1044
+ for batch in image:
1045
+ image, h, w,original_image = rgb_loader_refiner(batch)
1046
+ if torch.cuda.is_available():
1047
+
1048
+ img_tensor = img_transform(image).unsqueeze(0).to(next(self.parameters()).device)
1049
+ else:
1050
+ img_tensor = img_transform32(image).unsqueeze(0).to(next(self.parameters()).device)
1051
+
1052
+ with torch.no_grad():
1053
+ res = self.forward(img_tensor)
1054
+
1055
+ if refine_foreground == True:
1056
+
1057
+ pred_pil = transforms.ToPILImage()(res.squeeze())
1058
+ image_masked = refine_foreground_process(original_image, pred_pil)
1059
+
1060
+ image_masked.putalpha(pred_pil.resize(original_image.size))
1061
+
1062
+ foregrounds.append(image_masked)
1063
+ else:
1064
+ alpha = postprocess_image(res, im_size=[w,h])
1065
+ pred_pil = transforms.ToPILImage()(alpha)
1066
+ mask = pred_pil.resize(original_image.size)
1067
+ original_image.putalpha(mask)
1068
+ # mask = Image.fromarray(alpha)
1069
+ foregrounds.append(original_image)
1070
+
1071
+ return foregrounds
1072
+
1073
+
1074
+
1075
+
1076
+ def segment_video(self, video_path, output_path="./", fps=0, refine_foreground=False, batch=1, print_frames_processed=True, webm = False, rgb_value= (0, 255, 0)):
1077
+
1078
+ """
1079
+ Segments the given video to extract the foreground (with alpha) from each frame
1080
+ and saves the result as either a WebM video (with alpha channel) or MP4 (with a
1081
+ color background).
1082
+
1083
+ Args:
1084
+ video_path (str):
1085
+ Path to the input video file.
1086
+
1087
+ output_path (str, optional):
1088
+ Directory (or full path) where the output video and/or files will be saved.
1089
+ Defaults to "./".
1090
+
1091
+ fps (int, optional):
1092
+ The frames per second (FPS) to use for the output video. If 0 (default), the
1093
+ original FPS of the input video is used. Otherwise, overrides it.
1094
+
1095
+ refine_foreground (bool, optional):
1096
+ Whether to run an additional “refine foreground” process on each frame.
1097
+ Defaults to False.
1098
+
1099
+ batch (int, optional):
1100
+ Number of frames to process at once (inference batch size). Large batch sizes
1101
+ may require more GPU memory. Defaults to 1.
1102
+
1103
+ print_frames_processed (bool, optional):
1104
+ If True (default), prints progress (how many frames have been processed) to
1105
+ the console.
1106
+
1107
+ webm (bool, optional):
1108
+ If True (default), exports a WebM video with alpha channel (VP9 / yuva420p).
1109
+ If False, exports an MP4 video composited over a solid color background.
1110
+
1111
+ rgb_value (tuple, optional):
1112
+ The RGB background color (e.g., green screen) used to composite frames when
1113
+ saving to MP4. Defaults to (0, 255, 0).
1114
+
1115
+ Returns:
1116
+ None. Writes the output video(s) to disk in the specified format.
1117
+ """
1118
+
1119
+
1120
+ cap = cv2.VideoCapture(video_path)
1121
+ if not cap.isOpened():
1122
+ raise IOError(f"Cannot open video: {video_path}")
1123
+
1124
+ original_fps = cap.get(cv2.CAP_PROP_FPS)
1125
+ original_fps = 30 if original_fps == 0 else original_fps
1126
+ fps = original_fps if fps == 0 else fps
1127
+
1128
+ ret, first_frame = cap.read()
1129
+ if not ret:
1130
+ raise ValueError("No frames found in the video.")
1131
+ height, width = first_frame.shape[:2]
1132
+ cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
1133
+
1134
+ foregrounds = []
1135
+ frame_idx = 0
1136
+ processed_count = 0
1137
+ batch_frames = []
1138
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
1139
+
1140
+ while True:
1141
+ ret, frame = cap.read()
1142
+ if not ret:
1143
+ if batch_frames:
1144
+ batch_results = self.inference(batch_frames, refine_foreground)
1145
+ if isinstance(batch_results, Image.Image):
1146
+ foregrounds.append(batch_results)
1147
+ else:
1148
+ foregrounds.extend(batch_results)
1149
+ if print_frames_processed:
1150
+ print(f"Processed frames {frame_idx-len(batch_frames)+1} to {frame_idx} of {total_frames}")
1151
+ break
1152
+
1153
+ # Process every frame instead of using intervals
1154
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
1155
+ pil_frame = Image.fromarray(frame_rgb)
1156
+ batch_frames.append(pil_frame)
1157
+
1158
+ if len(batch_frames) == batch:
1159
+ batch_results = self.inference(batch_frames, refine_foreground)
1160
+ if isinstance(batch_results, Image.Image):
1161
+ foregrounds.append(batch_results)
1162
+ else:
1163
+ foregrounds.extend(batch_results)
1164
+ if print_frames_processed:
1165
+ print(f"Processed frames {frame_idx-batch+1} to {frame_idx} of {total_frames}")
1166
+ batch_frames = []
1167
+ processed_count += batch
1168
+
1169
+ frame_idx += 1
1170
+
1171
+
1172
+ if webm:
1173
+ alpha_webm_path = os.path.join(output_path, "foreground.webm")
1174
+ pil_images_to_webm_alpha(foregrounds, alpha_webm_path, fps=original_fps)
1175
+
1176
+ else:
1177
+ cap.release()
1178
+ fg_output = os.path.join(output_path, 'foreground.mp4')
1179
+
1180
+ pil_images_to_mp4(foregrounds, fg_output, fps=original_fps,rgb_value=rgb_value)
1181
+ cv2.destroyAllWindows()
1182
+
1183
+ try:
1184
+ fg_audio_output = os.path.join(output_path, 'foreground_output_with_audio.mp4')
1185
+ add_audio_to_video(fg_output, video_path, fg_audio_output)
1186
+ except Exception as e:
1187
+ print("No audio found in the original video")
1188
+ print(e)
1189
+
1190
+
1191
+
1192
+
1193
+
1194
+ def rgb_loader_refiner( original_image):
1195
+ h, w = original_image.size
1196
+
1197
+ image = original_image
1198
+ # Convert to RGB if necessary
1199
+ if image.mode != 'RGB':
1200
+ image = image.convert('RGB')
1201
+
1202
+ # Resize the image
1203
+ image = image.resize((1024, 1024), resample=Image.LANCZOS)
1204
+
1205
+ return image.convert('RGB'), h, w,original_image
1206
+
1207
+ # Define the image transformation
1208
+ img_transform = transforms.Compose([
1209
+ transforms.ToTensor(),
1210
+ transforms.ConvertImageDtype(torch.float16),
1211
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
1212
+ ])
1213
+
1214
+ img_transform32 = transforms.Compose([
1215
+ transforms.ToTensor(),
1216
+ transforms.ConvertImageDtype(torch.float32),
1217
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
1218
+ ])
1219
+
1220
+
1221
+
1222
+
1223
+
1224
+ def pil_images_to_mp4(images, output_path, fps=24, rgb_value=(0, 255, 0)):
1225
+ """
1226
+ Converts an array of PIL images to an MP4 video.
1227
+
1228
+ Args:
1229
+ images: List of PIL images
1230
+ output_path: Path to save the MP4 file
1231
+ fps: Frames per second (default: 24)
1232
+ rgb_value: Background RGB color tuple (default: green (0, 255, 0))
1233
+ """
1234
+ if not images:
1235
+ raise ValueError("No images provided to convert to MP4.")
1236
+
1237
+ width, height = images[0].size
1238
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
1239
+ video_writer = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
1240
+
1241
+ for image in images:
1242
+ # If image has alpha channel, composite onto the specified background color
1243
+ if image.mode == 'RGBA':
1244
+ # Create background image with specified RGB color
1245
+ background = Image.new('RGB', image.size, rgb_value)
1246
+ background = background.convert('RGBA')
1247
+ # Composite the image onto the background
1248
+ image = Image.alpha_composite(background, image)
1249
+ image = image.convert('RGB')
1250
+ else:
1251
+ # Ensure RGB format for non-alpha images
1252
+ image = image.convert('RGB')
1253
+
1254
+ # Convert to OpenCV format and write
1255
+ open_cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
1256
+ video_writer.write(open_cv_image)
1257
+
1258
+ video_writer.release()
1259
+
1260
+ def pil_images_to_webm_alpha(images, output_path, fps=30):
1261
+ """
1262
+ Converts a list of PIL RGBA images to a VP9 .webm video with alpha channel.
1263
+
1264
+ NOTE: Not all players will display alpha in WebM.
1265
+ Browsers like Chrome/Firefox typically do support VP9 alpha.
1266
+ """
1267
+ if not images:
1268
+ raise ValueError("No images provided for WebM with alpha.")
1269
+
1270
+ # Ensure output directory exists
1271
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
1272
+
1273
+ with tempfile.TemporaryDirectory() as tmpdir:
1274
+ # Save frames as PNG (with alpha)
1275
+ for idx, img in enumerate(images):
1276
+ if img.mode != "RGBA":
1277
+ img = img.convert("RGBA")
1278
+ out_path = os.path.join(tmpdir, f"{idx:06d}.png")
1279
+ img.save(out_path, "PNG")
1280
+
1281
+ # Construct ffmpeg command
1282
+ # -c:v libvpx-vp9 => VP9 encoder
1283
+ # -pix_fmt yuva420p => alpha-enabled pixel format
1284
+ # -auto-alt-ref 0 => helps preserve alpha frames (libvpx quirk)
1285
+ ffmpeg_cmd = [
1286
+ "ffmpeg", "-y",
1287
+ "-framerate", str(fps),
1288
+ "-i", os.path.join(tmpdir, "%06d.png"),
1289
+ "-c:v", "libvpx-vp9",
1290
+ "-pix_fmt", "yuva420p",
1291
+ "-auto-alt-ref", "0",
1292
+ output_path
1293
+ ]
1294
+
1295
+ subprocess.run(ffmpeg_cmd, check=True)
1296
+
1297
+ print(f"WebM with alpha saved to {output_path}")
1298
+
1299
+ def add_audio_to_video(video_without_audio_path, original_video_path, output_path):
1300
+ """
1301
+ Check if the original video has an audio stream. If yes, add it. If not, skip.
1302
+ """
1303
+ # 1) Probe original video for audio streams
1304
+ probe_command = [
1305
+ 'ffprobe', '-v', 'error',
1306
+ '-select_streams', 'a:0',
1307
+ '-show_entries', 'stream=index',
1308
+ '-of', 'csv=p=0',
1309
+ original_video_path
1310
+ ]
1311
+ result = subprocess.run(probe_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
1312
+
1313
+ # result.stdout is empty if no audio stream found
1314
+ if not result.stdout.strip():
1315
+ print("No audio track found in original video, skipping audio addition.")
1316
+ return
1317
+
1318
+ print("Audio track detected; proceeding to mux audio.")
1319
+ # 2) If audio found, run ffmpeg to add it
1320
+ command = [
1321
+ 'ffmpeg', '-y',
1322
+ '-i', video_without_audio_path,
1323
+ '-i', original_video_path,
1324
+ '-c', 'copy',
1325
+ '-map', '0:v:0',
1326
+ '-map', '1:a:0', # we know there's an audio track now
1327
+ output_path
1328
+ ]
1329
+ subprocess.run(command, check=True)
1330
+ print(f"Audio added successfully => {output_path}")
1331
+
1332
+
1333
+
1334
+
1335
+
1336
+ ### Thanks to the source: https://huggingface.co/ZhengPeng7/BiRefNet/blob/main/handler.py
1337
+ def refine_foreground_process(image, mask, r=90):
1338
+ if mask.size != image.size:
1339
+ mask = mask.resize(image.size)
1340
+ image = np.array(image) / 255.0
1341
+ mask = np.array(mask) / 255.0
1342
+ estimated_foreground = FB_blur_fusion_foreground_estimator_2(image, mask, r=r)
1343
+ image_masked = Image.fromarray((estimated_foreground * 255.0).astype(np.uint8))
1344
+ return image_masked
1345
+
1346
+
1347
+ def FB_blur_fusion_foreground_estimator_2(image, alpha, r=90):
1348
+ # Thanks to the source: https://github.com/Photoroom/fast-foreground-estimation
1349
+ alpha = alpha[:, :, None]
1350
+ F, blur_B = FB_blur_fusion_foreground_estimator(image, image, image, alpha, r)
1351
+ return FB_blur_fusion_foreground_estimator(image, F, blur_B, alpha, r=6)[0]
1352
+
1353
+
1354
+ def FB_blur_fusion_foreground_estimator(image, F, B, alpha, r=90):
1355
+ if isinstance(image, Image.Image):
1356
+ image = np.array(image) / 255.0
1357
+ blurred_alpha = cv2.blur(alpha, (r, r))[:, :, None]
1358
+
1359
+ blurred_FA = cv2.blur(F * alpha, (r, r))
1360
+ blurred_F = blurred_FA / (blurred_alpha + 1e-5)
1361
+
1362
+ blurred_B1A = cv2.blur(B * (1 - alpha), (r, r))
1363
+ blurred_B = blurred_B1A / ((1 - blurred_alpha) + 1e-5)
1364
+ F = blurred_F + alpha * \
1365
+ (image - alpha * blurred_F - (1 - alpha) * blurred_B)
1366
+ F = np.clip(F, 0, 1)
1367
+ return F, blurred_B
1368
+
1369
+
1370
+
1371
+ def postprocess_image(result: torch.Tensor, im_size: list) -> np.ndarray:
1372
+ result = torch.squeeze(F.interpolate(result, size=im_size, mode='bilinear'), 0)
1373
+ ma = torch.max(result)
1374
+ mi = torch.min(result)
1375
+ result = (result - mi) / (ma - mi)
1376
+ im_array = (result * 255).permute(1, 2, 0).cpu().data.numpy().astype(np.uint8)
1377
+ im_array = np.squeeze(im_array)
1378
+ return im_array
1379
+
1380
+
1381
+
1382
+
1383
+ def rgb_loader_refiner( original_image):
1384
+ h, w = original_image.size
1385
+ # # Apply EXIF orientation
1386
+
1387
+ image = ImageOps.exif_transpose(original_image)
1388
+
1389
+ if original_image.mode != 'RGB':
1390
+ original_image = original_image.convert('RGB')
1391
+
1392
+ image = original_image
1393
+ # Convert to RGB if necessary
1394
+
1395
+ # Resize the image
1396
+ image = image.resize((1024, 1024), resample=Image.LANCZOS)
1397
+
1398
+ return image, h, w,original_image
1399
+
1400
+
1401
+
models/RMBG/BEN2/BEN2_Base.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:926144a876bda06f125555b4f5a239ece89dc6eb838a863700ca9bf192161a1c
3
+ size 1134584206
models/RMBG/BEN2/gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
models/RMBG/BiRefNet-HR/BiRefNet_config.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class BiRefNetConfig(PretrainedConfig):
4
+ model_type = "SegformerForSemanticSegmentation"
5
+ def __init__(
6
+ self,
7
+ bb_pretrained=False,
8
+ **kwargs
9
+ ):
10
+ self.bb_pretrained = bb_pretrained
11
+ super().__init__(**kwargs)
models/RMBG/BiRefNet-HR/birefnet.py ADDED
@@ -0,0 +1,2248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### config.py
2
+
3
+ import os
4
+ import math
5
+
6
+
7
+ class Config():
8
+ def __init__(self) -> None:
9
+ # PATH settings
10
+ self.sys_home_dir = os.path.expanduser('~') # Make up your file system as: SYS_HOME_DIR/codes/dis/BiRefNet, SYS_HOME_DIR/datasets/dis/xx, SYS_HOME_DIR/weights/xx
11
+
12
+ # TASK settings
13
+ self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0]
14
+ self.training_set = {
15
+ 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0],
16
+ 'COD': 'TR-COD10K+TR-CAMO',
17
+ 'HRSOD': ['TR-DUTS', 'TR-HRSOD', 'TR-UHRSD', 'TR-DUTS+TR-HRSOD', 'TR-DUTS+TR-UHRSD', 'TR-HRSOD+TR-UHRSD', 'TR-DUTS+TR-HRSOD+TR-UHRSD'][5],
18
+ 'DIS5K+HRSOD+HRS10K': 'DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4+DIS-TR+TE-HRS10K+TE-HRSOD+TE-UHRSD+TR-HRS10K+TR-HRSOD+TR-UHRSD', # leave DIS-VD for evaluation.
19
+ 'P3M-10k': 'TR-P3M-10k',
20
+ }[self.task]
21
+ self.prompt4loc = ['dense', 'sparse'][0]
22
+
23
+ # Faster-Training settings
24
+ self.load_all = True
25
+ self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch.
26
+ # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting.
27
+ # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607.
28
+ # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training.
29
+ self.precisionHigh = True
30
+
31
+ # MODEL settings
32
+ self.ms_supervision = True
33
+ self.out_ref = self.ms_supervision and True
34
+ self.dec_ipt = True
35
+ self.dec_ipt_split = True
36
+ self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder
37
+ self.mul_scl_ipt = ['', 'add', 'cat'][2]
38
+ self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2]
39
+ self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1]
40
+ self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]
41
+
42
+ # TRAINING settings
43
+ self.batch_size = 4
44
+ self.IoU_finetune_last_epochs = [
45
+ 0,
46
+ {
47
+ 'DIS5K': -50,
48
+ 'COD': -20,
49
+ 'HRSOD': -20,
50
+ 'DIS5K+HRSOD+HRS10K': -20,
51
+ 'P3M-10k': -20,
52
+ }[self.task]
53
+ ][1] # choose 0 to skip
54
+ self.lr = (1e-4 if 'DIS5K' in self.task else 1e-5) * math.sqrt(self.batch_size / 4) # DIS needs high lr to converge faster. Adapt the lr linearly
55
+ self.size = 1024
56
+ self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader
57
+
58
+ # Backbone settings
59
+ self.bb = [
60
+ 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2
61
+ 'swin_v1_t', 'swin_v1_s', # 3, 4
62
+ 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4
63
+ 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8
64
+ 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5
65
+ ][6]
66
+ self.lateral_channels_in_collection = {
67
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
68
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
69
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
70
+ 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96],
71
+ 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64],
72
+ }[self.bb]
73
+ if self.mul_scl_ipt == 'cat':
74
+ self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection]
75
+ self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
76
+
77
+ # MODEL settings - inactive
78
+ self.lat_blk = ['BasicLatBlk'][0]
79
+ self.dec_channels_inter = ['fixed', 'adap'][0]
80
+ self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0]
81
+ self.progressive_ref = self.refine and True
82
+ self.ender = self.progressive_ref and False
83
+ self.scale = self.progressive_ref and 2
84
+ self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`.
85
+ self.refine_iteration = 1
86
+ self.freeze_bb = False
87
+ self.model = [
88
+ 'BiRefNet',
89
+ ][0]
90
+ if self.dec_blk == 'HierarAttDecBlk':
91
+ self.batch_size = 2 ** [0, 1, 2, 3, 4][2]
92
+
93
+ # TRAINING settings - inactive
94
+ self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4]
95
+ self.optimizer = ['Adam', 'AdamW'][1]
96
+ self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch.
97
+ self.lr_decay_rate = 0.5
98
+ # Loss
99
+ self.lambdas_pix_last = {
100
+ # not 0 means opening this loss
101
+ # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30
102
+ 'bce': 30 * 1, # high performance
103
+ 'iou': 0.5 * 1, # 0 / 255
104
+ 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64)
105
+ 'mse': 150 * 0, # can smooth the saliency map
106
+ 'triplet': 3 * 0,
107
+ 'reg': 100 * 0,
108
+ 'ssim': 10 * 1, # help contours,
109
+ 'cnt': 5 * 0, # help contours
110
+ 'structure': 5 * 0, # structure loss from codes of MVANet. A little improvement on DIS-TE[1,2,3], a bit more decrease on DIS-TE4.
111
+ }
112
+ self.lambdas_cls = {
113
+ 'ce': 5.0
114
+ }
115
+ # Adv
116
+ self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training
117
+ self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)
118
+
119
+ # PATH settings - inactive
120
+ self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis')
121
+ self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights')
122
+ self.weights = {
123
+ 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'),
124
+ 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]),
125
+ 'swin_v1_b': os.path.join(self.weights_root_dir, ['swin_base_patch4_window12_384_22kto1k.pth', 'swin_base_patch4_window12_384_22k.pth'][0]),
126
+ 'swin_v1_l': os.path.join(self.weights_root_dir, ['swin_large_patch4_window12_384_22kto1k.pth', 'swin_large_patch4_window12_384_22k.pth'][0]),
127
+ 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]),
128
+ 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]),
129
+ 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]),
130
+ 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]),
131
+ }
132
+
133
+ # Callbacks - inactive
134
+ self.verbose_eval = True
135
+ self.only_S_MAE = False
136
+ self.use_fp16 = False # Bugs. It may cause nan in training.
137
+ self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs
138
+
139
+ # others
140
+ self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
141
+
142
+ self.batch_size_valid = 1
143
+ self.rand_seed = 7
144
+ # run_sh_file = [f for f in os.listdir('.') if 'train.sh' == f] + [os.path.join('..', f) for f in os.listdir('..') if 'train.sh' == f]
145
+ # with open(run_sh_file[0], 'r') as f:
146
+ # lines = f.readlines()
147
+ # self.save_last = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'val_last=' in l][0].split('val_last=')[-1].split()[0])
148
+ # self.save_step = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'step=' in l][0].split('step=')[-1].split()[0])
149
+ # self.val_step = [0, self.save_step][0]
150
+
151
+ def print_task(self) -> None:
152
+ # Return task for choosing settings in shell scripts.
153
+ print(self.task)
154
+
155
+
156
+
157
+ ### models/backbones/pvt_v2.py
158
+
159
+ import torch
160
+ import torch.nn as nn
161
+ from functools import partial
162
+
163
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
164
+ from timm.models.registry import register_model
165
+
166
+ import math
167
+
168
+ # from config import Config
169
+
170
+ # config = Config()
171
+
172
+ class Mlp(nn.Module):
173
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
174
+ super().__init__()
175
+ out_features = out_features or in_features
176
+ hidden_features = hidden_features or in_features
177
+ self.fc1 = nn.Linear(in_features, hidden_features)
178
+ self.dwconv = DWConv(hidden_features)
179
+ self.act = act_layer()
180
+ self.fc2 = nn.Linear(hidden_features, out_features)
181
+ self.drop = nn.Dropout(drop)
182
+
183
+ self.apply(self._init_weights)
184
+
185
+ def _init_weights(self, m):
186
+ if isinstance(m, nn.Linear):
187
+ trunc_normal_(m.weight, std=.02)
188
+ if isinstance(m, nn.Linear) and m.bias is not None:
189
+ nn.init.constant_(m.bias, 0)
190
+ elif isinstance(m, nn.LayerNorm):
191
+ nn.init.constant_(m.bias, 0)
192
+ nn.init.constant_(m.weight, 1.0)
193
+ elif isinstance(m, nn.Conv2d):
194
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
195
+ fan_out //= m.groups
196
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
197
+ if m.bias is not None:
198
+ m.bias.data.zero_()
199
+
200
+ def forward(self, x, H, W):
201
+ x = self.fc1(x)
202
+ x = self.dwconv(x, H, W)
203
+ x = self.act(x)
204
+ x = self.drop(x)
205
+ x = self.fc2(x)
206
+ x = self.drop(x)
207
+ return x
208
+
209
+
210
+ class Attention(nn.Module):
211
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
212
+ super().__init__()
213
+ assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
214
+
215
+ self.dim = dim
216
+ self.num_heads = num_heads
217
+ head_dim = dim // num_heads
218
+ self.scale = qk_scale or head_dim ** -0.5
219
+
220
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
221
+ self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
222
+ self.attn_drop_prob = attn_drop
223
+ self.attn_drop = nn.Dropout(attn_drop)
224
+ self.proj = nn.Linear(dim, dim)
225
+ self.proj_drop = nn.Dropout(proj_drop)
226
+
227
+ self.sr_ratio = sr_ratio
228
+ if sr_ratio > 1:
229
+ self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
230
+ self.norm = nn.LayerNorm(dim)
231
+
232
+ self.apply(self._init_weights)
233
+
234
+ def _init_weights(self, m):
235
+ if isinstance(m, nn.Linear):
236
+ trunc_normal_(m.weight, std=.02)
237
+ if isinstance(m, nn.Linear) and m.bias is not None:
238
+ nn.init.constant_(m.bias, 0)
239
+ elif isinstance(m, nn.LayerNorm):
240
+ nn.init.constant_(m.bias, 0)
241
+ nn.init.constant_(m.weight, 1.0)
242
+ elif isinstance(m, nn.Conv2d):
243
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
244
+ fan_out //= m.groups
245
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
246
+ if m.bias is not None:
247
+ m.bias.data.zero_()
248
+
249
+ def forward(self, x, H, W):
250
+ B, N, C = x.shape
251
+ q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
252
+
253
+ if self.sr_ratio > 1:
254
+ x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
255
+ x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
256
+ x_ = self.norm(x_)
257
+ kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
258
+ else:
259
+ kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
260
+ k, v = kv[0], kv[1]
261
+
262
+ if config.SDPA_enabled:
263
+ x = torch.nn.functional.scaled_dot_product_attention(
264
+ q, k, v,
265
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
266
+ ).transpose(1, 2).reshape(B, N, C)
267
+ else:
268
+ attn = (q @ k.transpose(-2, -1)) * self.scale
269
+ attn = attn.softmax(dim=-1)
270
+ attn = self.attn_drop(attn)
271
+
272
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
273
+ x = self.proj(x)
274
+ x = self.proj_drop(x)
275
+
276
+ return x
277
+
278
+
279
+ class Block(nn.Module):
280
+
281
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
282
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
283
+ super().__init__()
284
+ self.norm1 = norm_layer(dim)
285
+ self.attn = Attention(
286
+ dim,
287
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
288
+ attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
289
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
290
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
291
+ self.norm2 = norm_layer(dim)
292
+ mlp_hidden_dim = int(dim * mlp_ratio)
293
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
294
+
295
+ self.apply(self._init_weights)
296
+
297
+ def _init_weights(self, m):
298
+ if isinstance(m, nn.Linear):
299
+ trunc_normal_(m.weight, std=.02)
300
+ if isinstance(m, nn.Linear) and m.bias is not None:
301
+ nn.init.constant_(m.bias, 0)
302
+ elif isinstance(m, nn.LayerNorm):
303
+ nn.init.constant_(m.bias, 0)
304
+ nn.init.constant_(m.weight, 1.0)
305
+ elif isinstance(m, nn.Conv2d):
306
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
307
+ fan_out //= m.groups
308
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
309
+ if m.bias is not None:
310
+ m.bias.data.zero_()
311
+
312
+ def forward(self, x, H, W):
313
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
314
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
315
+
316
+ return x
317
+
318
+
319
+ class OverlapPatchEmbed(nn.Module):
320
+ """ Image to Patch Embedding
321
+ """
322
+
323
+ def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768):
324
+ super().__init__()
325
+ img_size = to_2tuple(img_size)
326
+ patch_size = to_2tuple(patch_size)
327
+
328
+ self.img_size = img_size
329
+ self.patch_size = patch_size
330
+ self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
331
+ self.num_patches = self.H * self.W
332
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride,
333
+ padding=(patch_size[0] // 2, patch_size[1] // 2))
334
+ self.norm = nn.LayerNorm(embed_dim)
335
+
336
+ self.apply(self._init_weights)
337
+
338
+ def _init_weights(self, m):
339
+ if isinstance(m, nn.Linear):
340
+ trunc_normal_(m.weight, std=.02)
341
+ if isinstance(m, nn.Linear) and m.bias is not None:
342
+ nn.init.constant_(m.bias, 0)
343
+ elif isinstance(m, nn.LayerNorm):
344
+ nn.init.constant_(m.bias, 0)
345
+ nn.init.constant_(m.weight, 1.0)
346
+ elif isinstance(m, nn.Conv2d):
347
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
348
+ fan_out //= m.groups
349
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
350
+ if m.bias is not None:
351
+ m.bias.data.zero_()
352
+
353
+ def forward(self, x):
354
+ x = self.proj(x)
355
+ _, _, H, W = x.shape
356
+ x = x.flatten(2).transpose(1, 2)
357
+ x = self.norm(x)
358
+
359
+ return x, H, W
360
+
361
+
362
+ class PyramidVisionTransformerImpr(nn.Module):
363
+ def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
364
+ num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
365
+ attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
366
+ depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
367
+ super().__init__()
368
+ self.num_classes = num_classes
369
+ self.depths = depths
370
+
371
+ # patch_embed
372
+ self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels,
373
+ embed_dim=embed_dims[0])
374
+ self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0],
375
+ embed_dim=embed_dims[1])
376
+ self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1],
377
+ embed_dim=embed_dims[2])
378
+ self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2],
379
+ embed_dim=embed_dims[3])
380
+
381
+ # transformer encoder
382
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
383
+ cur = 0
384
+ self.block1 = nn.ModuleList([Block(
385
+ dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
386
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
387
+ sr_ratio=sr_ratios[0])
388
+ for i in range(depths[0])])
389
+ self.norm1 = norm_layer(embed_dims[0])
390
+
391
+ cur += depths[0]
392
+ self.block2 = nn.ModuleList([Block(
393
+ dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
394
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
395
+ sr_ratio=sr_ratios[1])
396
+ for i in range(depths[1])])
397
+ self.norm2 = norm_layer(embed_dims[1])
398
+
399
+ cur += depths[1]
400
+ self.block3 = nn.ModuleList([Block(
401
+ dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
402
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
403
+ sr_ratio=sr_ratios[2])
404
+ for i in range(depths[2])])
405
+ self.norm3 = norm_layer(embed_dims[2])
406
+
407
+ cur += depths[2]
408
+ self.block4 = nn.ModuleList([Block(
409
+ dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
410
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
411
+ sr_ratio=sr_ratios[3])
412
+ for i in range(depths[3])])
413
+ self.norm4 = norm_layer(embed_dims[3])
414
+
415
+ # classification head
416
+ # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
417
+
418
+ self.apply(self._init_weights)
419
+
420
+ def _init_weights(self, m):
421
+ if isinstance(m, nn.Linear):
422
+ trunc_normal_(m.weight, std=.02)
423
+ if isinstance(m, nn.Linear) and m.bias is not None:
424
+ nn.init.constant_(m.bias, 0)
425
+ elif isinstance(m, nn.LayerNorm):
426
+ nn.init.constant_(m.bias, 0)
427
+ nn.init.constant_(m.weight, 1.0)
428
+ elif isinstance(m, nn.Conv2d):
429
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
430
+ fan_out //= m.groups
431
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
432
+ if m.bias is not None:
433
+ m.bias.data.zero_()
434
+
435
+ def init_weights(self, pretrained=None):
436
+ if isinstance(pretrained, str):
437
+ logger = 1
438
+ #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
439
+
440
+ def reset_drop_path(self, drop_path_rate):
441
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
442
+ cur = 0
443
+ for i in range(self.depths[0]):
444
+ self.block1[i].drop_path.drop_prob = dpr[cur + i]
445
+
446
+ cur += self.depths[0]
447
+ for i in range(self.depths[1]):
448
+ self.block2[i].drop_path.drop_prob = dpr[cur + i]
449
+
450
+ cur += self.depths[1]
451
+ for i in range(self.depths[2]):
452
+ self.block3[i].drop_path.drop_prob = dpr[cur + i]
453
+
454
+ cur += self.depths[2]
455
+ for i in range(self.depths[3]):
456
+ self.block4[i].drop_path.drop_prob = dpr[cur + i]
457
+
458
+ def freeze_patch_emb(self):
459
+ self.patch_embed1.requires_grad = False
460
+
461
+ @torch.jit.ignore
462
+ def no_weight_decay(self):
463
+ return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
464
+
465
+ def get_classifier(self):
466
+ return self.head
467
+
468
+ def reset_classifier(self, num_classes, global_pool=''):
469
+ self.num_classes = num_classes
470
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
471
+
472
+ def forward_features(self, x):
473
+ B = x.shape[0]
474
+ outs = []
475
+
476
+ # stage 1
477
+ x, H, W = self.patch_embed1(x)
478
+ for i, blk in enumerate(self.block1):
479
+ x = blk(x, H, W)
480
+ x = self.norm1(x)
481
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
482
+ outs.append(x)
483
+
484
+ # stage 2
485
+ x, H, W = self.patch_embed2(x)
486
+ for i, blk in enumerate(self.block2):
487
+ x = blk(x, H, W)
488
+ x = self.norm2(x)
489
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
490
+ outs.append(x)
491
+
492
+ # stage 3
493
+ x, H, W = self.patch_embed3(x)
494
+ for i, blk in enumerate(self.block3):
495
+ x = blk(x, H, W)
496
+ x = self.norm3(x)
497
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
498
+ outs.append(x)
499
+
500
+ # stage 4
501
+ x, H, W = self.patch_embed4(x)
502
+ for i, blk in enumerate(self.block4):
503
+ x = blk(x, H, W)
504
+ x = self.norm4(x)
505
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
506
+ outs.append(x)
507
+
508
+ return outs
509
+
510
+ # return x.mean(dim=1)
511
+
512
+ def forward(self, x):
513
+ x = self.forward_features(x)
514
+ # x = self.head(x)
515
+
516
+ return x
517
+
518
+
519
+ class DWConv(nn.Module):
520
+ def __init__(self, dim=768):
521
+ super(DWConv, self).__init__()
522
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
523
+
524
+ def forward(self, x, H, W):
525
+ B, N, C = x.shape
526
+ x = x.transpose(1, 2).view(B, C, H, W).contiguous()
527
+ x = self.dwconv(x)
528
+ x = x.flatten(2).transpose(1, 2)
529
+
530
+ return x
531
+
532
+
533
+ def _conv_filter(state_dict, patch_size=16):
534
+ """ convert patch embedding weight from manual patchify + linear proj to conv"""
535
+ out_dict = {}
536
+ for k, v in state_dict.items():
537
+ if 'patch_embed.proj.weight' in k:
538
+ v = v.reshape((v.shape[0], 3, patch_size, patch_size))
539
+ out_dict[k] = v
540
+
541
+ return out_dict
542
+
543
+
544
+ ## @register_model
545
+ class pvt_v2_b0(PyramidVisionTransformerImpr):
546
+ def __init__(self, **kwargs):
547
+ super(pvt_v2_b0, self).__init__(
548
+ patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
549
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
550
+ drop_rate=0.0, drop_path_rate=0.1)
551
+
552
+
553
+
554
+ ## @register_model
555
+ class pvt_v2_b1(PyramidVisionTransformerImpr):
556
+ def __init__(self, **kwargs):
557
+ super(pvt_v2_b1, self).__init__(
558
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
559
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
560
+ drop_rate=0.0, drop_path_rate=0.1)
561
+
562
+ ## @register_model
563
+ class pvt_v2_b2(PyramidVisionTransformerImpr):
564
+ def __init__(self, in_channels=3, **kwargs):
565
+ super(pvt_v2_b2, self).__init__(
566
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
567
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],
568
+ drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
569
+
570
+ ## @register_model
571
+ class pvt_v2_b3(PyramidVisionTransformerImpr):
572
+ def __init__(self, **kwargs):
573
+ super(pvt_v2_b3, self).__init__(
574
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
575
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
576
+ drop_rate=0.0, drop_path_rate=0.1)
577
+
578
+ ## @register_model
579
+ class pvt_v2_b4(PyramidVisionTransformerImpr):
580
+ def __init__(self, **kwargs):
581
+ super(pvt_v2_b4, self).__init__(
582
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
583
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],
584
+ drop_rate=0.0, drop_path_rate=0.1)
585
+
586
+
587
+ ## @register_model
588
+ class pvt_v2_b5(PyramidVisionTransformerImpr):
589
+ def __init__(self, **kwargs):
590
+ super(pvt_v2_b5, self).__init__(
591
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
592
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
593
+ drop_rate=0.0, drop_path_rate=0.1)
594
+
595
+
596
+
597
+ ### models/backbones/swin_v1.py
598
+
599
+ # --------------------------------------------------------
600
+ # Swin Transformer
601
+ # Copyright (c) 2021 Microsoft
602
+ # Licensed under The MIT License [see LICENSE for details]
603
+ # Written by Ze Liu, Yutong Lin, Yixuan Wei
604
+ # --------------------------------------------------------
605
+
606
+ import torch
607
+ import torch.nn as nn
608
+ import torch.nn.functional as F
609
+ import torch.utils.checkpoint as checkpoint
610
+ import numpy as np
611
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
612
+
613
+ # from config import Config
614
+
615
+
616
+ # config = Config()
617
+
618
+
619
+ class Mlp(nn.Module):
620
+ """ Multilayer perceptron."""
621
+
622
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
623
+ super().__init__()
624
+ out_features = out_features or in_features
625
+ hidden_features = hidden_features or in_features
626
+ self.fc1 = nn.Linear(in_features, hidden_features)
627
+ self.act = act_layer()
628
+ self.fc2 = nn.Linear(hidden_features, out_features)
629
+ self.drop = nn.Dropout(drop)
630
+
631
+ def forward(self, x):
632
+ x = self.fc1(x)
633
+ x = self.act(x)
634
+ x = self.drop(x)
635
+ x = self.fc2(x)
636
+ x = self.drop(x)
637
+ return x
638
+
639
+
640
+ def window_partition(x, window_size):
641
+ """
642
+ Args:
643
+ x: (B, H, W, C)
644
+ window_size (int): window size
645
+
646
+ Returns:
647
+ windows: (num_windows*B, window_size, window_size, C)
648
+ """
649
+ B, H, W, C = x.shape
650
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
651
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
652
+ return windows
653
+
654
+
655
+ def window_reverse(windows, window_size, H, W):
656
+ """
657
+ Args:
658
+ windows: (num_windows*B, window_size, window_size, C)
659
+ window_size (int): Window size
660
+ H (int): Height of image
661
+ W (int): Width of image
662
+
663
+ Returns:
664
+ x: (B, H, W, C)
665
+ """
666
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
667
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
668
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
669
+ return x
670
+
671
+
672
+ class WindowAttention(nn.Module):
673
+ """ Window based multi-head self attention (W-MSA) module with relative position bias.
674
+ It supports both of shifted and non-shifted window.
675
+
676
+ Args:
677
+ dim (int): Number of input channels.
678
+ window_size (tuple[int]): The height and width of the window.
679
+ num_heads (int): Number of attention heads.
680
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
681
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
682
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
683
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
684
+ """
685
+
686
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
687
+
688
+ super().__init__()
689
+ self.dim = dim
690
+ self.window_size = window_size # Wh, Ww
691
+ self.num_heads = num_heads
692
+ head_dim = dim // num_heads
693
+ self.scale = qk_scale or head_dim ** -0.5
694
+
695
+ # define a parameter table of relative position bias
696
+ self.relative_position_bias_table = nn.Parameter(
697
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
698
+
699
+ # get pair-wise relative position index for each token inside the window
700
+ coords_h = torch.arange(self.window_size[0])
701
+ coords_w = torch.arange(self.window_size[1])
702
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww
703
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
704
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
705
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
706
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
707
+ relative_coords[:, :, 1] += self.window_size[1] - 1
708
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
709
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
710
+ self.register_buffer("relative_position_index", relative_position_index)
711
+
712
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
713
+ self.attn_drop_prob = attn_drop
714
+ self.attn_drop = nn.Dropout(attn_drop)
715
+ self.proj = nn.Linear(dim, dim)
716
+ self.proj_drop = nn.Dropout(proj_drop)
717
+
718
+ trunc_normal_(self.relative_position_bias_table, std=.02)
719
+ self.softmax = nn.Softmax(dim=-1)
720
+
721
+ def forward(self, x, mask=None):
722
+ """ Forward function.
723
+
724
+ Args:
725
+ x: input features with shape of (num_windows*B, N, C)
726
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
727
+ """
728
+ B_, N, C = x.shape
729
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
730
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
731
+
732
+ q = q * self.scale
733
+
734
+ if config.SDPA_enabled:
735
+ x = torch.nn.functional.scaled_dot_product_attention(
736
+ q, k, v,
737
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
738
+ ).transpose(1, 2).reshape(B_, N, C)
739
+ else:
740
+ attn = (q @ k.transpose(-2, -1))
741
+
742
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
743
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
744
+ ) # Wh*Ww, Wh*Ww, nH
745
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
746
+ attn = attn + relative_position_bias.unsqueeze(0)
747
+
748
+ if mask is not None:
749
+ nW = mask.shape[0]
750
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
751
+ attn = attn.view(-1, self.num_heads, N, N)
752
+ attn = self.softmax(attn)
753
+ else:
754
+ attn = self.softmax(attn)
755
+
756
+ attn = self.attn_drop(attn)
757
+
758
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
759
+ x = self.proj(x)
760
+ x = self.proj_drop(x)
761
+ return x
762
+
763
+
764
+ class SwinTransformerBlock(nn.Module):
765
+ """ Swin Transformer Block.
766
+
767
+ Args:
768
+ dim (int): Number of input channels.
769
+ num_heads (int): Number of attention heads.
770
+ window_size (int): Window size.
771
+ shift_size (int): Shift size for SW-MSA.
772
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
773
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
774
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
775
+ drop (float, optional): Dropout rate. Default: 0.0
776
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
777
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
778
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
779
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
780
+ """
781
+
782
+ def __init__(self, dim, num_heads, window_size=7, shift_size=0,
783
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
784
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
785
+ super().__init__()
786
+ self.dim = dim
787
+ self.num_heads = num_heads
788
+ self.window_size = window_size
789
+ self.shift_size = shift_size
790
+ self.mlp_ratio = mlp_ratio
791
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
792
+
793
+ self.norm1 = norm_layer(dim)
794
+ self.attn = WindowAttention(
795
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
796
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
797
+
798
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
799
+ self.norm2 = norm_layer(dim)
800
+ mlp_hidden_dim = int(dim * mlp_ratio)
801
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
802
+
803
+ self.H = None
804
+ self.W = None
805
+
806
+ def forward(self, x, mask_matrix):
807
+ """ Forward function.
808
+
809
+ Args:
810
+ x: Input feature, tensor size (B, H*W, C).
811
+ H, W: Spatial resolution of the input feature.
812
+ mask_matrix: Attention mask for cyclic shift.
813
+ """
814
+ B, L, C = x.shape
815
+ H, W = self.H, self.W
816
+ assert L == H * W, "input feature has wrong size"
817
+
818
+ shortcut = x
819
+ x = self.norm1(x)
820
+ x = x.view(B, H, W, C)
821
+
822
+ # pad feature maps to multiples of window size
823
+ pad_l = pad_t = 0
824
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
825
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
826
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
827
+ _, Hp, Wp, _ = x.shape
828
+
829
+ # cyclic shift
830
+ if self.shift_size > 0:
831
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
832
+ attn_mask = mask_matrix
833
+ else:
834
+ shifted_x = x
835
+ attn_mask = None
836
+
837
+ # partition windows
838
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
839
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
840
+
841
+ # W-MSA/SW-MSA
842
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
843
+
844
+ # merge windows
845
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
846
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
847
+
848
+ # reverse cyclic shift
849
+ if self.shift_size > 0:
850
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
851
+ else:
852
+ x = shifted_x
853
+
854
+ if pad_r > 0 or pad_b > 0:
855
+ x = x[:, :H, :W, :].contiguous()
856
+
857
+ x = x.view(B, H * W, C)
858
+
859
+ # FFN
860
+ x = shortcut + self.drop_path(x)
861
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
862
+
863
+ return x
864
+
865
+
866
+ class PatchMerging(nn.Module):
867
+ """ Patch Merging Layer
868
+
869
+ Args:
870
+ dim (int): Number of input channels.
871
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
872
+ """
873
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
874
+ super().__init__()
875
+ self.dim = dim
876
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
877
+ self.norm = norm_layer(4 * dim)
878
+
879
+ def forward(self, x, H, W):
880
+ """ Forward function.
881
+
882
+ Args:
883
+ x: Input feature, tensor size (B, H*W, C).
884
+ H, W: Spatial resolution of the input feature.
885
+ """
886
+ B, L, C = x.shape
887
+ assert L == H * W, "input feature has wrong size"
888
+
889
+ x = x.view(B, H, W, C)
890
+
891
+ # padding
892
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
893
+ if pad_input:
894
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
895
+
896
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
897
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
898
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
899
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
900
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
901
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
902
+
903
+ x = self.norm(x)
904
+ x = self.reduction(x)
905
+
906
+ return x
907
+
908
+
909
+ class BasicLayer(nn.Module):
910
+ """ A basic Swin Transformer layer for one stage.
911
+
912
+ Args:
913
+ dim (int): Number of feature channels
914
+ depth (int): Depths of this stage.
915
+ num_heads (int): Number of attention head.
916
+ window_size (int): Local window size. Default: 7.
917
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
918
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
919
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
920
+ drop (float, optional): Dropout rate. Default: 0.0
921
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
922
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
923
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
924
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
925
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
926
+ """
927
+
928
+ def __init__(self,
929
+ dim,
930
+ depth,
931
+ num_heads,
932
+ window_size=7,
933
+ mlp_ratio=4.,
934
+ qkv_bias=True,
935
+ qk_scale=None,
936
+ drop=0.,
937
+ attn_drop=0.,
938
+ drop_path=0.,
939
+ norm_layer=nn.LayerNorm,
940
+ downsample=None,
941
+ use_checkpoint=False):
942
+ super().__init__()
943
+ self.window_size = window_size
944
+ self.shift_size = window_size // 2
945
+ self.depth = depth
946
+ self.use_checkpoint = use_checkpoint
947
+
948
+ # build blocks
949
+ self.blocks = nn.ModuleList([
950
+ SwinTransformerBlock(
951
+ dim=dim,
952
+ num_heads=num_heads,
953
+ window_size=window_size,
954
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
955
+ mlp_ratio=mlp_ratio,
956
+ qkv_bias=qkv_bias,
957
+ qk_scale=qk_scale,
958
+ drop=drop,
959
+ attn_drop=attn_drop,
960
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
961
+ norm_layer=norm_layer)
962
+ for i in range(depth)])
963
+
964
+ # patch merging layer
965
+ if downsample is not None:
966
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
967
+ else:
968
+ self.downsample = None
969
+
970
+ def forward(self, x, H, W):
971
+ """ Forward function.
972
+
973
+ Args:
974
+ x: Input feature, tensor size (B, H*W, C).
975
+ H, W: Spatial resolution of the input feature.
976
+ """
977
+
978
+ # calculate attention mask for SW-MSA
979
+ # Turn int to torch.tensor for the compatiability with torch.compile in PyTorch 2.5.
980
+ Hp = torch.ceil(torch.tensor(H) / self.window_size).to(torch.int64) * self.window_size
981
+ Wp = torch.ceil(torch.tensor(W) / self.window_size).to(torch.int64) * self.window_size
982
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
983
+ h_slices = (slice(0, -self.window_size),
984
+ slice(-self.window_size, -self.shift_size),
985
+ slice(-self.shift_size, None))
986
+ w_slices = (slice(0, -self.window_size),
987
+ slice(-self.window_size, -self.shift_size),
988
+ slice(-self.shift_size, None))
989
+ cnt = 0
990
+ for h in h_slices:
991
+ for w in w_slices:
992
+ img_mask[:, h, w, :] = cnt
993
+ cnt += 1
994
+
995
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
996
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
997
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
998
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)).to(x.dtype)
999
+
1000
+ for blk in self.blocks:
1001
+ blk.H, blk.W = H, W
1002
+ if self.use_checkpoint:
1003
+ x = checkpoint.checkpoint(blk, x, attn_mask)
1004
+ else:
1005
+ x = blk(x, attn_mask)
1006
+ if self.downsample is not None:
1007
+ x_down = self.downsample(x, H, W)
1008
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
1009
+ return x, H, W, x_down, Wh, Ww
1010
+ else:
1011
+ return x, H, W, x, H, W
1012
+
1013
+
1014
+ class PatchEmbed(nn.Module):
1015
+ """ Image to Patch Embedding
1016
+
1017
+ Args:
1018
+ patch_size (int): Patch token size. Default: 4.
1019
+ in_channels (int): Number of input image channels. Default: 3.
1020
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1021
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
1022
+ """
1023
+
1024
+ def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None):
1025
+ super().__init__()
1026
+ patch_size = to_2tuple(patch_size)
1027
+ self.patch_size = patch_size
1028
+
1029
+ self.in_channels = in_channels
1030
+ self.embed_dim = embed_dim
1031
+
1032
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
1033
+ if norm_layer is not None:
1034
+ self.norm = norm_layer(embed_dim)
1035
+ else:
1036
+ self.norm = None
1037
+
1038
+ def forward(self, x):
1039
+ """Forward function."""
1040
+ # padding
1041
+ _, _, H, W = x.size()
1042
+ if W % self.patch_size[1] != 0:
1043
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
1044
+ if H % self.patch_size[0] != 0:
1045
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
1046
+
1047
+ x = self.proj(x) # B C Wh Ww
1048
+ if self.norm is not None:
1049
+ Wh, Ww = x.size(2), x.size(3)
1050
+ x = x.flatten(2).transpose(1, 2)
1051
+ x = self.norm(x)
1052
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
1053
+
1054
+ return x
1055
+
1056
+
1057
+ class SwinTransformer(nn.Module):
1058
+ """ Swin Transformer backbone.
1059
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
1060
+ https://arxiv.org/pdf/2103.14030
1061
+
1062
+ Args:
1063
+ pretrain_img_size (int): Input image size for training the pretrained model,
1064
+ used in absolute postion embedding. Default 224.
1065
+ patch_size (int | tuple(int)): Patch size. Default: 4.
1066
+ in_channels (int): Number of input image channels. Default: 3.
1067
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1068
+ depths (tuple[int]): Depths of each Swin Transformer stage.
1069
+ num_heads (tuple[int]): Number of attention head of each stage.
1070
+ window_size (int): Window size. Default: 7.
1071
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
1072
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
1073
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
1074
+ drop_rate (float): Dropout rate.
1075
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
1076
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
1077
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
1078
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
1079
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
1080
+ out_indices (Sequence[int]): Output from which stages.
1081
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
1082
+ -1 means not freezing any parameters.
1083
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
1084
+ """
1085
+
1086
+ def __init__(self,
1087
+ pretrain_img_size=224,
1088
+ patch_size=4,
1089
+ in_channels=3,
1090
+ embed_dim=96,
1091
+ depths=[2, 2, 6, 2],
1092
+ num_heads=[3, 6, 12, 24],
1093
+ window_size=7,
1094
+ mlp_ratio=4.,
1095
+ qkv_bias=True,
1096
+ qk_scale=None,
1097
+ drop_rate=0.,
1098
+ attn_drop_rate=0.,
1099
+ drop_path_rate=0.2,
1100
+ norm_layer=nn.LayerNorm,
1101
+ ape=False,
1102
+ patch_norm=True,
1103
+ out_indices=(0, 1, 2, 3),
1104
+ frozen_stages=-1,
1105
+ use_checkpoint=False):
1106
+ super().__init__()
1107
+
1108
+ self.pretrain_img_size = pretrain_img_size
1109
+ self.num_layers = len(depths)
1110
+ self.embed_dim = embed_dim
1111
+ self.ape = ape
1112
+ self.patch_norm = patch_norm
1113
+ self.out_indices = out_indices
1114
+ self.frozen_stages = frozen_stages
1115
+
1116
+ # split image into non-overlapping patches
1117
+ self.patch_embed = PatchEmbed(
1118
+ patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim,
1119
+ norm_layer=norm_layer if self.patch_norm else None)
1120
+
1121
+ # absolute position embedding
1122
+ if self.ape:
1123
+ pretrain_img_size = to_2tuple(pretrain_img_size)
1124
+ patch_size = to_2tuple(patch_size)
1125
+ patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
1126
+
1127
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
1128
+ trunc_normal_(self.absolute_pos_embed, std=.02)
1129
+
1130
+ self.pos_drop = nn.Dropout(p=drop_rate)
1131
+
1132
+ # stochastic depth
1133
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
1134
+
1135
+ # build layers
1136
+ self.layers = nn.ModuleList()
1137
+ for i_layer in range(self.num_layers):
1138
+ layer = BasicLayer(
1139
+ dim=int(embed_dim * 2 ** i_layer),
1140
+ depth=depths[i_layer],
1141
+ num_heads=num_heads[i_layer],
1142
+ window_size=window_size,
1143
+ mlp_ratio=mlp_ratio,
1144
+ qkv_bias=qkv_bias,
1145
+ qk_scale=qk_scale,
1146
+ drop=drop_rate,
1147
+ attn_drop=attn_drop_rate,
1148
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
1149
+ norm_layer=norm_layer,
1150
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
1151
+ use_checkpoint=use_checkpoint)
1152
+ self.layers.append(layer)
1153
+
1154
+ num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
1155
+ self.num_features = num_features
1156
+
1157
+ # add a norm layer for each output
1158
+ for i_layer in out_indices:
1159
+ layer = norm_layer(num_features[i_layer])
1160
+ layer_name = f'norm{i_layer}'
1161
+ self.add_module(layer_name, layer)
1162
+
1163
+ self._freeze_stages()
1164
+
1165
+ def _freeze_stages(self):
1166
+ if self.frozen_stages >= 0:
1167
+ self.patch_embed.eval()
1168
+ for param in self.patch_embed.parameters():
1169
+ param.requires_grad = False
1170
+
1171
+ if self.frozen_stages >= 1 and self.ape:
1172
+ self.absolute_pos_embed.requires_grad = False
1173
+
1174
+ if self.frozen_stages >= 2:
1175
+ self.pos_drop.eval()
1176
+ for i in range(0, self.frozen_stages - 1):
1177
+ m = self.layers[i]
1178
+ m.eval()
1179
+ for param in m.parameters():
1180
+ param.requires_grad = False
1181
+
1182
+
1183
+ def forward(self, x):
1184
+ """Forward function."""
1185
+ x = self.patch_embed(x)
1186
+
1187
+ Wh, Ww = x.size(2), x.size(3)
1188
+ if self.ape:
1189
+ # interpolate the position embedding to the corresponding size
1190
+ absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
1191
+ x = (x + absolute_pos_embed) # B Wh*Ww C
1192
+
1193
+ outs = []#x.contiguous()]
1194
+ x = x.flatten(2).transpose(1, 2)
1195
+ x = self.pos_drop(x)
1196
+ for i in range(self.num_layers):
1197
+ layer = self.layers[i]
1198
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
1199
+
1200
+ if i in self.out_indices:
1201
+ norm_layer = getattr(self, f'norm{i}')
1202
+ x_out = norm_layer(x_out)
1203
+
1204
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
1205
+ outs.append(out)
1206
+
1207
+ return tuple(outs)
1208
+
1209
+ def train(self, mode=True):
1210
+ """Convert the model into training mode while keep layers freezed."""
1211
+ super(SwinTransformer, self).train(mode)
1212
+ self._freeze_stages()
1213
+
1214
+ def swin_v1_t():
1215
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7)
1216
+ return model
1217
+
1218
+ def swin_v1_s():
1219
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7)
1220
+ return model
1221
+
1222
+ def swin_v1_b():
1223
+ model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
1224
+ return model
1225
+
1226
+ def swin_v1_l():
1227
+ model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12)
1228
+ return model
1229
+
1230
+
1231
+
1232
+ ### models/modules/deform_conv.py
1233
+
1234
+ import torch
1235
+ import torch.nn as nn
1236
+ from torchvision.ops import deform_conv2d
1237
+
1238
+
1239
+ class DeformableConv2d(nn.Module):
1240
+ def __init__(self,
1241
+ in_channels,
1242
+ out_channels,
1243
+ kernel_size=3,
1244
+ stride=1,
1245
+ padding=1,
1246
+ bias=False):
1247
+
1248
+ super(DeformableConv2d, self).__init__()
1249
+
1250
+ assert type(kernel_size) == tuple or type(kernel_size) == int
1251
+
1252
+ kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size)
1253
+ self.stride = stride if type(stride) == tuple else (stride, stride)
1254
+ self.padding = padding
1255
+
1256
+ self.offset_conv = nn.Conv2d(in_channels,
1257
+ 2 * kernel_size[0] * kernel_size[1],
1258
+ kernel_size=kernel_size,
1259
+ stride=stride,
1260
+ padding=self.padding,
1261
+ bias=True)
1262
+
1263
+ nn.init.constant_(self.offset_conv.weight, 0.)
1264
+ nn.init.constant_(self.offset_conv.bias, 0.)
1265
+
1266
+ self.modulator_conv = nn.Conv2d(in_channels,
1267
+ 1 * kernel_size[0] * kernel_size[1],
1268
+ kernel_size=kernel_size,
1269
+ stride=stride,
1270
+ padding=self.padding,
1271
+ bias=True)
1272
+
1273
+ nn.init.constant_(self.modulator_conv.weight, 0.)
1274
+ nn.init.constant_(self.modulator_conv.bias, 0.)
1275
+
1276
+ self.regular_conv = nn.Conv2d(in_channels,
1277
+ out_channels=out_channels,
1278
+ kernel_size=kernel_size,
1279
+ stride=stride,
1280
+ padding=self.padding,
1281
+ bias=bias)
1282
+
1283
+ def forward(self, x):
1284
+ #h, w = x.shape[2:]
1285
+ #max_offset = max(h, w)/4.
1286
+
1287
+ offset = self.offset_conv(x)#.clamp(-max_offset, max_offset)
1288
+ modulator = 2. * torch.sigmoid(self.modulator_conv(x))
1289
+
1290
+ x = deform_conv2d(
1291
+ input=x,
1292
+ offset=offset,
1293
+ weight=self.regular_conv.weight,
1294
+ bias=self.regular_conv.bias,
1295
+ padding=self.padding,
1296
+ mask=modulator,
1297
+ stride=self.stride,
1298
+ )
1299
+ return x
1300
+
1301
+
1302
+
1303
+
1304
+ ### utils.py
1305
+
1306
+ import torch.nn as nn
1307
+
1308
+
1309
+ def build_act_layer(act_layer):
1310
+ if act_layer == 'ReLU':
1311
+ return nn.ReLU(inplace=True)
1312
+ elif act_layer == 'SiLU':
1313
+ return nn.SiLU(inplace=True)
1314
+ elif act_layer == 'GELU':
1315
+ return nn.GELU()
1316
+
1317
+ raise NotImplementedError(f'build_act_layer does not support {act_layer}')
1318
+
1319
+
1320
+ def build_norm_layer(dim,
1321
+ norm_layer,
1322
+ in_format='channels_last',
1323
+ out_format='channels_last',
1324
+ eps=1e-6):
1325
+ layers = []
1326
+ if norm_layer == 'BN':
1327
+ if in_format == 'channels_last':
1328
+ layers.append(to_channels_first())
1329
+ layers.append(nn.BatchNorm2d(dim))
1330
+ if out_format == 'channels_last':
1331
+ layers.append(to_channels_last())
1332
+ elif norm_layer == 'LN':
1333
+ if in_format == 'channels_first':
1334
+ layers.append(to_channels_last())
1335
+ layers.append(nn.LayerNorm(dim, eps=eps))
1336
+ if out_format == 'channels_first':
1337
+ layers.append(to_channels_first())
1338
+ else:
1339
+ raise NotImplementedError(
1340
+ f'build_norm_layer does not support {norm_layer}')
1341
+ return nn.Sequential(*layers)
1342
+
1343
+
1344
+ class to_channels_first(nn.Module):
1345
+
1346
+ def __init__(self):
1347
+ super().__init__()
1348
+
1349
+ def forward(self, x):
1350
+ return x.permute(0, 3, 1, 2)
1351
+
1352
+
1353
+ class to_channels_last(nn.Module):
1354
+
1355
+ def __init__(self):
1356
+ super().__init__()
1357
+
1358
+ def forward(self, x):
1359
+ return x.permute(0, 2, 3, 1)
1360
+
1361
+
1362
+
1363
+ ### dataset.py
1364
+
1365
+ _class_labels_TR_sorted = (
1366
+ 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, '
1367
+ 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, '
1368
+ 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, '
1369
+ 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, '
1370
+ 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, '
1371
+ 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, '
1372
+ 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, '
1373
+ 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, '
1374
+ 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, '
1375
+ 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, '
1376
+ 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, '
1377
+ 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, '
1378
+ 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, '
1379
+ 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht'
1380
+ )
1381
+ class_labels_TR_sorted = _class_labels_TR_sorted.split(', ')
1382
+
1383
+
1384
+ ### models/backbones/build_backbones.py
1385
+
1386
+ import torch
1387
+ import torch.nn as nn
1388
+ from collections import OrderedDict
1389
+ from torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights
1390
+ # from models.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5
1391
+ # from models.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l
1392
+ # from config import Config
1393
+
1394
+
1395
+ config = Config()
1396
+
1397
+ def build_backbone(bb_name, pretrained=True, params_settings=''):
1398
+ if bb_name == 'vgg16':
1399
+ bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0]
1400
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]}))
1401
+ elif bb_name == 'vgg16bn':
1402
+ bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0]
1403
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]}))
1404
+ elif bb_name == 'resnet50':
1405
+ bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children())
1406
+ bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]}))
1407
+ else:
1408
+ bb = eval('{}({})'.format(bb_name, params_settings))
1409
+ if pretrained:
1410
+ bb = load_weights(bb, bb_name)
1411
+ return bb
1412
+
1413
+ def load_weights(model, model_name):
1414
+ save_model = torch.load(config.weights[model_name], map_location='cpu')
1415
+ model_dict = model.state_dict()
1416
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model.items() if k in model_dict.keys()}
1417
+ # to ignore the weights with mismatched size when I modify the backbone itself.
1418
+ if not state_dict:
1419
+ save_model_keys = list(save_model.keys())
1420
+ sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None
1421
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model[sub_item].items() if k in model_dict.keys()}
1422
+ if not state_dict or not sub_item:
1423
+ print('Weights are not successully loaded. Check the state dict of weights file.')
1424
+ return None
1425
+ else:
1426
+ print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item))
1427
+ model_dict.update(state_dict)
1428
+ model.load_state_dict(model_dict)
1429
+ return model
1430
+
1431
+
1432
+
1433
+ ### models/modules/decoder_blocks.py
1434
+
1435
+ import torch
1436
+ import torch.nn as nn
1437
+ # from models.aspp import ASPP, ASPPDeformable
1438
+ # from config import Config
1439
+
1440
+
1441
+ # config = Config()
1442
+
1443
+
1444
+ class BasicDecBlk(nn.Module):
1445
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1446
+ super(BasicDecBlk, self).__init__()
1447
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1448
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1449
+ self.relu_in = nn.ReLU(inplace=True)
1450
+ if config.dec_att == 'ASPP':
1451
+ self.dec_att = ASPP(in_channels=inter_channels)
1452
+ elif config.dec_att == 'ASPPDeformable':
1453
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1454
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1455
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1456
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1457
+
1458
+ def forward(self, x):
1459
+ x = self.conv_in(x)
1460
+ x = self.bn_in(x)
1461
+ x = self.relu_in(x)
1462
+ if hasattr(self, 'dec_att'):
1463
+ x = self.dec_att(x)
1464
+ x = self.conv_out(x)
1465
+ x = self.bn_out(x)
1466
+ return x
1467
+
1468
+
1469
+ class ResBlk(nn.Module):
1470
+ def __init__(self, in_channels=64, out_channels=None, inter_channels=64):
1471
+ super(ResBlk, self).__init__()
1472
+ if out_channels is None:
1473
+ out_channels = in_channels
1474
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1475
+
1476
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1477
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1478
+ self.relu_in = nn.ReLU(inplace=True)
1479
+
1480
+ if config.dec_att == 'ASPP':
1481
+ self.dec_att = ASPP(in_channels=inter_channels)
1482
+ elif config.dec_att == 'ASPPDeformable':
1483
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1484
+
1485
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1486
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1487
+
1488
+ self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1489
+
1490
+ def forward(self, x):
1491
+ _x = self.conv_resi(x)
1492
+ x = self.conv_in(x)
1493
+ x = self.bn_in(x)
1494
+ x = self.relu_in(x)
1495
+ if hasattr(self, 'dec_att'):
1496
+ x = self.dec_att(x)
1497
+ x = self.conv_out(x)
1498
+ x = self.bn_out(x)
1499
+ return x + _x
1500
+
1501
+
1502
+
1503
+ ### models/modules/lateral_blocks.py
1504
+
1505
+ import numpy as np
1506
+ import torch
1507
+ import torch.nn as nn
1508
+ import torch.nn.functional as F
1509
+ from functools import partial
1510
+
1511
+ # from config import Config
1512
+
1513
+
1514
+ # config = Config()
1515
+
1516
+
1517
+ class BasicLatBlk(nn.Module):
1518
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1519
+ super(BasicLatBlk, self).__init__()
1520
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1521
+ self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1522
+
1523
+ def forward(self, x):
1524
+ x = self.conv(x)
1525
+ return x
1526
+
1527
+
1528
+
1529
+ ### models/modules/aspp.py
1530
+
1531
+ import torch
1532
+ import torch.nn as nn
1533
+ import torch.nn.functional as F
1534
+ # from models.deform_conv import DeformableConv2d
1535
+ # from config import Config
1536
+
1537
+
1538
+ # config = Config()
1539
+
1540
+
1541
+ class _ASPPModule(nn.Module):
1542
+ def __init__(self, in_channels, planes, kernel_size, padding, dilation):
1543
+ super(_ASPPModule, self).__init__()
1544
+ self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size,
1545
+ stride=1, padding=padding, dilation=dilation, bias=False)
1546
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1547
+ self.relu = nn.ReLU(inplace=True)
1548
+
1549
+ def forward(self, x):
1550
+ x = self.atrous_conv(x)
1551
+ x = self.bn(x)
1552
+
1553
+ return self.relu(x)
1554
+
1555
+
1556
+ class ASPP(nn.Module):
1557
+ def __init__(self, in_channels=64, out_channels=None, output_stride=16):
1558
+ super(ASPP, self).__init__()
1559
+ self.down_scale = 1
1560
+ if out_channels is None:
1561
+ out_channels = in_channels
1562
+ self.in_channelster = 256 // self.down_scale
1563
+ if output_stride == 16:
1564
+ dilations = [1, 6, 12, 18]
1565
+ elif output_stride == 8:
1566
+ dilations = [1, 12, 24, 36]
1567
+ else:
1568
+ raise NotImplementedError
1569
+
1570
+ self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0])
1571
+ self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1])
1572
+ self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2])
1573
+ self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3])
1574
+
1575
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1576
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1577
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1578
+ nn.ReLU(inplace=True))
1579
+ self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False)
1580
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1581
+ self.relu = nn.ReLU(inplace=True)
1582
+ self.dropout = nn.Dropout(0.5)
1583
+
1584
+ def forward(self, x):
1585
+ x1 = self.aspp1(x)
1586
+ x2 = self.aspp2(x)
1587
+ x3 = self.aspp3(x)
1588
+ x4 = self.aspp4(x)
1589
+ x5 = self.global_avg_pool(x)
1590
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1591
+ x = torch.cat((x1, x2, x3, x4, x5), dim=1)
1592
+
1593
+ x = self.conv1(x)
1594
+ x = self.bn1(x)
1595
+ x = self.relu(x)
1596
+
1597
+ return self.dropout(x)
1598
+
1599
+
1600
+ ##################### Deformable
1601
+ class _ASPPModuleDeformable(nn.Module):
1602
+ def __init__(self, in_channels, planes, kernel_size, padding):
1603
+ super(_ASPPModuleDeformable, self).__init__()
1604
+ self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size,
1605
+ stride=1, padding=padding, bias=False)
1606
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1607
+ self.relu = nn.ReLU(inplace=True)
1608
+
1609
+ def forward(self, x):
1610
+ x = self.atrous_conv(x)
1611
+ x = self.bn(x)
1612
+
1613
+ return self.relu(x)
1614
+
1615
+
1616
+ class ASPPDeformable(nn.Module):
1617
+ def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]):
1618
+ super(ASPPDeformable, self).__init__()
1619
+ self.down_scale = 1
1620
+ if out_channels is None:
1621
+ out_channels = in_channels
1622
+ self.in_channelster = 256 // self.down_scale
1623
+
1624
+ self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0)
1625
+ self.aspp_deforms = nn.ModuleList([
1626
+ _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes
1627
+ ])
1628
+
1629
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1630
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1631
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1632
+ nn.ReLU(inplace=True))
1633
+ self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False)
1634
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1635
+ self.relu = nn.ReLU(inplace=True)
1636
+ self.dropout = nn.Dropout(0.5)
1637
+
1638
+ def forward(self, x):
1639
+ x1 = self.aspp1(x)
1640
+ x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms]
1641
+ x5 = self.global_avg_pool(x)
1642
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1643
+ x = torch.cat((x1, *x_aspp_deforms, x5), dim=1)
1644
+
1645
+ x = self.conv1(x)
1646
+ x = self.bn1(x)
1647
+ x = self.relu(x)
1648
+
1649
+ return self.dropout(x)
1650
+
1651
+
1652
+
1653
+ ### models/refinement/refiner.py
1654
+
1655
+ import torch
1656
+ import torch.nn as nn
1657
+ from collections import OrderedDict
1658
+ import torch
1659
+ import torch.nn as nn
1660
+ import torch.nn.functional as F
1661
+ from torchvision.models import vgg16, vgg16_bn
1662
+ from torchvision.models import resnet50
1663
+
1664
+ # from config import Config
1665
+ # from dataset import class_labels_TR_sorted
1666
+ # from models.build_backbone import build_backbone
1667
+ # from models.decoder_blocks import BasicDecBlk
1668
+ # from models.lateral_blocks import BasicLatBlk
1669
+ # from models.ing import *
1670
+ # from models.stem_layer import StemLayer
1671
+
1672
+
1673
+ class RefinerPVTInChannels4(nn.Module):
1674
+ def __init__(self, in_channels=3+1):
1675
+ super(RefinerPVTInChannels4, self).__init__()
1676
+ self.config = Config()
1677
+ self.epoch = 1
1678
+ self.bb = build_backbone(self.config.bb, params_settings='in_channels=4')
1679
+
1680
+ lateral_channels_in_collection = {
1681
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1682
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1683
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1684
+ }
1685
+ channels = lateral_channels_in_collection[self.config.bb]
1686
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1687
+
1688
+ self.decoder = Decoder(channels)
1689
+
1690
+ if 0:
1691
+ for key, value in self.named_parameters():
1692
+ if 'bb.' in key:
1693
+ value.requires_grad = False
1694
+
1695
+ def forward(self, x):
1696
+ if isinstance(x, list):
1697
+ x = torch.cat(x, dim=1)
1698
+ ########## Encoder ##########
1699
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1700
+ x1 = self.bb.conv1(x)
1701
+ x2 = self.bb.conv2(x1)
1702
+ x3 = self.bb.conv3(x2)
1703
+ x4 = self.bb.conv4(x3)
1704
+ else:
1705
+ x1, x2, x3, x4 = self.bb(x)
1706
+
1707
+ x4 = self.squeeze_module(x4)
1708
+
1709
+ ########## Decoder ##########
1710
+
1711
+ features = [x, x1, x2, x3, x4]
1712
+ scaled_preds = self.decoder(features)
1713
+
1714
+ return scaled_preds
1715
+
1716
+
1717
+ class Refiner(nn.Module):
1718
+ def __init__(self, in_channels=3+1):
1719
+ super(Refiner, self).__init__()
1720
+ self.config = Config()
1721
+ self.epoch = 1
1722
+ self.stem_layer = StemLayer(in_channels=in_channels, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
1723
+ self.bb = build_backbone(self.config.bb)
1724
+
1725
+ lateral_channels_in_collection = {
1726
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1727
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1728
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1729
+ }
1730
+ channels = lateral_channels_in_collection[self.config.bb]
1731
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1732
+
1733
+ self.decoder = Decoder(channels)
1734
+
1735
+ if 0:
1736
+ for key, value in self.named_parameters():
1737
+ if 'bb.' in key:
1738
+ value.requires_grad = False
1739
+
1740
+ def forward(self, x):
1741
+ if isinstance(x, list):
1742
+ x = torch.cat(x, dim=1)
1743
+ x = self.stem_layer(x)
1744
+ ########## Encoder ##########
1745
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1746
+ x1 = self.bb.conv1(x)
1747
+ x2 = self.bb.conv2(x1)
1748
+ x3 = self.bb.conv3(x2)
1749
+ x4 = self.bb.conv4(x3)
1750
+ else:
1751
+ x1, x2, x3, x4 = self.bb(x)
1752
+
1753
+ x4 = self.squeeze_module(x4)
1754
+
1755
+ ########## Decoder ##########
1756
+
1757
+ features = [x, x1, x2, x3, x4]
1758
+ scaled_preds = self.decoder(features)
1759
+
1760
+ return scaled_preds
1761
+
1762
+
1763
+ class Decoder(nn.Module):
1764
+ def __init__(self, channels):
1765
+ super(Decoder, self).__init__()
1766
+ self.config = Config()
1767
+ DecoderBlock = eval('BasicDecBlk')
1768
+ LateralBlock = eval('BasicLatBlk')
1769
+
1770
+ self.decoder_block4 = DecoderBlock(channels[0], channels[1])
1771
+ self.decoder_block3 = DecoderBlock(channels[1], channels[2])
1772
+ self.decoder_block2 = DecoderBlock(channels[2], channels[3])
1773
+ self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2)
1774
+
1775
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
1776
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
1777
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
1778
+
1779
+ if self.config.ms_supervision:
1780
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
1781
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
1782
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
1783
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0))
1784
+
1785
+ def forward(self, features):
1786
+ x, x1, x2, x3, x4 = features
1787
+ outs = []
1788
+ p4 = self.decoder_block4(x4)
1789
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
1790
+ _p3 = _p4 + self.lateral_block4(x3)
1791
+
1792
+ p3 = self.decoder_block3(_p3)
1793
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
1794
+ _p2 = _p3 + self.lateral_block3(x2)
1795
+
1796
+ p2 = self.decoder_block2(_p2)
1797
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
1798
+ _p1 = _p2 + self.lateral_block2(x1)
1799
+
1800
+ _p1 = self.decoder_block1(_p1)
1801
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
1802
+ p1_out = self.conv_out1(_p1)
1803
+
1804
+ if self.config.ms_supervision:
1805
+ outs.append(self.conv_ms_spvn_4(p4))
1806
+ outs.append(self.conv_ms_spvn_3(p3))
1807
+ outs.append(self.conv_ms_spvn_2(p2))
1808
+ outs.append(p1_out)
1809
+ return outs
1810
+
1811
+
1812
+ class RefUNet(nn.Module):
1813
+ # Refinement
1814
+ def __init__(self, in_channels=3+1):
1815
+ super(RefUNet, self).__init__()
1816
+ self.encoder_1 = nn.Sequential(
1817
+ nn.Conv2d(in_channels, 64, 3, 1, 1),
1818
+ nn.Conv2d(64, 64, 3, 1, 1),
1819
+ nn.BatchNorm2d(64),
1820
+ nn.ReLU(inplace=True)
1821
+ )
1822
+
1823
+ self.encoder_2 = nn.Sequential(
1824
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1825
+ nn.Conv2d(64, 64, 3, 1, 1),
1826
+ nn.BatchNorm2d(64),
1827
+ nn.ReLU(inplace=True)
1828
+ )
1829
+
1830
+ self.encoder_3 = nn.Sequential(
1831
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1832
+ nn.Conv2d(64, 64, 3, 1, 1),
1833
+ nn.BatchNorm2d(64),
1834
+ nn.ReLU(inplace=True)
1835
+ )
1836
+
1837
+ self.encoder_4 = nn.Sequential(
1838
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1839
+ nn.Conv2d(64, 64, 3, 1, 1),
1840
+ nn.BatchNorm2d(64),
1841
+ nn.ReLU(inplace=True)
1842
+ )
1843
+
1844
+ self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True)
1845
+ #####
1846
+ self.decoder_5 = nn.Sequential(
1847
+ nn.Conv2d(64, 64, 3, 1, 1),
1848
+ nn.BatchNorm2d(64),
1849
+ nn.ReLU(inplace=True)
1850
+ )
1851
+ #####
1852
+ self.decoder_4 = nn.Sequential(
1853
+ nn.Conv2d(128, 64, 3, 1, 1),
1854
+ nn.BatchNorm2d(64),
1855
+ nn.ReLU(inplace=True)
1856
+ )
1857
+
1858
+ self.decoder_3 = nn.Sequential(
1859
+ nn.Conv2d(128, 64, 3, 1, 1),
1860
+ nn.BatchNorm2d(64),
1861
+ nn.ReLU(inplace=True)
1862
+ )
1863
+
1864
+ self.decoder_2 = nn.Sequential(
1865
+ nn.Conv2d(128, 64, 3, 1, 1),
1866
+ nn.BatchNorm2d(64),
1867
+ nn.ReLU(inplace=True)
1868
+ )
1869
+
1870
+ self.decoder_1 = nn.Sequential(
1871
+ nn.Conv2d(128, 64, 3, 1, 1),
1872
+ nn.BatchNorm2d(64),
1873
+ nn.ReLU(inplace=True)
1874
+ )
1875
+
1876
+ self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1)
1877
+
1878
+ self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
1879
+
1880
+ def forward(self, x):
1881
+ outs = []
1882
+ if isinstance(x, list):
1883
+ x = torch.cat(x, dim=1)
1884
+ hx = x
1885
+
1886
+ hx1 = self.encoder_1(hx)
1887
+ hx2 = self.encoder_2(hx1)
1888
+ hx3 = self.encoder_3(hx2)
1889
+ hx4 = self.encoder_4(hx3)
1890
+
1891
+ hx = self.decoder_5(self.pool4(hx4))
1892
+ hx = torch.cat((self.upscore2(hx), hx4), 1)
1893
+
1894
+ d4 = self.decoder_4(hx)
1895
+ hx = torch.cat((self.upscore2(d4), hx3), 1)
1896
+
1897
+ d3 = self.decoder_3(hx)
1898
+ hx = torch.cat((self.upscore2(d3), hx2), 1)
1899
+
1900
+ d2 = self.decoder_2(hx)
1901
+ hx = torch.cat((self.upscore2(d2), hx1), 1)
1902
+
1903
+ d1 = self.decoder_1(hx)
1904
+
1905
+ x = self.conv_d0(d1)
1906
+ outs.append(x)
1907
+ return outs
1908
+
1909
+
1910
+
1911
+ ### models/stem_layer.py
1912
+
1913
+ import torch.nn as nn
1914
+ # from utils import build_act_layer, build_norm_layer
1915
+
1916
+
1917
+ class StemLayer(nn.Module):
1918
+ r""" Stem layer of InternImage
1919
+ Args:
1920
+ in_channels (int): number of input channels
1921
+ out_channels (int): number of output channels
1922
+ act_layer (str): activation layer
1923
+ norm_layer (str): normalization layer
1924
+ """
1925
+
1926
+ def __init__(self,
1927
+ in_channels=3+1,
1928
+ inter_channels=48,
1929
+ out_channels=96,
1930
+ act_layer='GELU',
1931
+ norm_layer='BN'):
1932
+ super().__init__()
1933
+ self.conv1 = nn.Conv2d(in_channels,
1934
+ inter_channels,
1935
+ kernel_size=3,
1936
+ stride=1,
1937
+ padding=1)
1938
+ self.norm1 = build_norm_layer(
1939
+ inter_channels, norm_layer, 'channels_first', 'channels_first'
1940
+ )
1941
+ self.act = build_act_layer(act_layer)
1942
+ self.conv2 = nn.Conv2d(inter_channels,
1943
+ out_channels,
1944
+ kernel_size=3,
1945
+ stride=1,
1946
+ padding=1)
1947
+ self.norm2 = build_norm_layer(
1948
+ out_channels, norm_layer, 'channels_first', 'channels_first'
1949
+ )
1950
+
1951
+ def forward(self, x):
1952
+ x = self.conv1(x)
1953
+ x = self.norm1(x)
1954
+ x = self.act(x)
1955
+ x = self.conv2(x)
1956
+ x = self.norm2(x)
1957
+ return x
1958
+
1959
+
1960
+ ### models/birefnet.py
1961
+
1962
+ import torch
1963
+ import torch.nn as nn
1964
+ import torch.nn.functional as F
1965
+ from kornia.filters import laplacian
1966
+ from transformers import PreTrainedModel
1967
+ from einops import rearrange
1968
+
1969
+ # from config import Config
1970
+ # from dataset import class_labels_TR_sorted
1971
+ # from models.build_backbone import build_backbone
1972
+ # from models.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk
1973
+ # from models.lateral_blocks import BasicLatBlk
1974
+ # from models.aspp import ASPP, ASPPDeformable
1975
+ # from models.ing import *
1976
+ # from models.refiner import Refiner, RefinerPVTInChannels4, RefUNet
1977
+ # from models.stem_layer import StemLayer
1978
+ from .BiRefNet_config import BiRefNetConfig
1979
+
1980
+
1981
+ def image2patches(image, grid_h=2, grid_w=2, patch_ref=None, transformation='b c (hg h) (wg w) -> (b hg wg) c h w'):
1982
+ if patch_ref is not None:
1983
+ grid_h, grid_w = image.shape[-2] // patch_ref.shape[-2], image.shape[-1] // patch_ref.shape[-1]
1984
+ patches = rearrange(image, transformation, hg=grid_h, wg=grid_w)
1985
+ return patches
1986
+
1987
+ def patches2image(patches, grid_h=2, grid_w=2, patch_ref=None, transformation='(b hg wg) c h w -> b c (hg h) (wg w)'):
1988
+ if patch_ref is not None:
1989
+ grid_h, grid_w = patch_ref.shape[-2] // patches[0].shape[-2], patch_ref.shape[-1] // patches[0].shape[-1]
1990
+ image = rearrange(patches, transformation, hg=grid_h, wg=grid_w)
1991
+ return image
1992
+
1993
+ class BiRefNet(
1994
+ PreTrainedModel
1995
+ ):
1996
+ config_class = BiRefNetConfig
1997
+ def __init__(self, bb_pretrained=True, config=BiRefNetConfig()):
1998
+ super(BiRefNet, self).__init__(config)
1999
+ bb_pretrained = config.bb_pretrained
2000
+ self.config = Config()
2001
+ self.epoch = 1
2002
+ self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained)
2003
+
2004
+ channels = self.config.lateral_channels_in_collection
2005
+
2006
+ if self.config.auxiliary_classification:
2007
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
2008
+ self.cls_head = nn.Sequential(
2009
+ nn.Linear(channels[0], len(class_labels_TR_sorted))
2010
+ )
2011
+
2012
+ if self.config.squeeze_block:
2013
+ self.squeeze_module = nn.Sequential(*[
2014
+ eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0])
2015
+ for _ in range(eval(self.config.squeeze_block.split('_x')[1]))
2016
+ ])
2017
+
2018
+ self.decoder = Decoder(channels)
2019
+
2020
+ if self.config.ender:
2021
+ self.dec_end = nn.Sequential(
2022
+ nn.Conv2d(1, 16, 3, 1, 1),
2023
+ nn.Conv2d(16, 1, 3, 1, 1),
2024
+ nn.ReLU(inplace=True),
2025
+ )
2026
+
2027
+ # refine patch-level segmentation
2028
+ if self.config.refine:
2029
+ if self.config.refine == 'itself':
2030
+ self.stem_layer = StemLayer(in_channels=3+1, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
2031
+ else:
2032
+ self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1'))
2033
+
2034
+ if self.config.freeze_bb:
2035
+ # Freeze the backbone...
2036
+ print(self.named_parameters())
2037
+ for key, value in self.named_parameters():
2038
+ if 'bb.' in key and 'refiner.' not in key:
2039
+ value.requires_grad = False
2040
+
2041
+ def forward_enc(self, x):
2042
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
2043
+ x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3)
2044
+ else:
2045
+ x1, x2, x3, x4 = self.bb(x)
2046
+ if self.config.mul_scl_ipt == 'cat':
2047
+ B, C, H, W = x.shape
2048
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2049
+ x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2050
+ x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2051
+ x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2052
+ x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2053
+ elif self.config.mul_scl_ipt == 'add':
2054
+ B, C, H, W = x.shape
2055
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2056
+ x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)
2057
+ x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)
2058
+ x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)
2059
+ x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)
2060
+ class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None
2061
+ if self.config.cxt:
2062
+ x4 = torch.cat(
2063
+ (
2064
+ *[
2065
+ F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True),
2066
+ F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True),
2067
+ F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True),
2068
+ ][-len(self.config.cxt):],
2069
+ x4
2070
+ ),
2071
+ dim=1
2072
+ )
2073
+ return (x1, x2, x3, x4), class_preds
2074
+
2075
+ def forward_ori(self, x):
2076
+ ########## Encoder ##########
2077
+ (x1, x2, x3, x4), class_preds = self.forward_enc(x)
2078
+ if self.config.squeeze_block:
2079
+ x4 = self.squeeze_module(x4)
2080
+ ########## Decoder ##########
2081
+ features = [x, x1, x2, x3, x4]
2082
+ if self.training and self.config.out_ref:
2083
+ features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5))
2084
+ scaled_preds = self.decoder(features)
2085
+ return scaled_preds, class_preds
2086
+
2087
+ def forward(self, x):
2088
+ scaled_preds, class_preds = self.forward_ori(x)
2089
+ class_preds_lst = [class_preds]
2090
+ return [scaled_preds, class_preds_lst] if self.training else scaled_preds
2091
+
2092
+
2093
+ class Decoder(nn.Module):
2094
+ def __init__(self, channels):
2095
+ super(Decoder, self).__init__()
2096
+ self.config = Config()
2097
+ DecoderBlock = eval(self.config.dec_blk)
2098
+ LateralBlock = eval(self.config.lat_blk)
2099
+
2100
+ if self.config.dec_ipt:
2101
+ self.split = self.config.dec_ipt_split
2102
+ N_dec_ipt = 64
2103
+ DBlock = SimpleConvs
2104
+ ic = 64
2105
+ ipt_cha_opt = 1
2106
+ self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2107
+ self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2108
+ self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic)
2109
+ self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic)
2110
+ self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic)
2111
+ else:
2112
+ self.split = None
2113
+
2114
+ self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1])
2115
+ self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2])
2116
+ self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3])
2117
+ self.decoder_block1 = DecoderBlock(channels[3]+([N_dec_ipt, channels[2]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]//2)
2118
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2+([N_dec_ipt, channels[3]//8][ipt_cha_opt] if self.config.dec_ipt else 0), 1, 1, 1, 0))
2119
+
2120
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
2121
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
2122
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
2123
+
2124
+ if self.config.ms_supervision:
2125
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
2126
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
2127
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
2128
+
2129
+ if self.config.out_ref:
2130
+ _N = 16
2131
+ self.gdt_convs_4 = nn.Sequential(nn.Conv2d(channels[1], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2132
+ self.gdt_convs_3 = nn.Sequential(nn.Conv2d(channels[2], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2133
+ self.gdt_convs_2 = nn.Sequential(nn.Conv2d(channels[3], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2134
+
2135
+ self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2136
+ self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2137
+ self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2138
+
2139
+ self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2140
+ self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2141
+ self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2142
+
2143
+ def forward(self, features):
2144
+ if self.training and self.config.out_ref:
2145
+ outs_gdt_pred = []
2146
+ outs_gdt_label = []
2147
+ x, x1, x2, x3, x4, gdt_gt = features
2148
+ else:
2149
+ x, x1, x2, x3, x4 = features
2150
+ outs = []
2151
+
2152
+ if self.config.dec_ipt:
2153
+ patches_batch = image2patches(x, patch_ref=x4, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2154
+ x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1)
2155
+ p4 = self.decoder_block4(x4)
2156
+ m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision and self.training else None
2157
+ if self.config.out_ref:
2158
+ p4_gdt = self.gdt_convs_4(p4)
2159
+ if self.training:
2160
+ # >> GT:
2161
+ m4_dia = m4
2162
+ gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2163
+ outs_gdt_label.append(gdt_label_main_4)
2164
+ # >> Pred:
2165
+ gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt)
2166
+ outs_gdt_pred.append(gdt_pred_4)
2167
+ gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid()
2168
+ # >> Finally:
2169
+ p4 = p4 * gdt_attn_4
2170
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
2171
+ _p3 = _p4 + self.lateral_block4(x3)
2172
+
2173
+ if self.config.dec_ipt:
2174
+ patches_batch = image2patches(x, patch_ref=_p3, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2175
+ _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1)
2176
+ p3 = self.decoder_block3(_p3)
2177
+ m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision and self.training else None
2178
+ if self.config.out_ref:
2179
+ p3_gdt = self.gdt_convs_3(p3)
2180
+ if self.training:
2181
+ # >> GT:
2182
+ # m3 --dilation--> m3_dia
2183
+ # G_3^gt * m3_dia --> G_3^m, which is the label of gradient
2184
+ m3_dia = m3
2185
+ gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2186
+ outs_gdt_label.append(gdt_label_main_3)
2187
+ # >> Pred:
2188
+ # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx
2189
+ # F_3^G --sigmoid--> A_3^G
2190
+ gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt)
2191
+ outs_gdt_pred.append(gdt_pred_3)
2192
+ gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid()
2193
+ # >> Finally:
2194
+ # p3 = p3 * A_3^G
2195
+ p3 = p3 * gdt_attn_3
2196
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
2197
+ _p2 = _p3 + self.lateral_block3(x2)
2198
+
2199
+ if self.config.dec_ipt:
2200
+ patches_batch = image2patches(x, patch_ref=_p2, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2201
+ _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1)
2202
+ p2 = self.decoder_block2(_p2)
2203
+ m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision and self.training else None
2204
+ if self.config.out_ref:
2205
+ p2_gdt = self.gdt_convs_2(p2)
2206
+ if self.training:
2207
+ # >> GT:
2208
+ m2_dia = m2
2209
+ gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2210
+ outs_gdt_label.append(gdt_label_main_2)
2211
+ # >> Pred:
2212
+ gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt)
2213
+ outs_gdt_pred.append(gdt_pred_2)
2214
+ gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid()
2215
+ # >> Finally:
2216
+ p2 = p2 * gdt_attn_2
2217
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
2218
+ _p1 = _p2 + self.lateral_block2(x1)
2219
+
2220
+ if self.config.dec_ipt:
2221
+ patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2222
+ _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1)
2223
+ _p1 = self.decoder_block1(_p1)
2224
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
2225
+
2226
+ if self.config.dec_ipt:
2227
+ patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2228
+ _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1)
2229
+ p1_out = self.conv_out1(_p1)
2230
+
2231
+ if self.config.ms_supervision and self.training:
2232
+ outs.append(m4)
2233
+ outs.append(m3)
2234
+ outs.append(m2)
2235
+ outs.append(p1_out)
2236
+ return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs)
2237
+
2238
+
2239
+ class SimpleConvs(nn.Module):
2240
+ def __init__(
2241
+ self, in_channels: int, out_channels: int, inter_channels=64
2242
+ ) -> None:
2243
+ super().__init__()
2244
+ self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1)
2245
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
2246
+
2247
+ def forward(self, x):
2248
+ return self.conv_out(self.conv1(x))
models/RMBG/BiRefNet-HR/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "ZhengPeng7/BiRefNet_HR",
3
+ "architectures": [
4
+ "BiRefNet"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "BiRefNet_config.BiRefNetConfig",
8
+ "AutoModelForImageSegmentation": "birefnet.BiRefNet"
9
+ },
10
+ "custom_pipelines": {
11
+ "image-segmentation": {
12
+ "pt": [
13
+ "AutoModelForImageSegmentation"
14
+ ],
15
+ "tf": [],
16
+ "type": "image"
17
+ }
18
+ },
19
+ "bb_pretrained": false
20
+ }
models/RMBG/BiRefNet-HR/gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
models/RMBG/BiRefNet-HR/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d678bafec0b0019fbb073b7fd02f05ede25dc4b15254f23b2fb0be333200c0d
3
+ size 444473596
models/RMBG/BiRefNet/BiRefNet-HR-matting.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5a4de698739ea5e0e8bbab28e1b293dde95092b87a442d566cbc585c53cef55
3
+ size 444473596
models/RMBG/BiRefNet/BiRefNet-HR.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d678bafec0b0019fbb073b7fd02f05ede25dc4b15254f23b2fb0be333200c0d
3
+ size 444473596
models/RMBG/BiRefNet/BiRefNet-general.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77277264c0e8c74149d3ff2fade4fd8176965b7108f3c5fc3b8c9c811edb4519
3
+ size 884878856
models/RMBG/BiRefNet/BiRefNet-matting.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9875de5b1e6c8eb5fdaa8c727a82927ce442cdc87ba3abee6a77e6fa46c25bb
3
+ size 884878856
models/RMBG/BiRefNet/BiRefNet-portrait.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a4eb3a5469b75f0cccaec6772c22fc30e6c12ed429c2c0ba71b43e3d8d97182
3
+ size 884878856
models/RMBG/BiRefNet/BiRefNet_512x512.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d94ae0eefb2d2020192001e984ecd6b367478118257a3132e6a484bbf18b0f41
3
+ size 444473596
models/RMBG/BiRefNet/BiRefNet_config.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class BiRefNetConfig(PretrainedConfig):
4
+ model_type = "SegformerForSemanticSegmentation"
5
+ def __init__(
6
+ self,
7
+ bb_pretrained=False,
8
+ **kwargs
9
+ ):
10
+ self.bb_pretrained = bb_pretrained
11
+ super().__init__(**kwargs)
models/RMBG/BiRefNet/BiRefNet_lite-2K.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa2e4a5af5eb3904694feb40f2b39ec5dd7cd9110906590cfeb982f09a46021d
3
+ size 177634392
models/RMBG/BiRefNet/BiRefNet_lite.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4417d89795250e698c3cb0ae8df15743810065f646f48a694fdfa7ca052d0815
3
+ size 177634392
models/RMBG/BiRefNet/birefnet.py ADDED
@@ -0,0 +1,2248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### config.py
2
+
3
+ import os
4
+ import math
5
+
6
+
7
+ class Config():
8
+ def __init__(self) -> None:
9
+ # PATH settings
10
+ self.sys_home_dir = os.path.expanduser('~') # Make up your file system as: SYS_HOME_DIR/codes/dis/BiRefNet, SYS_HOME_DIR/datasets/dis/xx, SYS_HOME_DIR/weights/xx
11
+
12
+ # TASK settings
13
+ self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0]
14
+ self.training_set = {
15
+ 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0],
16
+ 'COD': 'TR-COD10K+TR-CAMO',
17
+ 'HRSOD': ['TR-DUTS', 'TR-HRSOD', 'TR-UHRSD', 'TR-DUTS+TR-HRSOD', 'TR-DUTS+TR-UHRSD', 'TR-HRSOD+TR-UHRSD', 'TR-DUTS+TR-HRSOD+TR-UHRSD'][5],
18
+ 'DIS5K+HRSOD+HRS10K': 'DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4+DIS-TR+TE-HRS10K+TE-HRSOD+TE-UHRSD+TR-HRS10K+TR-HRSOD+TR-UHRSD', # leave DIS-VD for evaluation.
19
+ 'P3M-10k': 'TR-P3M-10k',
20
+ }[self.task]
21
+ self.prompt4loc = ['dense', 'sparse'][0]
22
+
23
+ # Faster-Training settings
24
+ self.load_all = True
25
+ self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch.
26
+ # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting.
27
+ # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607.
28
+ # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training.
29
+ self.precisionHigh = True
30
+
31
+ # MODEL settings
32
+ self.ms_supervision = True
33
+ self.out_ref = self.ms_supervision and True
34
+ self.dec_ipt = True
35
+ self.dec_ipt_split = True
36
+ self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder
37
+ self.mul_scl_ipt = ['', 'add', 'cat'][2]
38
+ self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2]
39
+ self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1]
40
+ self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]
41
+
42
+ # TRAINING settings
43
+ self.batch_size = 4
44
+ self.IoU_finetune_last_epochs = [
45
+ 0,
46
+ {
47
+ 'DIS5K': -50,
48
+ 'COD': -20,
49
+ 'HRSOD': -20,
50
+ 'DIS5K+HRSOD+HRS10K': -20,
51
+ 'P3M-10k': -20,
52
+ }[self.task]
53
+ ][1] # choose 0 to skip
54
+ self.lr = (1e-4 if 'DIS5K' in self.task else 1e-5) * math.sqrt(self.batch_size / 4) # DIS needs high lr to converge faster. Adapt the lr linearly
55
+ self.size = 1024
56
+ self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader
57
+
58
+ # Backbone settings
59
+ self.bb = [
60
+ 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2
61
+ 'swin_v1_t', 'swin_v1_s', # 3, 4
62
+ 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4
63
+ 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8
64
+ 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5
65
+ ][6]
66
+ self.lateral_channels_in_collection = {
67
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
68
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
69
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
70
+ 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96],
71
+ 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64],
72
+ }[self.bb]
73
+ if self.mul_scl_ipt == 'cat':
74
+ self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection]
75
+ self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
76
+
77
+ # MODEL settings - inactive
78
+ self.lat_blk = ['BasicLatBlk'][0]
79
+ self.dec_channels_inter = ['fixed', 'adap'][0]
80
+ self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0]
81
+ self.progressive_ref = self.refine and True
82
+ self.ender = self.progressive_ref and False
83
+ self.scale = self.progressive_ref and 2
84
+ self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`.
85
+ self.refine_iteration = 1
86
+ self.freeze_bb = False
87
+ self.model = [
88
+ 'BiRefNet',
89
+ ][0]
90
+ if self.dec_blk == 'HierarAttDecBlk':
91
+ self.batch_size = 2 ** [0, 1, 2, 3, 4][2]
92
+
93
+ # TRAINING settings - inactive
94
+ self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4]
95
+ self.optimizer = ['Adam', 'AdamW'][1]
96
+ self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch.
97
+ self.lr_decay_rate = 0.5
98
+ # Loss
99
+ self.lambdas_pix_last = {
100
+ # not 0 means opening this loss
101
+ # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30
102
+ 'bce': 30 * 1, # high performance
103
+ 'iou': 0.5 * 1, # 0 / 255
104
+ 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64)
105
+ 'mse': 150 * 0, # can smooth the saliency map
106
+ 'triplet': 3 * 0,
107
+ 'reg': 100 * 0,
108
+ 'ssim': 10 * 1, # help contours,
109
+ 'cnt': 5 * 0, # help contours
110
+ 'structure': 5 * 0, # structure loss from codes of MVANet. A little improvement on DIS-TE[1,2,3], a bit more decrease on DIS-TE4.
111
+ }
112
+ self.lambdas_cls = {
113
+ 'ce': 5.0
114
+ }
115
+ # Adv
116
+ self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training
117
+ self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)
118
+
119
+ # PATH settings - inactive
120
+ self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis')
121
+ self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights')
122
+ self.weights = {
123
+ 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'),
124
+ 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]),
125
+ 'swin_v1_b': os.path.join(self.weights_root_dir, ['swin_base_patch4_window12_384_22kto1k.pth', 'swin_base_patch4_window12_384_22k.pth'][0]),
126
+ 'swin_v1_l': os.path.join(self.weights_root_dir, ['swin_large_patch4_window12_384_22kto1k.pth', 'swin_large_patch4_window12_384_22k.pth'][0]),
127
+ 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]),
128
+ 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]),
129
+ 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]),
130
+ 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]),
131
+ }
132
+
133
+ # Callbacks - inactive
134
+ self.verbose_eval = True
135
+ self.only_S_MAE = False
136
+ self.use_fp16 = False # Bugs. It may cause nan in training.
137
+ self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs
138
+
139
+ # others
140
+ self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
141
+
142
+ self.batch_size_valid = 1
143
+ self.rand_seed = 7
144
+ # run_sh_file = [f for f in os.listdir('.') if 'train.sh' == f] + [os.path.join('..', f) for f in os.listdir('..') if 'train.sh' == f]
145
+ # with open(run_sh_file[0], 'r') as f:
146
+ # lines = f.readlines()
147
+ # self.save_last = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'val_last=' in l][0].split('val_last=')[-1].split()[0])
148
+ # self.save_step = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'step=' in l][0].split('step=')[-1].split()[0])
149
+ # self.val_step = [0, self.save_step][0]
150
+
151
+ def print_task(self) -> None:
152
+ # Return task for choosing settings in shell scripts.
153
+ print(self.task)
154
+
155
+
156
+
157
+ ### models/backbones/pvt_v2.py
158
+
159
+ import torch
160
+ import torch.nn as nn
161
+ from functools import partial
162
+
163
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
164
+ from timm.models.registry import register_model
165
+
166
+ import math
167
+
168
+ # from config import Config
169
+
170
+ # config = Config()
171
+
172
+ class Mlp(nn.Module):
173
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
174
+ super().__init__()
175
+ out_features = out_features or in_features
176
+ hidden_features = hidden_features or in_features
177
+ self.fc1 = nn.Linear(in_features, hidden_features)
178
+ self.dwconv = DWConv(hidden_features)
179
+ self.act = act_layer()
180
+ self.fc2 = nn.Linear(hidden_features, out_features)
181
+ self.drop = nn.Dropout(drop)
182
+
183
+ self.apply(self._init_weights)
184
+
185
+ def _init_weights(self, m):
186
+ if isinstance(m, nn.Linear):
187
+ trunc_normal_(m.weight, std=.02)
188
+ if isinstance(m, nn.Linear) and m.bias is not None:
189
+ nn.init.constant_(m.bias, 0)
190
+ elif isinstance(m, nn.LayerNorm):
191
+ nn.init.constant_(m.bias, 0)
192
+ nn.init.constant_(m.weight, 1.0)
193
+ elif isinstance(m, nn.Conv2d):
194
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
195
+ fan_out //= m.groups
196
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
197
+ if m.bias is not None:
198
+ m.bias.data.zero_()
199
+
200
+ def forward(self, x, H, W):
201
+ x = self.fc1(x)
202
+ x = self.dwconv(x, H, W)
203
+ x = self.act(x)
204
+ x = self.drop(x)
205
+ x = self.fc2(x)
206
+ x = self.drop(x)
207
+ return x
208
+
209
+
210
+ class Attention(nn.Module):
211
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
212
+ super().__init__()
213
+ assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
214
+
215
+ self.dim = dim
216
+ self.num_heads = num_heads
217
+ head_dim = dim // num_heads
218
+ self.scale = qk_scale or head_dim ** -0.5
219
+
220
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
221
+ self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
222
+ self.attn_drop_prob = attn_drop
223
+ self.attn_drop = nn.Dropout(attn_drop)
224
+ self.proj = nn.Linear(dim, dim)
225
+ self.proj_drop = nn.Dropout(proj_drop)
226
+
227
+ self.sr_ratio = sr_ratio
228
+ if sr_ratio > 1:
229
+ self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
230
+ self.norm = nn.LayerNorm(dim)
231
+
232
+ self.apply(self._init_weights)
233
+
234
+ def _init_weights(self, m):
235
+ if isinstance(m, nn.Linear):
236
+ trunc_normal_(m.weight, std=.02)
237
+ if isinstance(m, nn.Linear) and m.bias is not None:
238
+ nn.init.constant_(m.bias, 0)
239
+ elif isinstance(m, nn.LayerNorm):
240
+ nn.init.constant_(m.bias, 0)
241
+ nn.init.constant_(m.weight, 1.0)
242
+ elif isinstance(m, nn.Conv2d):
243
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
244
+ fan_out //= m.groups
245
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
246
+ if m.bias is not None:
247
+ m.bias.data.zero_()
248
+
249
+ def forward(self, x, H, W):
250
+ B, N, C = x.shape
251
+ q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
252
+
253
+ if self.sr_ratio > 1:
254
+ x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
255
+ x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
256
+ x_ = self.norm(x_)
257
+ kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
258
+ else:
259
+ kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
260
+ k, v = kv[0], kv[1]
261
+
262
+ if config.SDPA_enabled:
263
+ x = torch.nn.functional.scaled_dot_product_attention(
264
+ q, k, v,
265
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
266
+ ).transpose(1, 2).reshape(B, N, C)
267
+ else:
268
+ attn = (q @ k.transpose(-2, -1)) * self.scale
269
+ attn = attn.softmax(dim=-1)
270
+ attn = self.attn_drop(attn)
271
+
272
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
273
+ x = self.proj(x)
274
+ x = self.proj_drop(x)
275
+
276
+ return x
277
+
278
+
279
+ class Block(nn.Module):
280
+
281
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
282
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
283
+ super().__init__()
284
+ self.norm1 = norm_layer(dim)
285
+ self.attn = Attention(
286
+ dim,
287
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
288
+ attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
289
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
290
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
291
+ self.norm2 = norm_layer(dim)
292
+ mlp_hidden_dim = int(dim * mlp_ratio)
293
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
294
+
295
+ self.apply(self._init_weights)
296
+
297
+ def _init_weights(self, m):
298
+ if isinstance(m, nn.Linear):
299
+ trunc_normal_(m.weight, std=.02)
300
+ if isinstance(m, nn.Linear) and m.bias is not None:
301
+ nn.init.constant_(m.bias, 0)
302
+ elif isinstance(m, nn.LayerNorm):
303
+ nn.init.constant_(m.bias, 0)
304
+ nn.init.constant_(m.weight, 1.0)
305
+ elif isinstance(m, nn.Conv2d):
306
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
307
+ fan_out //= m.groups
308
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
309
+ if m.bias is not None:
310
+ m.bias.data.zero_()
311
+
312
+ def forward(self, x, H, W):
313
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
314
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
315
+
316
+ return x
317
+
318
+
319
+ class OverlapPatchEmbed(nn.Module):
320
+ """ Image to Patch Embedding
321
+ """
322
+
323
+ def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768):
324
+ super().__init__()
325
+ img_size = to_2tuple(img_size)
326
+ patch_size = to_2tuple(patch_size)
327
+
328
+ self.img_size = img_size
329
+ self.patch_size = patch_size
330
+ self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
331
+ self.num_patches = self.H * self.W
332
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride,
333
+ padding=(patch_size[0] // 2, patch_size[1] // 2))
334
+ self.norm = nn.LayerNorm(embed_dim)
335
+
336
+ self.apply(self._init_weights)
337
+
338
+ def _init_weights(self, m):
339
+ if isinstance(m, nn.Linear):
340
+ trunc_normal_(m.weight, std=.02)
341
+ if isinstance(m, nn.Linear) and m.bias is not None:
342
+ nn.init.constant_(m.bias, 0)
343
+ elif isinstance(m, nn.LayerNorm):
344
+ nn.init.constant_(m.bias, 0)
345
+ nn.init.constant_(m.weight, 1.0)
346
+ elif isinstance(m, nn.Conv2d):
347
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
348
+ fan_out //= m.groups
349
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
350
+ if m.bias is not None:
351
+ m.bias.data.zero_()
352
+
353
+ def forward(self, x):
354
+ x = self.proj(x)
355
+ _, _, H, W = x.shape
356
+ x = x.flatten(2).transpose(1, 2)
357
+ x = self.norm(x)
358
+
359
+ return x, H, W
360
+
361
+
362
+ class PyramidVisionTransformerImpr(nn.Module):
363
+ def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
364
+ num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
365
+ attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
366
+ depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
367
+ super().__init__()
368
+ self.num_classes = num_classes
369
+ self.depths = depths
370
+
371
+ # patch_embed
372
+ self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels,
373
+ embed_dim=embed_dims[0])
374
+ self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0],
375
+ embed_dim=embed_dims[1])
376
+ self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1],
377
+ embed_dim=embed_dims[2])
378
+ self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2],
379
+ embed_dim=embed_dims[3])
380
+
381
+ # transformer encoder
382
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
383
+ cur = 0
384
+ self.block1 = nn.ModuleList([Block(
385
+ dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
386
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
387
+ sr_ratio=sr_ratios[0])
388
+ for i in range(depths[0])])
389
+ self.norm1 = norm_layer(embed_dims[0])
390
+
391
+ cur += depths[0]
392
+ self.block2 = nn.ModuleList([Block(
393
+ dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
394
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
395
+ sr_ratio=sr_ratios[1])
396
+ for i in range(depths[1])])
397
+ self.norm2 = norm_layer(embed_dims[1])
398
+
399
+ cur += depths[1]
400
+ self.block3 = nn.ModuleList([Block(
401
+ dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
402
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
403
+ sr_ratio=sr_ratios[2])
404
+ for i in range(depths[2])])
405
+ self.norm3 = norm_layer(embed_dims[2])
406
+
407
+ cur += depths[2]
408
+ self.block4 = nn.ModuleList([Block(
409
+ dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
410
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
411
+ sr_ratio=sr_ratios[3])
412
+ for i in range(depths[3])])
413
+ self.norm4 = norm_layer(embed_dims[3])
414
+
415
+ # classification head
416
+ # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
417
+
418
+ self.apply(self._init_weights)
419
+
420
+ def _init_weights(self, m):
421
+ if isinstance(m, nn.Linear):
422
+ trunc_normal_(m.weight, std=.02)
423
+ if isinstance(m, nn.Linear) and m.bias is not None:
424
+ nn.init.constant_(m.bias, 0)
425
+ elif isinstance(m, nn.LayerNorm):
426
+ nn.init.constant_(m.bias, 0)
427
+ nn.init.constant_(m.weight, 1.0)
428
+ elif isinstance(m, nn.Conv2d):
429
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
430
+ fan_out //= m.groups
431
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
432
+ if m.bias is not None:
433
+ m.bias.data.zero_()
434
+
435
+ def init_weights(self, pretrained=None):
436
+ if isinstance(pretrained, str):
437
+ logger = 1
438
+ #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
439
+
440
+ def reset_drop_path(self, drop_path_rate):
441
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
442
+ cur = 0
443
+ for i in range(self.depths[0]):
444
+ self.block1[i].drop_path.drop_prob = dpr[cur + i]
445
+
446
+ cur += self.depths[0]
447
+ for i in range(self.depths[1]):
448
+ self.block2[i].drop_path.drop_prob = dpr[cur + i]
449
+
450
+ cur += self.depths[1]
451
+ for i in range(self.depths[2]):
452
+ self.block3[i].drop_path.drop_prob = dpr[cur + i]
453
+
454
+ cur += self.depths[2]
455
+ for i in range(self.depths[3]):
456
+ self.block4[i].drop_path.drop_prob = dpr[cur + i]
457
+
458
+ def freeze_patch_emb(self):
459
+ self.patch_embed1.requires_grad = False
460
+
461
+ @torch.jit.ignore
462
+ def no_weight_decay(self):
463
+ return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
464
+
465
+ def get_classifier(self):
466
+ return self.head
467
+
468
+ def reset_classifier(self, num_classes, global_pool=''):
469
+ self.num_classes = num_classes
470
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
471
+
472
+ def forward_features(self, x):
473
+ B = x.shape[0]
474
+ outs = []
475
+
476
+ # stage 1
477
+ x, H, W = self.patch_embed1(x)
478
+ for i, blk in enumerate(self.block1):
479
+ x = blk(x, H, W)
480
+ x = self.norm1(x)
481
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
482
+ outs.append(x)
483
+
484
+ # stage 2
485
+ x, H, W = self.patch_embed2(x)
486
+ for i, blk in enumerate(self.block2):
487
+ x = blk(x, H, W)
488
+ x = self.norm2(x)
489
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
490
+ outs.append(x)
491
+
492
+ # stage 3
493
+ x, H, W = self.patch_embed3(x)
494
+ for i, blk in enumerate(self.block3):
495
+ x = blk(x, H, W)
496
+ x = self.norm3(x)
497
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
498
+ outs.append(x)
499
+
500
+ # stage 4
501
+ x, H, W = self.patch_embed4(x)
502
+ for i, blk in enumerate(self.block4):
503
+ x = blk(x, H, W)
504
+ x = self.norm4(x)
505
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
506
+ outs.append(x)
507
+
508
+ return outs
509
+
510
+ # return x.mean(dim=1)
511
+
512
+ def forward(self, x):
513
+ x = self.forward_features(x)
514
+ # x = self.head(x)
515
+
516
+ return x
517
+
518
+
519
+ class DWConv(nn.Module):
520
+ def __init__(self, dim=768):
521
+ super(DWConv, self).__init__()
522
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
523
+
524
+ def forward(self, x, H, W):
525
+ B, N, C = x.shape
526
+ x = x.transpose(1, 2).view(B, C, H, W).contiguous()
527
+ x = self.dwconv(x)
528
+ x = x.flatten(2).transpose(1, 2)
529
+
530
+ return x
531
+
532
+
533
+ def _conv_filter(state_dict, patch_size=16):
534
+ """ convert patch embedding weight from manual patchify + linear proj to conv"""
535
+ out_dict = {}
536
+ for k, v in state_dict.items():
537
+ if 'patch_embed.proj.weight' in k:
538
+ v = v.reshape((v.shape[0], 3, patch_size, patch_size))
539
+ out_dict[k] = v
540
+
541
+ return out_dict
542
+
543
+
544
+ ## @register_model
545
+ class pvt_v2_b0(PyramidVisionTransformerImpr):
546
+ def __init__(self, **kwargs):
547
+ super(pvt_v2_b0, self).__init__(
548
+ patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
549
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
550
+ drop_rate=0.0, drop_path_rate=0.1)
551
+
552
+
553
+
554
+ ## @register_model
555
+ class pvt_v2_b1(PyramidVisionTransformerImpr):
556
+ def __init__(self, **kwargs):
557
+ super(pvt_v2_b1, self).__init__(
558
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
559
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
560
+ drop_rate=0.0, drop_path_rate=0.1)
561
+
562
+ ## @register_model
563
+ class pvt_v2_b2(PyramidVisionTransformerImpr):
564
+ def __init__(self, in_channels=3, **kwargs):
565
+ super(pvt_v2_b2, self).__init__(
566
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
567
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],
568
+ drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
569
+
570
+ ## @register_model
571
+ class pvt_v2_b3(PyramidVisionTransformerImpr):
572
+ def __init__(self, **kwargs):
573
+ super(pvt_v2_b3, self).__init__(
574
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
575
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
576
+ drop_rate=0.0, drop_path_rate=0.1)
577
+
578
+ ## @register_model
579
+ class pvt_v2_b4(PyramidVisionTransformerImpr):
580
+ def __init__(self, **kwargs):
581
+ super(pvt_v2_b4, self).__init__(
582
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
583
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],
584
+ drop_rate=0.0, drop_path_rate=0.1)
585
+
586
+
587
+ ## @register_model
588
+ class pvt_v2_b5(PyramidVisionTransformerImpr):
589
+ def __init__(self, **kwargs):
590
+ super(pvt_v2_b5, self).__init__(
591
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
592
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
593
+ drop_rate=0.0, drop_path_rate=0.1)
594
+
595
+
596
+
597
+ ### models/backbones/swin_v1.py
598
+
599
+ # --------------------------------------------------------
600
+ # Swin Transformer
601
+ # Copyright (c) 2021 Microsoft
602
+ # Licensed under The MIT License [see LICENSE for details]
603
+ # Written by Ze Liu, Yutong Lin, Yixuan Wei
604
+ # --------------------------------------------------------
605
+
606
+ import torch
607
+ import torch.nn as nn
608
+ import torch.nn.functional as F
609
+ import torch.utils.checkpoint as checkpoint
610
+ import numpy as np
611
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
612
+
613
+ # from config import Config
614
+
615
+
616
+ # config = Config()
617
+
618
+
619
+ class Mlp(nn.Module):
620
+ """ Multilayer perceptron."""
621
+
622
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
623
+ super().__init__()
624
+ out_features = out_features or in_features
625
+ hidden_features = hidden_features or in_features
626
+ self.fc1 = nn.Linear(in_features, hidden_features)
627
+ self.act = act_layer()
628
+ self.fc2 = nn.Linear(hidden_features, out_features)
629
+ self.drop = nn.Dropout(drop)
630
+
631
+ def forward(self, x):
632
+ x = self.fc1(x)
633
+ x = self.act(x)
634
+ x = self.drop(x)
635
+ x = self.fc2(x)
636
+ x = self.drop(x)
637
+ return x
638
+
639
+
640
+ def window_partition(x, window_size):
641
+ """
642
+ Args:
643
+ x: (B, H, W, C)
644
+ window_size (int): window size
645
+
646
+ Returns:
647
+ windows: (num_windows*B, window_size, window_size, C)
648
+ """
649
+ B, H, W, C = x.shape
650
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
651
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
652
+ return windows
653
+
654
+
655
+ def window_reverse(windows, window_size, H, W):
656
+ """
657
+ Args:
658
+ windows: (num_windows*B, window_size, window_size, C)
659
+ window_size (int): Window size
660
+ H (int): Height of image
661
+ W (int): Width of image
662
+
663
+ Returns:
664
+ x: (B, H, W, C)
665
+ """
666
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
667
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
668
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
669
+ return x
670
+
671
+
672
+ class WindowAttention(nn.Module):
673
+ """ Window based multi-head self attention (W-MSA) module with relative position bias.
674
+ It supports both of shifted and non-shifted window.
675
+
676
+ Args:
677
+ dim (int): Number of input channels.
678
+ window_size (tuple[int]): The height and width of the window.
679
+ num_heads (int): Number of attention heads.
680
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
681
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
682
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
683
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
684
+ """
685
+
686
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
687
+
688
+ super().__init__()
689
+ self.dim = dim
690
+ self.window_size = window_size # Wh, Ww
691
+ self.num_heads = num_heads
692
+ head_dim = dim // num_heads
693
+ self.scale = qk_scale or head_dim ** -0.5
694
+
695
+ # define a parameter table of relative position bias
696
+ self.relative_position_bias_table = nn.Parameter(
697
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
698
+
699
+ # get pair-wise relative position index for each token inside the window
700
+ coords_h = torch.arange(self.window_size[0])
701
+ coords_w = torch.arange(self.window_size[1])
702
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww
703
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
704
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
705
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
706
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
707
+ relative_coords[:, :, 1] += self.window_size[1] - 1
708
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
709
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
710
+ self.register_buffer("relative_position_index", relative_position_index)
711
+
712
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
713
+ self.attn_drop_prob = attn_drop
714
+ self.attn_drop = nn.Dropout(attn_drop)
715
+ self.proj = nn.Linear(dim, dim)
716
+ self.proj_drop = nn.Dropout(proj_drop)
717
+
718
+ trunc_normal_(self.relative_position_bias_table, std=.02)
719
+ self.softmax = nn.Softmax(dim=-1)
720
+
721
+ def forward(self, x, mask=None):
722
+ """ Forward function.
723
+
724
+ Args:
725
+ x: input features with shape of (num_windows*B, N, C)
726
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
727
+ """
728
+ B_, N, C = x.shape
729
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
730
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
731
+
732
+ q = q * self.scale
733
+
734
+ if config.SDPA_enabled:
735
+ x = torch.nn.functional.scaled_dot_product_attention(
736
+ q, k, v,
737
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
738
+ ).transpose(1, 2).reshape(B_, N, C)
739
+ else:
740
+ attn = (q @ k.transpose(-2, -1))
741
+
742
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
743
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
744
+ ) # Wh*Ww, Wh*Ww, nH
745
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
746
+ attn = attn + relative_position_bias.unsqueeze(0)
747
+
748
+ if mask is not None:
749
+ nW = mask.shape[0]
750
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
751
+ attn = attn.view(-1, self.num_heads, N, N)
752
+ attn = self.softmax(attn)
753
+ else:
754
+ attn = self.softmax(attn)
755
+
756
+ attn = self.attn_drop(attn)
757
+
758
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
759
+ x = self.proj(x)
760
+ x = self.proj_drop(x)
761
+ return x
762
+
763
+
764
+ class SwinTransformerBlock(nn.Module):
765
+ """ Swin Transformer Block.
766
+
767
+ Args:
768
+ dim (int): Number of input channels.
769
+ num_heads (int): Number of attention heads.
770
+ window_size (int): Window size.
771
+ shift_size (int): Shift size for SW-MSA.
772
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
773
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
774
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
775
+ drop (float, optional): Dropout rate. Default: 0.0
776
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
777
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
778
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
779
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
780
+ """
781
+
782
+ def __init__(self, dim, num_heads, window_size=7, shift_size=0,
783
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
784
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
785
+ super().__init__()
786
+ self.dim = dim
787
+ self.num_heads = num_heads
788
+ self.window_size = window_size
789
+ self.shift_size = shift_size
790
+ self.mlp_ratio = mlp_ratio
791
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
792
+
793
+ self.norm1 = norm_layer(dim)
794
+ self.attn = WindowAttention(
795
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
796
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
797
+
798
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
799
+ self.norm2 = norm_layer(dim)
800
+ mlp_hidden_dim = int(dim * mlp_ratio)
801
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
802
+
803
+ self.H = None
804
+ self.W = None
805
+
806
+ def forward(self, x, mask_matrix):
807
+ """ Forward function.
808
+
809
+ Args:
810
+ x: Input feature, tensor size (B, H*W, C).
811
+ H, W: Spatial resolution of the input feature.
812
+ mask_matrix: Attention mask for cyclic shift.
813
+ """
814
+ B, L, C = x.shape
815
+ H, W = self.H, self.W
816
+ assert L == H * W, "input feature has wrong size"
817
+
818
+ shortcut = x
819
+ x = self.norm1(x)
820
+ x = x.view(B, H, W, C)
821
+
822
+ # pad feature maps to multiples of window size
823
+ pad_l = pad_t = 0
824
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
825
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
826
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
827
+ _, Hp, Wp, _ = x.shape
828
+
829
+ # cyclic shift
830
+ if self.shift_size > 0:
831
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
832
+ attn_mask = mask_matrix
833
+ else:
834
+ shifted_x = x
835
+ attn_mask = None
836
+
837
+ # partition windows
838
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
839
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
840
+
841
+ # W-MSA/SW-MSA
842
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
843
+
844
+ # merge windows
845
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
846
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
847
+
848
+ # reverse cyclic shift
849
+ if self.shift_size > 0:
850
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
851
+ else:
852
+ x = shifted_x
853
+
854
+ if pad_r > 0 or pad_b > 0:
855
+ x = x[:, :H, :W, :].contiguous()
856
+
857
+ x = x.view(B, H * W, C)
858
+
859
+ # FFN
860
+ x = shortcut + self.drop_path(x)
861
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
862
+
863
+ return x
864
+
865
+
866
+ class PatchMerging(nn.Module):
867
+ """ Patch Merging Layer
868
+
869
+ Args:
870
+ dim (int): Number of input channels.
871
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
872
+ """
873
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
874
+ super().__init__()
875
+ self.dim = dim
876
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
877
+ self.norm = norm_layer(4 * dim)
878
+
879
+ def forward(self, x, H, W):
880
+ """ Forward function.
881
+
882
+ Args:
883
+ x: Input feature, tensor size (B, H*W, C).
884
+ H, W: Spatial resolution of the input feature.
885
+ """
886
+ B, L, C = x.shape
887
+ assert L == H * W, "input feature has wrong size"
888
+
889
+ x = x.view(B, H, W, C)
890
+
891
+ # padding
892
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
893
+ if pad_input:
894
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
895
+
896
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
897
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
898
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
899
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
900
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
901
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
902
+
903
+ x = self.norm(x)
904
+ x = self.reduction(x)
905
+
906
+ return x
907
+
908
+
909
+ class BasicLayer(nn.Module):
910
+ """ A basic Swin Transformer layer for one stage.
911
+
912
+ Args:
913
+ dim (int): Number of feature channels
914
+ depth (int): Depths of this stage.
915
+ num_heads (int): Number of attention head.
916
+ window_size (int): Local window size. Default: 7.
917
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
918
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
919
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
920
+ drop (float, optional): Dropout rate. Default: 0.0
921
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
922
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
923
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
924
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
925
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
926
+ """
927
+
928
+ def __init__(self,
929
+ dim,
930
+ depth,
931
+ num_heads,
932
+ window_size=7,
933
+ mlp_ratio=4.,
934
+ qkv_bias=True,
935
+ qk_scale=None,
936
+ drop=0.,
937
+ attn_drop=0.,
938
+ drop_path=0.,
939
+ norm_layer=nn.LayerNorm,
940
+ downsample=None,
941
+ use_checkpoint=False):
942
+ super().__init__()
943
+ self.window_size = window_size
944
+ self.shift_size = window_size // 2
945
+ self.depth = depth
946
+ self.use_checkpoint = use_checkpoint
947
+
948
+ # build blocks
949
+ self.blocks = nn.ModuleList([
950
+ SwinTransformerBlock(
951
+ dim=dim,
952
+ num_heads=num_heads,
953
+ window_size=window_size,
954
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
955
+ mlp_ratio=mlp_ratio,
956
+ qkv_bias=qkv_bias,
957
+ qk_scale=qk_scale,
958
+ drop=drop,
959
+ attn_drop=attn_drop,
960
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
961
+ norm_layer=norm_layer)
962
+ for i in range(depth)])
963
+
964
+ # patch merging layer
965
+ if downsample is not None:
966
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
967
+ else:
968
+ self.downsample = None
969
+
970
+ def forward(self, x, H, W):
971
+ """ Forward function.
972
+
973
+ Args:
974
+ x: Input feature, tensor size (B, H*W, C).
975
+ H, W: Spatial resolution of the input feature.
976
+ """
977
+
978
+ # calculate attention mask for SW-MSA
979
+ # Turn int to torch.tensor for the compatiability with torch.compile in PyTorch 2.5.
980
+ Hp = torch.ceil(torch.tensor(H) / self.window_size).to(torch.int64) * self.window_size
981
+ Wp = torch.ceil(torch.tensor(W) / self.window_size).to(torch.int64) * self.window_size
982
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
983
+ h_slices = (slice(0, -self.window_size),
984
+ slice(-self.window_size, -self.shift_size),
985
+ slice(-self.shift_size, None))
986
+ w_slices = (slice(0, -self.window_size),
987
+ slice(-self.window_size, -self.shift_size),
988
+ slice(-self.shift_size, None))
989
+ cnt = 0
990
+ for h in h_slices:
991
+ for w in w_slices:
992
+ img_mask[:, h, w, :] = cnt
993
+ cnt += 1
994
+
995
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
996
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
997
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
998
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)).to(x.dtype)
999
+
1000
+ for blk in self.blocks:
1001
+ blk.H, blk.W = H, W
1002
+ if self.use_checkpoint:
1003
+ x = checkpoint.checkpoint(blk, x, attn_mask)
1004
+ else:
1005
+ x = blk(x, attn_mask)
1006
+ if self.downsample is not None:
1007
+ x_down = self.downsample(x, H, W)
1008
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
1009
+ return x, H, W, x_down, Wh, Ww
1010
+ else:
1011
+ return x, H, W, x, H, W
1012
+
1013
+
1014
+ class PatchEmbed(nn.Module):
1015
+ """ Image to Patch Embedding
1016
+
1017
+ Args:
1018
+ patch_size (int): Patch token size. Default: 4.
1019
+ in_channels (int): Number of input image channels. Default: 3.
1020
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1021
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
1022
+ """
1023
+
1024
+ def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None):
1025
+ super().__init__()
1026
+ patch_size = to_2tuple(patch_size)
1027
+ self.patch_size = patch_size
1028
+
1029
+ self.in_channels = in_channels
1030
+ self.embed_dim = embed_dim
1031
+
1032
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
1033
+ if norm_layer is not None:
1034
+ self.norm = norm_layer(embed_dim)
1035
+ else:
1036
+ self.norm = None
1037
+
1038
+ def forward(self, x):
1039
+ """Forward function."""
1040
+ # padding
1041
+ _, _, H, W = x.size()
1042
+ if W % self.patch_size[1] != 0:
1043
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
1044
+ if H % self.patch_size[0] != 0:
1045
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
1046
+
1047
+ x = self.proj(x) # B C Wh Ww
1048
+ if self.norm is not None:
1049
+ Wh, Ww = x.size(2), x.size(3)
1050
+ x = x.flatten(2).transpose(1, 2)
1051
+ x = self.norm(x)
1052
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
1053
+
1054
+ return x
1055
+
1056
+
1057
+ class SwinTransformer(nn.Module):
1058
+ """ Swin Transformer backbone.
1059
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
1060
+ https://arxiv.org/pdf/2103.14030
1061
+
1062
+ Args:
1063
+ pretrain_img_size (int): Input image size for training the pretrained model,
1064
+ used in absolute postion embedding. Default 224.
1065
+ patch_size (int | tuple(int)): Patch size. Default: 4.
1066
+ in_channels (int): Number of input image channels. Default: 3.
1067
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1068
+ depths (tuple[int]): Depths of each Swin Transformer stage.
1069
+ num_heads (tuple[int]): Number of attention head of each stage.
1070
+ window_size (int): Window size. Default: 7.
1071
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
1072
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
1073
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
1074
+ drop_rate (float): Dropout rate.
1075
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
1076
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
1077
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
1078
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
1079
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
1080
+ out_indices (Sequence[int]): Output from which stages.
1081
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
1082
+ -1 means not freezing any parameters.
1083
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
1084
+ """
1085
+
1086
+ def __init__(self,
1087
+ pretrain_img_size=224,
1088
+ patch_size=4,
1089
+ in_channels=3,
1090
+ embed_dim=96,
1091
+ depths=[2, 2, 6, 2],
1092
+ num_heads=[3, 6, 12, 24],
1093
+ window_size=7,
1094
+ mlp_ratio=4.,
1095
+ qkv_bias=True,
1096
+ qk_scale=None,
1097
+ drop_rate=0.,
1098
+ attn_drop_rate=0.,
1099
+ drop_path_rate=0.2,
1100
+ norm_layer=nn.LayerNorm,
1101
+ ape=False,
1102
+ patch_norm=True,
1103
+ out_indices=(0, 1, 2, 3),
1104
+ frozen_stages=-1,
1105
+ use_checkpoint=False):
1106
+ super().__init__()
1107
+
1108
+ self.pretrain_img_size = pretrain_img_size
1109
+ self.num_layers = len(depths)
1110
+ self.embed_dim = embed_dim
1111
+ self.ape = ape
1112
+ self.patch_norm = patch_norm
1113
+ self.out_indices = out_indices
1114
+ self.frozen_stages = frozen_stages
1115
+
1116
+ # split image into non-overlapping patches
1117
+ self.patch_embed = PatchEmbed(
1118
+ patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim,
1119
+ norm_layer=norm_layer if self.patch_norm else None)
1120
+
1121
+ # absolute position embedding
1122
+ if self.ape:
1123
+ pretrain_img_size = to_2tuple(pretrain_img_size)
1124
+ patch_size = to_2tuple(patch_size)
1125
+ patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
1126
+
1127
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
1128
+ trunc_normal_(self.absolute_pos_embed, std=.02)
1129
+
1130
+ self.pos_drop = nn.Dropout(p=drop_rate)
1131
+
1132
+ # stochastic depth
1133
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
1134
+
1135
+ # build layers
1136
+ self.layers = nn.ModuleList()
1137
+ for i_layer in range(self.num_layers):
1138
+ layer = BasicLayer(
1139
+ dim=int(embed_dim * 2 ** i_layer),
1140
+ depth=depths[i_layer],
1141
+ num_heads=num_heads[i_layer],
1142
+ window_size=window_size,
1143
+ mlp_ratio=mlp_ratio,
1144
+ qkv_bias=qkv_bias,
1145
+ qk_scale=qk_scale,
1146
+ drop=drop_rate,
1147
+ attn_drop=attn_drop_rate,
1148
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
1149
+ norm_layer=norm_layer,
1150
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
1151
+ use_checkpoint=use_checkpoint)
1152
+ self.layers.append(layer)
1153
+
1154
+ num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
1155
+ self.num_features = num_features
1156
+
1157
+ # add a norm layer for each output
1158
+ for i_layer in out_indices:
1159
+ layer = norm_layer(num_features[i_layer])
1160
+ layer_name = f'norm{i_layer}'
1161
+ self.add_module(layer_name, layer)
1162
+
1163
+ self._freeze_stages()
1164
+
1165
+ def _freeze_stages(self):
1166
+ if self.frozen_stages >= 0:
1167
+ self.patch_embed.eval()
1168
+ for param in self.patch_embed.parameters():
1169
+ param.requires_grad = False
1170
+
1171
+ if self.frozen_stages >= 1 and self.ape:
1172
+ self.absolute_pos_embed.requires_grad = False
1173
+
1174
+ if self.frozen_stages >= 2:
1175
+ self.pos_drop.eval()
1176
+ for i in range(0, self.frozen_stages - 1):
1177
+ m = self.layers[i]
1178
+ m.eval()
1179
+ for param in m.parameters():
1180
+ param.requires_grad = False
1181
+
1182
+
1183
+ def forward(self, x):
1184
+ """Forward function."""
1185
+ x = self.patch_embed(x)
1186
+
1187
+ Wh, Ww = x.size(2), x.size(3)
1188
+ if self.ape:
1189
+ # interpolate the position embedding to the corresponding size
1190
+ absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
1191
+ x = (x + absolute_pos_embed) # B Wh*Ww C
1192
+
1193
+ outs = []#x.contiguous()]
1194
+ x = x.flatten(2).transpose(1, 2)
1195
+ x = self.pos_drop(x)
1196
+ for i in range(self.num_layers):
1197
+ layer = self.layers[i]
1198
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
1199
+
1200
+ if i in self.out_indices:
1201
+ norm_layer = getattr(self, f'norm{i}')
1202
+ x_out = norm_layer(x_out)
1203
+
1204
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
1205
+ outs.append(out)
1206
+
1207
+ return tuple(outs)
1208
+
1209
+ def train(self, mode=True):
1210
+ """Convert the model into training mode while keep layers freezed."""
1211
+ super(SwinTransformer, self).train(mode)
1212
+ self._freeze_stages()
1213
+
1214
+ def swin_v1_t():
1215
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7)
1216
+ return model
1217
+
1218
+ def swin_v1_s():
1219
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7)
1220
+ return model
1221
+
1222
+ def swin_v1_b():
1223
+ model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
1224
+ return model
1225
+
1226
+ def swin_v1_l():
1227
+ model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12)
1228
+ return model
1229
+
1230
+
1231
+
1232
+ ### models/modules/deform_conv.py
1233
+
1234
+ import torch
1235
+ import torch.nn as nn
1236
+ from torchvision.ops import deform_conv2d
1237
+
1238
+
1239
+ class DeformableConv2d(nn.Module):
1240
+ def __init__(self,
1241
+ in_channels,
1242
+ out_channels,
1243
+ kernel_size=3,
1244
+ stride=1,
1245
+ padding=1,
1246
+ bias=False):
1247
+
1248
+ super(DeformableConv2d, self).__init__()
1249
+
1250
+ assert type(kernel_size) == tuple or type(kernel_size) == int
1251
+
1252
+ kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size)
1253
+ self.stride = stride if type(stride) == tuple else (stride, stride)
1254
+ self.padding = padding
1255
+
1256
+ self.offset_conv = nn.Conv2d(in_channels,
1257
+ 2 * kernel_size[0] * kernel_size[1],
1258
+ kernel_size=kernel_size,
1259
+ stride=stride,
1260
+ padding=self.padding,
1261
+ bias=True)
1262
+
1263
+ nn.init.constant_(self.offset_conv.weight, 0.)
1264
+ nn.init.constant_(self.offset_conv.bias, 0.)
1265
+
1266
+ self.modulator_conv = nn.Conv2d(in_channels,
1267
+ 1 * kernel_size[0] * kernel_size[1],
1268
+ kernel_size=kernel_size,
1269
+ stride=stride,
1270
+ padding=self.padding,
1271
+ bias=True)
1272
+
1273
+ nn.init.constant_(self.modulator_conv.weight, 0.)
1274
+ nn.init.constant_(self.modulator_conv.bias, 0.)
1275
+
1276
+ self.regular_conv = nn.Conv2d(in_channels,
1277
+ out_channels=out_channels,
1278
+ kernel_size=kernel_size,
1279
+ stride=stride,
1280
+ padding=self.padding,
1281
+ bias=bias)
1282
+
1283
+ def forward(self, x):
1284
+ #h, w = x.shape[2:]
1285
+ #max_offset = max(h, w)/4.
1286
+
1287
+ offset = self.offset_conv(x)#.clamp(-max_offset, max_offset)
1288
+ modulator = 2. * torch.sigmoid(self.modulator_conv(x))
1289
+
1290
+ x = deform_conv2d(
1291
+ input=x,
1292
+ offset=offset,
1293
+ weight=self.regular_conv.weight,
1294
+ bias=self.regular_conv.bias,
1295
+ padding=self.padding,
1296
+ mask=modulator,
1297
+ stride=self.stride,
1298
+ )
1299
+ return x
1300
+
1301
+
1302
+
1303
+
1304
+ ### utils.py
1305
+
1306
+ import torch.nn as nn
1307
+
1308
+
1309
+ def build_act_layer(act_layer):
1310
+ if act_layer == 'ReLU':
1311
+ return nn.ReLU(inplace=True)
1312
+ elif act_layer == 'SiLU':
1313
+ return nn.SiLU(inplace=True)
1314
+ elif act_layer == 'GELU':
1315
+ return nn.GELU()
1316
+
1317
+ raise NotImplementedError(f'build_act_layer does not support {act_layer}')
1318
+
1319
+
1320
+ def build_norm_layer(dim,
1321
+ norm_layer,
1322
+ in_format='channels_last',
1323
+ out_format='channels_last',
1324
+ eps=1e-6):
1325
+ layers = []
1326
+ if norm_layer == 'BN':
1327
+ if in_format == 'channels_last':
1328
+ layers.append(to_channels_first())
1329
+ layers.append(nn.BatchNorm2d(dim))
1330
+ if out_format == 'channels_last':
1331
+ layers.append(to_channels_last())
1332
+ elif norm_layer == 'LN':
1333
+ if in_format == 'channels_first':
1334
+ layers.append(to_channels_last())
1335
+ layers.append(nn.LayerNorm(dim, eps=eps))
1336
+ if out_format == 'channels_first':
1337
+ layers.append(to_channels_first())
1338
+ else:
1339
+ raise NotImplementedError(
1340
+ f'build_norm_layer does not support {norm_layer}')
1341
+ return nn.Sequential(*layers)
1342
+
1343
+
1344
+ class to_channels_first(nn.Module):
1345
+
1346
+ def __init__(self):
1347
+ super().__init__()
1348
+
1349
+ def forward(self, x):
1350
+ return x.permute(0, 3, 1, 2)
1351
+
1352
+
1353
+ class to_channels_last(nn.Module):
1354
+
1355
+ def __init__(self):
1356
+ super().__init__()
1357
+
1358
+ def forward(self, x):
1359
+ return x.permute(0, 2, 3, 1)
1360
+
1361
+
1362
+
1363
+ ### dataset.py
1364
+
1365
+ _class_labels_TR_sorted = (
1366
+ 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, '
1367
+ 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, '
1368
+ 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, '
1369
+ 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, '
1370
+ 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, '
1371
+ 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, '
1372
+ 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, '
1373
+ 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, '
1374
+ 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, '
1375
+ 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, '
1376
+ 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, '
1377
+ 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, '
1378
+ 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, '
1379
+ 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht'
1380
+ )
1381
+ class_labels_TR_sorted = _class_labels_TR_sorted.split(', ')
1382
+
1383
+
1384
+ ### models/backbones/build_backbones.py
1385
+
1386
+ import torch
1387
+ import torch.nn as nn
1388
+ from collections import OrderedDict
1389
+ from torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights
1390
+ # from models.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5
1391
+ # from models.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l
1392
+ # from config import Config
1393
+
1394
+
1395
+ config = Config()
1396
+
1397
+ def build_backbone(bb_name, pretrained=True, params_settings=''):
1398
+ if bb_name == 'vgg16':
1399
+ bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0]
1400
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]}))
1401
+ elif bb_name == 'vgg16bn':
1402
+ bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0]
1403
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]}))
1404
+ elif bb_name == 'resnet50':
1405
+ bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children())
1406
+ bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]}))
1407
+ else:
1408
+ bb = eval('{}({})'.format(bb_name, params_settings))
1409
+ if pretrained:
1410
+ bb = load_weights(bb, bb_name)
1411
+ return bb
1412
+
1413
+ def load_weights(model, model_name):
1414
+ save_model = torch.load(config.weights[model_name], map_location='cpu')
1415
+ model_dict = model.state_dict()
1416
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model.items() if k in model_dict.keys()}
1417
+ # to ignore the weights with mismatched size when I modify the backbone itself.
1418
+ if not state_dict:
1419
+ save_model_keys = list(save_model.keys())
1420
+ sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None
1421
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model[sub_item].items() if k in model_dict.keys()}
1422
+ if not state_dict or not sub_item:
1423
+ print('Weights are not successully loaded. Check the state dict of weights file.')
1424
+ return None
1425
+ else:
1426
+ print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item))
1427
+ model_dict.update(state_dict)
1428
+ model.load_state_dict(model_dict)
1429
+ return model
1430
+
1431
+
1432
+
1433
+ ### models/modules/decoder_blocks.py
1434
+
1435
+ import torch
1436
+ import torch.nn as nn
1437
+ # from models.aspp import ASPP, ASPPDeformable
1438
+ # from config import Config
1439
+
1440
+
1441
+ # config = Config()
1442
+
1443
+
1444
+ class BasicDecBlk(nn.Module):
1445
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1446
+ super(BasicDecBlk, self).__init__()
1447
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1448
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1449
+ self.relu_in = nn.ReLU(inplace=True)
1450
+ if config.dec_att == 'ASPP':
1451
+ self.dec_att = ASPP(in_channels=inter_channels)
1452
+ elif config.dec_att == 'ASPPDeformable':
1453
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1454
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1455
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1456
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1457
+
1458
+ def forward(self, x):
1459
+ x = self.conv_in(x)
1460
+ x = self.bn_in(x)
1461
+ x = self.relu_in(x)
1462
+ if hasattr(self, 'dec_att'):
1463
+ x = self.dec_att(x)
1464
+ x = self.conv_out(x)
1465
+ x = self.bn_out(x)
1466
+ return x
1467
+
1468
+
1469
+ class ResBlk(nn.Module):
1470
+ def __init__(self, in_channels=64, out_channels=None, inter_channels=64):
1471
+ super(ResBlk, self).__init__()
1472
+ if out_channels is None:
1473
+ out_channels = in_channels
1474
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1475
+
1476
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1477
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1478
+ self.relu_in = nn.ReLU(inplace=True)
1479
+
1480
+ if config.dec_att == 'ASPP':
1481
+ self.dec_att = ASPP(in_channels=inter_channels)
1482
+ elif config.dec_att == 'ASPPDeformable':
1483
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1484
+
1485
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1486
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1487
+
1488
+ self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1489
+
1490
+ def forward(self, x):
1491
+ _x = self.conv_resi(x)
1492
+ x = self.conv_in(x)
1493
+ x = self.bn_in(x)
1494
+ x = self.relu_in(x)
1495
+ if hasattr(self, 'dec_att'):
1496
+ x = self.dec_att(x)
1497
+ x = self.conv_out(x)
1498
+ x = self.bn_out(x)
1499
+ return x + _x
1500
+
1501
+
1502
+
1503
+ ### models/modules/lateral_blocks.py
1504
+
1505
+ import numpy as np
1506
+ import torch
1507
+ import torch.nn as nn
1508
+ import torch.nn.functional as F
1509
+ from functools import partial
1510
+
1511
+ # from config import Config
1512
+
1513
+
1514
+ # config = Config()
1515
+
1516
+
1517
+ class BasicLatBlk(nn.Module):
1518
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1519
+ super(BasicLatBlk, self).__init__()
1520
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1521
+ self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1522
+
1523
+ def forward(self, x):
1524
+ x = self.conv(x)
1525
+ return x
1526
+
1527
+
1528
+
1529
+ ### models/modules/aspp.py
1530
+
1531
+ import torch
1532
+ import torch.nn as nn
1533
+ import torch.nn.functional as F
1534
+ # from models.deform_conv import DeformableConv2d
1535
+ # from config import Config
1536
+
1537
+
1538
+ # config = Config()
1539
+
1540
+
1541
+ class _ASPPModule(nn.Module):
1542
+ def __init__(self, in_channels, planes, kernel_size, padding, dilation):
1543
+ super(_ASPPModule, self).__init__()
1544
+ self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size,
1545
+ stride=1, padding=padding, dilation=dilation, bias=False)
1546
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1547
+ self.relu = nn.ReLU(inplace=True)
1548
+
1549
+ def forward(self, x):
1550
+ x = self.atrous_conv(x)
1551
+ x = self.bn(x)
1552
+
1553
+ return self.relu(x)
1554
+
1555
+
1556
+ class ASPP(nn.Module):
1557
+ def __init__(self, in_channels=64, out_channels=None, output_stride=16):
1558
+ super(ASPP, self).__init__()
1559
+ self.down_scale = 1
1560
+ if out_channels is None:
1561
+ out_channels = in_channels
1562
+ self.in_channelster = 256 // self.down_scale
1563
+ if output_stride == 16:
1564
+ dilations = [1, 6, 12, 18]
1565
+ elif output_stride == 8:
1566
+ dilations = [1, 12, 24, 36]
1567
+ else:
1568
+ raise NotImplementedError
1569
+
1570
+ self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0])
1571
+ self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1])
1572
+ self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2])
1573
+ self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3])
1574
+
1575
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1576
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1577
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1578
+ nn.ReLU(inplace=True))
1579
+ self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False)
1580
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1581
+ self.relu = nn.ReLU(inplace=True)
1582
+ self.dropout = nn.Dropout(0.5)
1583
+
1584
+ def forward(self, x):
1585
+ x1 = self.aspp1(x)
1586
+ x2 = self.aspp2(x)
1587
+ x3 = self.aspp3(x)
1588
+ x4 = self.aspp4(x)
1589
+ x5 = self.global_avg_pool(x)
1590
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1591
+ x = torch.cat((x1, x2, x3, x4, x5), dim=1)
1592
+
1593
+ x = self.conv1(x)
1594
+ x = self.bn1(x)
1595
+ x = self.relu(x)
1596
+
1597
+ return self.dropout(x)
1598
+
1599
+
1600
+ ##################### Deformable
1601
+ class _ASPPModuleDeformable(nn.Module):
1602
+ def __init__(self, in_channels, planes, kernel_size, padding):
1603
+ super(_ASPPModuleDeformable, self).__init__()
1604
+ self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size,
1605
+ stride=1, padding=padding, bias=False)
1606
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1607
+ self.relu = nn.ReLU(inplace=True)
1608
+
1609
+ def forward(self, x):
1610
+ x = self.atrous_conv(x)
1611
+ x = self.bn(x)
1612
+
1613
+ return self.relu(x)
1614
+
1615
+
1616
+ class ASPPDeformable(nn.Module):
1617
+ def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]):
1618
+ super(ASPPDeformable, self).__init__()
1619
+ self.down_scale = 1
1620
+ if out_channels is None:
1621
+ out_channels = in_channels
1622
+ self.in_channelster = 256 // self.down_scale
1623
+
1624
+ self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0)
1625
+ self.aspp_deforms = nn.ModuleList([
1626
+ _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes
1627
+ ])
1628
+
1629
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1630
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1631
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1632
+ nn.ReLU(inplace=True))
1633
+ self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False)
1634
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1635
+ self.relu = nn.ReLU(inplace=True)
1636
+ self.dropout = nn.Dropout(0.5)
1637
+
1638
+ def forward(self, x):
1639
+ x1 = self.aspp1(x)
1640
+ x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms]
1641
+ x5 = self.global_avg_pool(x)
1642
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1643
+ x = torch.cat((x1, *x_aspp_deforms, x5), dim=1)
1644
+
1645
+ x = self.conv1(x)
1646
+ x = self.bn1(x)
1647
+ x = self.relu(x)
1648
+
1649
+ return self.dropout(x)
1650
+
1651
+
1652
+
1653
+ ### models/refinement/refiner.py
1654
+
1655
+ import torch
1656
+ import torch.nn as nn
1657
+ from collections import OrderedDict
1658
+ import torch
1659
+ import torch.nn as nn
1660
+ import torch.nn.functional as F
1661
+ from torchvision.models import vgg16, vgg16_bn
1662
+ from torchvision.models import resnet50
1663
+
1664
+ # from config import Config
1665
+ # from dataset import class_labels_TR_sorted
1666
+ # from models.build_backbone import build_backbone
1667
+ # from models.decoder_blocks import BasicDecBlk
1668
+ # from models.lateral_blocks import BasicLatBlk
1669
+ # from models.ing import *
1670
+ # from models.stem_layer import StemLayer
1671
+
1672
+
1673
+ class RefinerPVTInChannels4(nn.Module):
1674
+ def __init__(self, in_channels=3+1):
1675
+ super(RefinerPVTInChannels4, self).__init__()
1676
+ self.config = Config()
1677
+ self.epoch = 1
1678
+ self.bb = build_backbone(self.config.bb, params_settings='in_channels=4')
1679
+
1680
+ lateral_channels_in_collection = {
1681
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1682
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1683
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1684
+ }
1685
+ channels = lateral_channels_in_collection[self.config.bb]
1686
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1687
+
1688
+ self.decoder = Decoder(channels)
1689
+
1690
+ if 0:
1691
+ for key, value in self.named_parameters():
1692
+ if 'bb.' in key:
1693
+ value.requires_grad = False
1694
+
1695
+ def forward(self, x):
1696
+ if isinstance(x, list):
1697
+ x = torch.cat(x, dim=1)
1698
+ ########## Encoder ##########
1699
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1700
+ x1 = self.bb.conv1(x)
1701
+ x2 = self.bb.conv2(x1)
1702
+ x3 = self.bb.conv3(x2)
1703
+ x4 = self.bb.conv4(x3)
1704
+ else:
1705
+ x1, x2, x3, x4 = self.bb(x)
1706
+
1707
+ x4 = self.squeeze_module(x4)
1708
+
1709
+ ########## Decoder ##########
1710
+
1711
+ features = [x, x1, x2, x3, x4]
1712
+ scaled_preds = self.decoder(features)
1713
+
1714
+ return scaled_preds
1715
+
1716
+
1717
+ class Refiner(nn.Module):
1718
+ def __init__(self, in_channels=3+1):
1719
+ super(Refiner, self).__init__()
1720
+ self.config = Config()
1721
+ self.epoch = 1
1722
+ self.stem_layer = StemLayer(in_channels=in_channels, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
1723
+ self.bb = build_backbone(self.config.bb)
1724
+
1725
+ lateral_channels_in_collection = {
1726
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1727
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1728
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1729
+ }
1730
+ channels = lateral_channels_in_collection[self.config.bb]
1731
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1732
+
1733
+ self.decoder = Decoder(channels)
1734
+
1735
+ if 0:
1736
+ for key, value in self.named_parameters():
1737
+ if 'bb.' in key:
1738
+ value.requires_grad = False
1739
+
1740
+ def forward(self, x):
1741
+ if isinstance(x, list):
1742
+ x = torch.cat(x, dim=1)
1743
+ x = self.stem_layer(x)
1744
+ ########## Encoder ##########
1745
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1746
+ x1 = self.bb.conv1(x)
1747
+ x2 = self.bb.conv2(x1)
1748
+ x3 = self.bb.conv3(x2)
1749
+ x4 = self.bb.conv4(x3)
1750
+ else:
1751
+ x1, x2, x3, x4 = self.bb(x)
1752
+
1753
+ x4 = self.squeeze_module(x4)
1754
+
1755
+ ########## Decoder ##########
1756
+
1757
+ features = [x, x1, x2, x3, x4]
1758
+ scaled_preds = self.decoder(features)
1759
+
1760
+ return scaled_preds
1761
+
1762
+
1763
+ class Decoder(nn.Module):
1764
+ def __init__(self, channels):
1765
+ super(Decoder, self).__init__()
1766
+ self.config = Config()
1767
+ DecoderBlock = eval('BasicDecBlk')
1768
+ LateralBlock = eval('BasicLatBlk')
1769
+
1770
+ self.decoder_block4 = DecoderBlock(channels[0], channels[1])
1771
+ self.decoder_block3 = DecoderBlock(channels[1], channels[2])
1772
+ self.decoder_block2 = DecoderBlock(channels[2], channels[3])
1773
+ self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2)
1774
+
1775
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
1776
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
1777
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
1778
+
1779
+ if self.config.ms_supervision:
1780
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
1781
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
1782
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
1783
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0))
1784
+
1785
+ def forward(self, features):
1786
+ x, x1, x2, x3, x4 = features
1787
+ outs = []
1788
+ p4 = self.decoder_block4(x4)
1789
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
1790
+ _p3 = _p4 + self.lateral_block4(x3)
1791
+
1792
+ p3 = self.decoder_block3(_p3)
1793
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
1794
+ _p2 = _p3 + self.lateral_block3(x2)
1795
+
1796
+ p2 = self.decoder_block2(_p2)
1797
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
1798
+ _p1 = _p2 + self.lateral_block2(x1)
1799
+
1800
+ _p1 = self.decoder_block1(_p1)
1801
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
1802
+ p1_out = self.conv_out1(_p1)
1803
+
1804
+ if self.config.ms_supervision:
1805
+ outs.append(self.conv_ms_spvn_4(p4))
1806
+ outs.append(self.conv_ms_spvn_3(p3))
1807
+ outs.append(self.conv_ms_spvn_2(p2))
1808
+ outs.append(p1_out)
1809
+ return outs
1810
+
1811
+
1812
+ class RefUNet(nn.Module):
1813
+ # Refinement
1814
+ def __init__(self, in_channels=3+1):
1815
+ super(RefUNet, self).__init__()
1816
+ self.encoder_1 = nn.Sequential(
1817
+ nn.Conv2d(in_channels, 64, 3, 1, 1),
1818
+ nn.Conv2d(64, 64, 3, 1, 1),
1819
+ nn.BatchNorm2d(64),
1820
+ nn.ReLU(inplace=True)
1821
+ )
1822
+
1823
+ self.encoder_2 = nn.Sequential(
1824
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1825
+ nn.Conv2d(64, 64, 3, 1, 1),
1826
+ nn.BatchNorm2d(64),
1827
+ nn.ReLU(inplace=True)
1828
+ )
1829
+
1830
+ self.encoder_3 = nn.Sequential(
1831
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1832
+ nn.Conv2d(64, 64, 3, 1, 1),
1833
+ nn.BatchNorm2d(64),
1834
+ nn.ReLU(inplace=True)
1835
+ )
1836
+
1837
+ self.encoder_4 = nn.Sequential(
1838
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1839
+ nn.Conv2d(64, 64, 3, 1, 1),
1840
+ nn.BatchNorm2d(64),
1841
+ nn.ReLU(inplace=True)
1842
+ )
1843
+
1844
+ self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True)
1845
+ #####
1846
+ self.decoder_5 = nn.Sequential(
1847
+ nn.Conv2d(64, 64, 3, 1, 1),
1848
+ nn.BatchNorm2d(64),
1849
+ nn.ReLU(inplace=True)
1850
+ )
1851
+ #####
1852
+ self.decoder_4 = nn.Sequential(
1853
+ nn.Conv2d(128, 64, 3, 1, 1),
1854
+ nn.BatchNorm2d(64),
1855
+ nn.ReLU(inplace=True)
1856
+ )
1857
+
1858
+ self.decoder_3 = nn.Sequential(
1859
+ nn.Conv2d(128, 64, 3, 1, 1),
1860
+ nn.BatchNorm2d(64),
1861
+ nn.ReLU(inplace=True)
1862
+ )
1863
+
1864
+ self.decoder_2 = nn.Sequential(
1865
+ nn.Conv2d(128, 64, 3, 1, 1),
1866
+ nn.BatchNorm2d(64),
1867
+ nn.ReLU(inplace=True)
1868
+ )
1869
+
1870
+ self.decoder_1 = nn.Sequential(
1871
+ nn.Conv2d(128, 64, 3, 1, 1),
1872
+ nn.BatchNorm2d(64),
1873
+ nn.ReLU(inplace=True)
1874
+ )
1875
+
1876
+ self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1)
1877
+
1878
+ self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
1879
+
1880
+ def forward(self, x):
1881
+ outs = []
1882
+ if isinstance(x, list):
1883
+ x = torch.cat(x, dim=1)
1884
+ hx = x
1885
+
1886
+ hx1 = self.encoder_1(hx)
1887
+ hx2 = self.encoder_2(hx1)
1888
+ hx3 = self.encoder_3(hx2)
1889
+ hx4 = self.encoder_4(hx3)
1890
+
1891
+ hx = self.decoder_5(self.pool4(hx4))
1892
+ hx = torch.cat((self.upscore2(hx), hx4), 1)
1893
+
1894
+ d4 = self.decoder_4(hx)
1895
+ hx = torch.cat((self.upscore2(d4), hx3), 1)
1896
+
1897
+ d3 = self.decoder_3(hx)
1898
+ hx = torch.cat((self.upscore2(d3), hx2), 1)
1899
+
1900
+ d2 = self.decoder_2(hx)
1901
+ hx = torch.cat((self.upscore2(d2), hx1), 1)
1902
+
1903
+ d1 = self.decoder_1(hx)
1904
+
1905
+ x = self.conv_d0(d1)
1906
+ outs.append(x)
1907
+ return outs
1908
+
1909
+
1910
+
1911
+ ### models/stem_layer.py
1912
+
1913
+ import torch.nn as nn
1914
+ # from utils import build_act_layer, build_norm_layer
1915
+
1916
+
1917
+ class StemLayer(nn.Module):
1918
+ r""" Stem layer of InternImage
1919
+ Args:
1920
+ in_channels (int): number of input channels
1921
+ out_channels (int): number of output channels
1922
+ act_layer (str): activation layer
1923
+ norm_layer (str): normalization layer
1924
+ """
1925
+
1926
+ def __init__(self,
1927
+ in_channels=3+1,
1928
+ inter_channels=48,
1929
+ out_channels=96,
1930
+ act_layer='GELU',
1931
+ norm_layer='BN'):
1932
+ super().__init__()
1933
+ self.conv1 = nn.Conv2d(in_channels,
1934
+ inter_channels,
1935
+ kernel_size=3,
1936
+ stride=1,
1937
+ padding=1)
1938
+ self.norm1 = build_norm_layer(
1939
+ inter_channels, norm_layer, 'channels_first', 'channels_first'
1940
+ )
1941
+ self.act = build_act_layer(act_layer)
1942
+ self.conv2 = nn.Conv2d(inter_channels,
1943
+ out_channels,
1944
+ kernel_size=3,
1945
+ stride=1,
1946
+ padding=1)
1947
+ self.norm2 = build_norm_layer(
1948
+ out_channels, norm_layer, 'channels_first', 'channels_first'
1949
+ )
1950
+
1951
+ def forward(self, x):
1952
+ x = self.conv1(x)
1953
+ x = self.norm1(x)
1954
+ x = self.act(x)
1955
+ x = self.conv2(x)
1956
+ x = self.norm2(x)
1957
+ return x
1958
+
1959
+
1960
+ ### models/birefnet.py
1961
+
1962
+ import torch
1963
+ import torch.nn as nn
1964
+ import torch.nn.functional as F
1965
+ from kornia.filters import laplacian
1966
+ from transformers import PreTrainedModel
1967
+ from einops import rearrange
1968
+
1969
+ # from config import Config
1970
+ # from dataset import class_labels_TR_sorted
1971
+ # from models.build_backbone import build_backbone
1972
+ # from models.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk
1973
+ # from models.lateral_blocks import BasicLatBlk
1974
+ # from models.aspp import ASPP, ASPPDeformable
1975
+ # from models.ing import *
1976
+ # from models.refiner import Refiner, RefinerPVTInChannels4, RefUNet
1977
+ # from models.stem_layer import StemLayer
1978
+ from BiRefNet_config import BiRefNetConfig
1979
+
1980
+
1981
+ def image2patches(image, grid_h=2, grid_w=2, patch_ref=None, transformation='b c (hg h) (wg w) -> (b hg wg) c h w'):
1982
+ if patch_ref is not None:
1983
+ grid_h, grid_w = image.shape[-2] // patch_ref.shape[-2], image.shape[-1] // patch_ref.shape[-1]
1984
+ patches = rearrange(image, transformation, hg=grid_h, wg=grid_w)
1985
+ return patches
1986
+
1987
+ def patches2image(patches, grid_h=2, grid_w=2, patch_ref=None, transformation='(b hg wg) c h w -> b c (hg h) (wg w)'):
1988
+ if patch_ref is not None:
1989
+ grid_h, grid_w = patch_ref.shape[-2] // patches[0].shape[-2], patch_ref.shape[-1] // patches[0].shape[-1]
1990
+ image = rearrange(patches, transformation, hg=grid_h, wg=grid_w)
1991
+ return image
1992
+
1993
+ class BiRefNet(
1994
+ PreTrainedModel
1995
+ ):
1996
+ config_class = BiRefNetConfig
1997
+ def __init__(self, bb_pretrained=True, config=BiRefNetConfig()):
1998
+ super(BiRefNet, self).__init__(config)
1999
+ bb_pretrained = config.bb_pretrained
2000
+ self.config = Config()
2001
+ self.epoch = 1
2002
+ self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained)
2003
+
2004
+ channels = self.config.lateral_channels_in_collection
2005
+
2006
+ if self.config.auxiliary_classification:
2007
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
2008
+ self.cls_head = nn.Sequential(
2009
+ nn.Linear(channels[0], len(class_labels_TR_sorted))
2010
+ )
2011
+
2012
+ if self.config.squeeze_block:
2013
+ self.squeeze_module = nn.Sequential(*[
2014
+ eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0])
2015
+ for _ in range(eval(self.config.squeeze_block.split('_x')[1]))
2016
+ ])
2017
+
2018
+ self.decoder = Decoder(channels)
2019
+
2020
+ if self.config.ender:
2021
+ self.dec_end = nn.Sequential(
2022
+ nn.Conv2d(1, 16, 3, 1, 1),
2023
+ nn.Conv2d(16, 1, 3, 1, 1),
2024
+ nn.ReLU(inplace=True),
2025
+ )
2026
+
2027
+ # refine patch-level segmentation
2028
+ if self.config.refine:
2029
+ if self.config.refine == 'itself':
2030
+ self.stem_layer = StemLayer(in_channels=3+1, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
2031
+ else:
2032
+ self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1'))
2033
+
2034
+ if self.config.freeze_bb:
2035
+ # Freeze the backbone...
2036
+ print(self.named_parameters())
2037
+ for key, value in self.named_parameters():
2038
+ if 'bb.' in key and 'refiner.' not in key:
2039
+ value.requires_grad = False
2040
+
2041
+ def forward_enc(self, x):
2042
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
2043
+ x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3)
2044
+ else:
2045
+ x1, x2, x3, x4 = self.bb(x)
2046
+ if self.config.mul_scl_ipt == 'cat':
2047
+ B, C, H, W = x.shape
2048
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2049
+ x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2050
+ x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2051
+ x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2052
+ x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2053
+ elif self.config.mul_scl_ipt == 'add':
2054
+ B, C, H, W = x.shape
2055
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2056
+ x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)
2057
+ x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)
2058
+ x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)
2059
+ x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)
2060
+ class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None
2061
+ if self.config.cxt:
2062
+ x4 = torch.cat(
2063
+ (
2064
+ *[
2065
+ F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True),
2066
+ F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True),
2067
+ F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True),
2068
+ ][-len(self.config.cxt):],
2069
+ x4
2070
+ ),
2071
+ dim=1
2072
+ )
2073
+ return (x1, x2, x3, x4), class_preds
2074
+
2075
+ def forward_ori(self, x):
2076
+ ########## Encoder ##########
2077
+ (x1, x2, x3, x4), class_preds = self.forward_enc(x)
2078
+ if self.config.squeeze_block:
2079
+ x4 = self.squeeze_module(x4)
2080
+ ########## Decoder ##########
2081
+ features = [x, x1, x2, x3, x4]
2082
+ if self.training and self.config.out_ref:
2083
+ features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5))
2084
+ scaled_preds = self.decoder(features)
2085
+ return scaled_preds, class_preds
2086
+
2087
+ def forward(self, x):
2088
+ scaled_preds, class_preds = self.forward_ori(x)
2089
+ class_preds_lst = [class_preds]
2090
+ return [scaled_preds, class_preds_lst] if self.training else scaled_preds
2091
+
2092
+
2093
+ class Decoder(nn.Module):
2094
+ def __init__(self, channels):
2095
+ super(Decoder, self).__init__()
2096
+ self.config = Config()
2097
+ DecoderBlock = eval(self.config.dec_blk)
2098
+ LateralBlock = eval(self.config.lat_blk)
2099
+
2100
+ if self.config.dec_ipt:
2101
+ self.split = self.config.dec_ipt_split
2102
+ N_dec_ipt = 64
2103
+ DBlock = SimpleConvs
2104
+ ic = 64
2105
+ ipt_cha_opt = 1
2106
+ self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2107
+ self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2108
+ self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic)
2109
+ self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic)
2110
+ self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic)
2111
+ else:
2112
+ self.split = None
2113
+
2114
+ self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1])
2115
+ self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2])
2116
+ self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3])
2117
+ self.decoder_block1 = DecoderBlock(channels[3]+([N_dec_ipt, channels[2]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]//2)
2118
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2+([N_dec_ipt, channels[3]//8][ipt_cha_opt] if self.config.dec_ipt else 0), 1, 1, 1, 0))
2119
+
2120
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
2121
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
2122
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
2123
+
2124
+ if self.config.ms_supervision:
2125
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
2126
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
2127
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
2128
+
2129
+ if self.config.out_ref:
2130
+ _N = 16
2131
+ self.gdt_convs_4 = nn.Sequential(nn.Conv2d(channels[1], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2132
+ self.gdt_convs_3 = nn.Sequential(nn.Conv2d(channels[2], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2133
+ self.gdt_convs_2 = nn.Sequential(nn.Conv2d(channels[3], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2134
+
2135
+ self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2136
+ self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2137
+ self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2138
+
2139
+ self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2140
+ self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2141
+ self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2142
+
2143
+ def forward(self, features):
2144
+ if self.training and self.config.out_ref:
2145
+ outs_gdt_pred = []
2146
+ outs_gdt_label = []
2147
+ x, x1, x2, x3, x4, gdt_gt = features
2148
+ else:
2149
+ x, x1, x2, x3, x4 = features
2150
+ outs = []
2151
+
2152
+ if self.config.dec_ipt:
2153
+ patches_batch = image2patches(x, patch_ref=x4, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2154
+ x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1)
2155
+ p4 = self.decoder_block4(x4)
2156
+ m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision and self.training else None
2157
+ if self.config.out_ref:
2158
+ p4_gdt = self.gdt_convs_4(p4)
2159
+ if self.training:
2160
+ # >> GT:
2161
+ m4_dia = m4
2162
+ gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2163
+ outs_gdt_label.append(gdt_label_main_4)
2164
+ # >> Pred:
2165
+ gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt)
2166
+ outs_gdt_pred.append(gdt_pred_4)
2167
+ gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid()
2168
+ # >> Finally:
2169
+ p4 = p4 * gdt_attn_4
2170
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
2171
+ _p3 = _p4 + self.lateral_block4(x3)
2172
+
2173
+ if self.config.dec_ipt:
2174
+ patches_batch = image2patches(x, patch_ref=_p3, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2175
+ _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1)
2176
+ p3 = self.decoder_block3(_p3)
2177
+ m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision and self.training else None
2178
+ if self.config.out_ref:
2179
+ p3_gdt = self.gdt_convs_3(p3)
2180
+ if self.training:
2181
+ # >> GT:
2182
+ # m3 --dilation--> m3_dia
2183
+ # G_3^gt * m3_dia --> G_3^m, which is the label of gradient
2184
+ m3_dia = m3
2185
+ gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2186
+ outs_gdt_label.append(gdt_label_main_3)
2187
+ # >> Pred:
2188
+ # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx
2189
+ # F_3^G --sigmoid--> A_3^G
2190
+ gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt)
2191
+ outs_gdt_pred.append(gdt_pred_3)
2192
+ gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid()
2193
+ # >> Finally:
2194
+ # p3 = p3 * A_3^G
2195
+ p3 = p3 * gdt_attn_3
2196
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
2197
+ _p2 = _p3 + self.lateral_block3(x2)
2198
+
2199
+ if self.config.dec_ipt:
2200
+ patches_batch = image2patches(x, patch_ref=_p2, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2201
+ _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1)
2202
+ p2 = self.decoder_block2(_p2)
2203
+ m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision and self.training else None
2204
+ if self.config.out_ref:
2205
+ p2_gdt = self.gdt_convs_2(p2)
2206
+ if self.training:
2207
+ # >> GT:
2208
+ m2_dia = m2
2209
+ gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2210
+ outs_gdt_label.append(gdt_label_main_2)
2211
+ # >> Pred:
2212
+ gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt)
2213
+ outs_gdt_pred.append(gdt_pred_2)
2214
+ gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid()
2215
+ # >> Finally:
2216
+ p2 = p2 * gdt_attn_2
2217
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
2218
+ _p1 = _p2 + self.lateral_block2(x1)
2219
+
2220
+ if self.config.dec_ipt:
2221
+ patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2222
+ _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1)
2223
+ _p1 = self.decoder_block1(_p1)
2224
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
2225
+
2226
+ if self.config.dec_ipt:
2227
+ patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2228
+ _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1)
2229
+ p1_out = self.conv_out1(_p1)
2230
+
2231
+ if self.config.ms_supervision and self.training:
2232
+ outs.append(m4)
2233
+ outs.append(m3)
2234
+ outs.append(m2)
2235
+ outs.append(p1_out)
2236
+ return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs)
2237
+
2238
+
2239
+ class SimpleConvs(nn.Module):
2240
+ def __init__(
2241
+ self, in_channels: int, out_channels: int, inter_channels=64
2242
+ ) -> None:
2243
+ super().__init__()
2244
+ self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1)
2245
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
2246
+
2247
+ def forward(self, x):
2248
+ return self.conv_out(self.conv1(x))
models/RMBG/BiRefNet/birefnet_lite.py ADDED
@@ -0,0 +1,2248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### config.py
2
+
3
+ import os
4
+ import math
5
+
6
+
7
+ class Config():
8
+ def __init__(self) -> None:
9
+ # PATH settings
10
+ self.sys_home_dir = os.path.expanduser('~') # Make up your file system as: SYS_HOME_DIR/codes/dis/BiRefNet, SYS_HOME_DIR/datasets/dis/xx, SYS_HOME_DIR/weights/xx
11
+
12
+ # TASK settings
13
+ self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0]
14
+ self.training_set = {
15
+ 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0],
16
+ 'COD': 'TR-COD10K+TR-CAMO',
17
+ 'HRSOD': ['TR-DUTS', 'TR-HRSOD', 'TR-UHRSD', 'TR-DUTS+TR-HRSOD', 'TR-DUTS+TR-UHRSD', 'TR-HRSOD+TR-UHRSD', 'TR-DUTS+TR-HRSOD+TR-UHRSD'][5],
18
+ 'DIS5K+HRSOD+HRS10K': 'DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4+DIS-TR+TE-HRS10K+TE-HRSOD+TE-UHRSD+TR-HRS10K+TR-HRSOD+TR-UHRSD', # leave DIS-VD for evaluation.
19
+ 'P3M-10k': 'TR-P3M-10k',
20
+ }[self.task]
21
+ self.prompt4loc = ['dense', 'sparse'][0]
22
+
23
+ # Faster-Training settings
24
+ self.load_all = True
25
+ self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch.
26
+ # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting.
27
+ # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607.
28
+ # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training.
29
+ self.precisionHigh = True
30
+
31
+ # MODEL settings
32
+ self.ms_supervision = True
33
+ self.out_ref = self.ms_supervision and True
34
+ self.dec_ipt = True
35
+ self.dec_ipt_split = True
36
+ self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder
37
+ self.mul_scl_ipt = ['', 'add', 'cat'][2]
38
+ self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2]
39
+ self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1]
40
+ self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]
41
+
42
+ # TRAINING settings
43
+ self.batch_size = 4
44
+ self.IoU_finetune_last_epochs = [
45
+ 0,
46
+ {
47
+ 'DIS5K': -50,
48
+ 'COD': -20,
49
+ 'HRSOD': -20,
50
+ 'DIS5K+HRSOD+HRS10K': -20,
51
+ 'P3M-10k': -20,
52
+ }[self.task]
53
+ ][1] # choose 0 to skip
54
+ self.lr = (1e-4 if 'DIS5K' in self.task else 1e-5) * math.sqrt(self.batch_size / 4) # DIS needs high lr to converge faster. Adapt the lr linearly
55
+ self.size = 1024
56
+ self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader
57
+
58
+ # Backbone settings
59
+ self.bb = [
60
+ 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2
61
+ 'swin_v1_t', 'swin_v1_s', # 3, 4
62
+ 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4
63
+ 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8
64
+ 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5
65
+ ][3]
66
+ self.lateral_channels_in_collection = {
67
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
68
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
69
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
70
+ 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96],
71
+ 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64],
72
+ }[self.bb]
73
+ if self.mul_scl_ipt == 'cat':
74
+ self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection]
75
+ self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
76
+
77
+ # MODEL settings - inactive
78
+ self.lat_blk = ['BasicLatBlk'][0]
79
+ self.dec_channels_inter = ['fixed', 'adap'][0]
80
+ self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0]
81
+ self.progressive_ref = self.refine and True
82
+ self.ender = self.progressive_ref and False
83
+ self.scale = self.progressive_ref and 2
84
+ self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`.
85
+ self.refine_iteration = 1
86
+ self.freeze_bb = False
87
+ self.model = [
88
+ 'BiRefNet',
89
+ ][0]
90
+ if self.dec_blk == 'HierarAttDecBlk':
91
+ self.batch_size = 2 ** [0, 1, 2, 3, 4][2]
92
+
93
+ # TRAINING settings - inactive
94
+ self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4]
95
+ self.optimizer = ['Adam', 'AdamW'][1]
96
+ self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch.
97
+ self.lr_decay_rate = 0.5
98
+ # Loss
99
+ self.lambdas_pix_last = {
100
+ # not 0 means opening this loss
101
+ # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30
102
+ 'bce': 30 * 1, # high performance
103
+ 'iou': 0.5 * 1, # 0 / 255
104
+ 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64)
105
+ 'mse': 150 * 0, # can smooth the saliency map
106
+ 'triplet': 3 * 0,
107
+ 'reg': 100 * 0,
108
+ 'ssim': 10 * 1, # help contours,
109
+ 'cnt': 5 * 0, # help contours
110
+ 'structure': 5 * 0, # structure loss from codes of MVANet. A little improvement on DIS-TE[1,2,3], a bit more decrease on DIS-TE4.
111
+ }
112
+ self.lambdas_cls = {
113
+ 'ce': 5.0
114
+ }
115
+ # Adv
116
+ self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training
117
+ self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)
118
+
119
+ # PATH settings - inactive
120
+ self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis')
121
+ self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights')
122
+ self.weights = {
123
+ 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'),
124
+ 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]),
125
+ 'swin_v1_b': os.path.join(self.weights_root_dir, ['swin_base_patch4_window12_384_22kto1k.pth', 'swin_base_patch4_window12_384_22k.pth'][0]),
126
+ 'swin_v1_l': os.path.join(self.weights_root_dir, ['swin_large_patch4_window12_384_22kto1k.pth', 'swin_large_patch4_window12_384_22k.pth'][0]),
127
+ 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]),
128
+ 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]),
129
+ 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]),
130
+ 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]),
131
+ }
132
+
133
+ # Callbacks - inactive
134
+ self.verbose_eval = True
135
+ self.only_S_MAE = False
136
+ self.use_fp16 = False # Bugs. It may cause nan in training.
137
+ self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs
138
+
139
+ # others
140
+ self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
141
+
142
+ self.batch_size_valid = 1
143
+ self.rand_seed = 7
144
+ # run_sh_file = [f for f in os.listdir('.') if 'train.sh' == f] + [os.path.join('..', f) for f in os.listdir('..') if 'train.sh' == f]
145
+ # with open(run_sh_file[0], 'r') as f:
146
+ # lines = f.readlines()
147
+ # self.save_last = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'val_last=' in l][0].split('val_last=')[-1].split()[0])
148
+ # self.save_step = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'step=' in l][0].split('step=')[-1].split()[0])
149
+ # self.val_step = [0, self.save_step][0]
150
+
151
+ def print_task(self) -> None:
152
+ # Return task for choosing settings in shell scripts.
153
+ print(self.task)
154
+
155
+
156
+
157
+ ### models/backbones/pvt_v2.py
158
+
159
+ import torch
160
+ import torch.nn as nn
161
+ from functools import partial
162
+
163
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
164
+ from timm.models.registry import register_model
165
+
166
+ import math
167
+
168
+ # from config import Config
169
+
170
+ # config = Config()
171
+
172
+ class Mlp(nn.Module):
173
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
174
+ super().__init__()
175
+ out_features = out_features or in_features
176
+ hidden_features = hidden_features or in_features
177
+ self.fc1 = nn.Linear(in_features, hidden_features)
178
+ self.dwconv = DWConv(hidden_features)
179
+ self.act = act_layer()
180
+ self.fc2 = nn.Linear(hidden_features, out_features)
181
+ self.drop = nn.Dropout(drop)
182
+
183
+ self.apply(self._init_weights)
184
+
185
+ def _init_weights(self, m):
186
+ if isinstance(m, nn.Linear):
187
+ trunc_normal_(m.weight, std=.02)
188
+ if isinstance(m, nn.Linear) and m.bias is not None:
189
+ nn.init.constant_(m.bias, 0)
190
+ elif isinstance(m, nn.LayerNorm):
191
+ nn.init.constant_(m.bias, 0)
192
+ nn.init.constant_(m.weight, 1.0)
193
+ elif isinstance(m, nn.Conv2d):
194
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
195
+ fan_out //= m.groups
196
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
197
+ if m.bias is not None:
198
+ m.bias.data.zero_()
199
+
200
+ def forward(self, x, H, W):
201
+ x = self.fc1(x)
202
+ x = self.dwconv(x, H, W)
203
+ x = self.act(x)
204
+ x = self.drop(x)
205
+ x = self.fc2(x)
206
+ x = self.drop(x)
207
+ return x
208
+
209
+
210
+ class Attention(nn.Module):
211
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
212
+ super().__init__()
213
+ assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
214
+
215
+ self.dim = dim
216
+ self.num_heads = num_heads
217
+ head_dim = dim // num_heads
218
+ self.scale = qk_scale or head_dim ** -0.5
219
+
220
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
221
+ self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
222
+ self.attn_drop_prob = attn_drop
223
+ self.attn_drop = nn.Dropout(attn_drop)
224
+ self.proj = nn.Linear(dim, dim)
225
+ self.proj_drop = nn.Dropout(proj_drop)
226
+
227
+ self.sr_ratio = sr_ratio
228
+ if sr_ratio > 1:
229
+ self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
230
+ self.norm = nn.LayerNorm(dim)
231
+
232
+ self.apply(self._init_weights)
233
+
234
+ def _init_weights(self, m):
235
+ if isinstance(m, nn.Linear):
236
+ trunc_normal_(m.weight, std=.02)
237
+ if isinstance(m, nn.Linear) and m.bias is not None:
238
+ nn.init.constant_(m.bias, 0)
239
+ elif isinstance(m, nn.LayerNorm):
240
+ nn.init.constant_(m.bias, 0)
241
+ nn.init.constant_(m.weight, 1.0)
242
+ elif isinstance(m, nn.Conv2d):
243
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
244
+ fan_out //= m.groups
245
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
246
+ if m.bias is not None:
247
+ m.bias.data.zero_()
248
+
249
+ def forward(self, x, H, W):
250
+ B, N, C = x.shape
251
+ q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
252
+
253
+ if self.sr_ratio > 1:
254
+ x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
255
+ x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
256
+ x_ = self.norm(x_)
257
+ kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
258
+ else:
259
+ kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
260
+ k, v = kv[0], kv[1]
261
+
262
+ if config.SDPA_enabled:
263
+ x = torch.nn.functional.scaled_dot_product_attention(
264
+ q, k, v,
265
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
266
+ ).transpose(1, 2).reshape(B, N, C)
267
+ else:
268
+ attn = (q @ k.transpose(-2, -1)) * self.scale
269
+ attn = attn.softmax(dim=-1)
270
+ attn = self.attn_drop(attn)
271
+
272
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
273
+ x = self.proj(x)
274
+ x = self.proj_drop(x)
275
+
276
+ return x
277
+
278
+
279
+ class Block(nn.Module):
280
+
281
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
282
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
283
+ super().__init__()
284
+ self.norm1 = norm_layer(dim)
285
+ self.attn = Attention(
286
+ dim,
287
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
288
+ attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
289
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
290
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
291
+ self.norm2 = norm_layer(dim)
292
+ mlp_hidden_dim = int(dim * mlp_ratio)
293
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
294
+
295
+ self.apply(self._init_weights)
296
+
297
+ def _init_weights(self, m):
298
+ if isinstance(m, nn.Linear):
299
+ trunc_normal_(m.weight, std=.02)
300
+ if isinstance(m, nn.Linear) and m.bias is not None:
301
+ nn.init.constant_(m.bias, 0)
302
+ elif isinstance(m, nn.LayerNorm):
303
+ nn.init.constant_(m.bias, 0)
304
+ nn.init.constant_(m.weight, 1.0)
305
+ elif isinstance(m, nn.Conv2d):
306
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
307
+ fan_out //= m.groups
308
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
309
+ if m.bias is not None:
310
+ m.bias.data.zero_()
311
+
312
+ def forward(self, x, H, W):
313
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
314
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
315
+
316
+ return x
317
+
318
+
319
+ class OverlapPatchEmbed(nn.Module):
320
+ """ Image to Patch Embedding
321
+ """
322
+
323
+ def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768):
324
+ super().__init__()
325
+ img_size = to_2tuple(img_size)
326
+ patch_size = to_2tuple(patch_size)
327
+
328
+ self.img_size = img_size
329
+ self.patch_size = patch_size
330
+ self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
331
+ self.num_patches = self.H * self.W
332
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride,
333
+ padding=(patch_size[0] // 2, patch_size[1] // 2))
334
+ self.norm = nn.LayerNorm(embed_dim)
335
+
336
+ self.apply(self._init_weights)
337
+
338
+ def _init_weights(self, m):
339
+ if isinstance(m, nn.Linear):
340
+ trunc_normal_(m.weight, std=.02)
341
+ if isinstance(m, nn.Linear) and m.bias is not None:
342
+ nn.init.constant_(m.bias, 0)
343
+ elif isinstance(m, nn.LayerNorm):
344
+ nn.init.constant_(m.bias, 0)
345
+ nn.init.constant_(m.weight, 1.0)
346
+ elif isinstance(m, nn.Conv2d):
347
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
348
+ fan_out //= m.groups
349
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
350
+ if m.bias is not None:
351
+ m.bias.data.zero_()
352
+
353
+ def forward(self, x):
354
+ x = self.proj(x)
355
+ _, _, H, W = x.shape
356
+ x = x.flatten(2).transpose(1, 2)
357
+ x = self.norm(x)
358
+
359
+ return x, H, W
360
+
361
+
362
+ class PyramidVisionTransformerImpr(nn.Module):
363
+ def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
364
+ num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
365
+ attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
366
+ depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
367
+ super().__init__()
368
+ self.num_classes = num_classes
369
+ self.depths = depths
370
+
371
+ # patch_embed
372
+ self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels,
373
+ embed_dim=embed_dims[0])
374
+ self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0],
375
+ embed_dim=embed_dims[1])
376
+ self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1],
377
+ embed_dim=embed_dims[2])
378
+ self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2],
379
+ embed_dim=embed_dims[3])
380
+
381
+ # transformer encoder
382
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
383
+ cur = 0
384
+ self.block1 = nn.ModuleList([Block(
385
+ dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
386
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
387
+ sr_ratio=sr_ratios[0])
388
+ for i in range(depths[0])])
389
+ self.norm1 = norm_layer(embed_dims[0])
390
+
391
+ cur += depths[0]
392
+ self.block2 = nn.ModuleList([Block(
393
+ dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
394
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
395
+ sr_ratio=sr_ratios[1])
396
+ for i in range(depths[1])])
397
+ self.norm2 = norm_layer(embed_dims[1])
398
+
399
+ cur += depths[1]
400
+ self.block3 = nn.ModuleList([Block(
401
+ dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
402
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
403
+ sr_ratio=sr_ratios[2])
404
+ for i in range(depths[2])])
405
+ self.norm3 = norm_layer(embed_dims[2])
406
+
407
+ cur += depths[2]
408
+ self.block4 = nn.ModuleList([Block(
409
+ dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
410
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
411
+ sr_ratio=sr_ratios[3])
412
+ for i in range(depths[3])])
413
+ self.norm4 = norm_layer(embed_dims[3])
414
+
415
+ # classification head
416
+ # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
417
+
418
+ self.apply(self._init_weights)
419
+
420
+ def _init_weights(self, m):
421
+ if isinstance(m, nn.Linear):
422
+ trunc_normal_(m.weight, std=.02)
423
+ if isinstance(m, nn.Linear) and m.bias is not None:
424
+ nn.init.constant_(m.bias, 0)
425
+ elif isinstance(m, nn.LayerNorm):
426
+ nn.init.constant_(m.bias, 0)
427
+ nn.init.constant_(m.weight, 1.0)
428
+ elif isinstance(m, nn.Conv2d):
429
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
430
+ fan_out //= m.groups
431
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
432
+ if m.bias is not None:
433
+ m.bias.data.zero_()
434
+
435
+ def init_weights(self, pretrained=None):
436
+ if isinstance(pretrained, str):
437
+ logger = 1
438
+ #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
439
+
440
+ def reset_drop_path(self, drop_path_rate):
441
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
442
+ cur = 0
443
+ for i in range(self.depths[0]):
444
+ self.block1[i].drop_path.drop_prob = dpr[cur + i]
445
+
446
+ cur += self.depths[0]
447
+ for i in range(self.depths[1]):
448
+ self.block2[i].drop_path.drop_prob = dpr[cur + i]
449
+
450
+ cur += self.depths[1]
451
+ for i in range(self.depths[2]):
452
+ self.block3[i].drop_path.drop_prob = dpr[cur + i]
453
+
454
+ cur += self.depths[2]
455
+ for i in range(self.depths[3]):
456
+ self.block4[i].drop_path.drop_prob = dpr[cur + i]
457
+
458
+ def freeze_patch_emb(self):
459
+ self.patch_embed1.requires_grad = False
460
+
461
+ @torch.jit.ignore
462
+ def no_weight_decay(self):
463
+ return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
464
+
465
+ def get_classifier(self):
466
+ return self.head
467
+
468
+ def reset_classifier(self, num_classes, global_pool=''):
469
+ self.num_classes = num_classes
470
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
471
+
472
+ def forward_features(self, x):
473
+ B = x.shape[0]
474
+ outs = []
475
+
476
+ # stage 1
477
+ x, H, W = self.patch_embed1(x)
478
+ for i, blk in enumerate(self.block1):
479
+ x = blk(x, H, W)
480
+ x = self.norm1(x)
481
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
482
+ outs.append(x)
483
+
484
+ # stage 2
485
+ x, H, W = self.patch_embed2(x)
486
+ for i, blk in enumerate(self.block2):
487
+ x = blk(x, H, W)
488
+ x = self.norm2(x)
489
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
490
+ outs.append(x)
491
+
492
+ # stage 3
493
+ x, H, W = self.patch_embed3(x)
494
+ for i, blk in enumerate(self.block3):
495
+ x = blk(x, H, W)
496
+ x = self.norm3(x)
497
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
498
+ outs.append(x)
499
+
500
+ # stage 4
501
+ x, H, W = self.patch_embed4(x)
502
+ for i, blk in enumerate(self.block4):
503
+ x = blk(x, H, W)
504
+ x = self.norm4(x)
505
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
506
+ outs.append(x)
507
+
508
+ return outs
509
+
510
+ # return x.mean(dim=1)
511
+
512
+ def forward(self, x):
513
+ x = self.forward_features(x)
514
+ # x = self.head(x)
515
+
516
+ return x
517
+
518
+
519
+ class DWConv(nn.Module):
520
+ def __init__(self, dim=768):
521
+ super(DWConv, self).__init__()
522
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
523
+
524
+ def forward(self, x, H, W):
525
+ B, N, C = x.shape
526
+ x = x.transpose(1, 2).view(B, C, H, W).contiguous()
527
+ x = self.dwconv(x)
528
+ x = x.flatten(2).transpose(1, 2)
529
+
530
+ return x
531
+
532
+
533
+ def _conv_filter(state_dict, patch_size=16):
534
+ """ convert patch embedding weight from manual patchify + linear proj to conv"""
535
+ out_dict = {}
536
+ for k, v in state_dict.items():
537
+ if 'patch_embed.proj.weight' in k:
538
+ v = v.reshape((v.shape[0], 3, patch_size, patch_size))
539
+ out_dict[k] = v
540
+
541
+ return out_dict
542
+
543
+
544
+ ## @register_model
545
+ class pvt_v2_b0(PyramidVisionTransformerImpr):
546
+ def __init__(self, **kwargs):
547
+ super(pvt_v2_b0, self).__init__(
548
+ patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
549
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
550
+ drop_rate=0.0, drop_path_rate=0.1)
551
+
552
+
553
+
554
+ ## @register_model
555
+ class pvt_v2_b1(PyramidVisionTransformerImpr):
556
+ def __init__(self, **kwargs):
557
+ super(pvt_v2_b1, self).__init__(
558
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
559
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
560
+ drop_rate=0.0, drop_path_rate=0.1)
561
+
562
+ ## @register_model
563
+ class pvt_v2_b2(PyramidVisionTransformerImpr):
564
+ def __init__(self, in_channels=3, **kwargs):
565
+ super(pvt_v2_b2, self).__init__(
566
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
567
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],
568
+ drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
569
+
570
+ ## @register_model
571
+ class pvt_v2_b3(PyramidVisionTransformerImpr):
572
+ def __init__(self, **kwargs):
573
+ super(pvt_v2_b3, self).__init__(
574
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
575
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
576
+ drop_rate=0.0, drop_path_rate=0.1)
577
+
578
+ ## @register_model
579
+ class pvt_v2_b4(PyramidVisionTransformerImpr):
580
+ def __init__(self, **kwargs):
581
+ super(pvt_v2_b4, self).__init__(
582
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
583
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],
584
+ drop_rate=0.0, drop_path_rate=0.1)
585
+
586
+
587
+ ## @register_model
588
+ class pvt_v2_b5(PyramidVisionTransformerImpr):
589
+ def __init__(self, **kwargs):
590
+ super(pvt_v2_b5, self).__init__(
591
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
592
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
593
+ drop_rate=0.0, drop_path_rate=0.1)
594
+
595
+
596
+
597
+ ### models/backbones/swin_v1.py
598
+
599
+ # --------------------------------------------------------
600
+ # Swin Transformer
601
+ # Copyright (c) 2021 Microsoft
602
+ # Licensed under The MIT License [see LICENSE for details]
603
+ # Written by Ze Liu, Yutong Lin, Yixuan Wei
604
+ # --------------------------------------------------------
605
+
606
+ import torch
607
+ import torch.nn as nn
608
+ import torch.nn.functional as F
609
+ import torch.utils.checkpoint as checkpoint
610
+ import numpy as np
611
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
612
+
613
+ # from config import Config
614
+
615
+
616
+ # config = Config()
617
+
618
+
619
+ class Mlp(nn.Module):
620
+ """ Multilayer perceptron."""
621
+
622
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
623
+ super().__init__()
624
+ out_features = out_features or in_features
625
+ hidden_features = hidden_features or in_features
626
+ self.fc1 = nn.Linear(in_features, hidden_features)
627
+ self.act = act_layer()
628
+ self.fc2 = nn.Linear(hidden_features, out_features)
629
+ self.drop = nn.Dropout(drop)
630
+
631
+ def forward(self, x):
632
+ x = self.fc1(x)
633
+ x = self.act(x)
634
+ x = self.drop(x)
635
+ x = self.fc2(x)
636
+ x = self.drop(x)
637
+ return x
638
+
639
+
640
+ def window_partition(x, window_size):
641
+ """
642
+ Args:
643
+ x: (B, H, W, C)
644
+ window_size (int): window size
645
+
646
+ Returns:
647
+ windows: (num_windows*B, window_size, window_size, C)
648
+ """
649
+ B, H, W, C = x.shape
650
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
651
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
652
+ return windows
653
+
654
+
655
+ def window_reverse(windows, window_size, H, W):
656
+ """
657
+ Args:
658
+ windows: (num_windows*B, window_size, window_size, C)
659
+ window_size (int): Window size
660
+ H (int): Height of image
661
+ W (int): Width of image
662
+
663
+ Returns:
664
+ x: (B, H, W, C)
665
+ """
666
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
667
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
668
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
669
+ return x
670
+
671
+
672
+ class WindowAttention(nn.Module):
673
+ """ Window based multi-head self attention (W-MSA) module with relative position bias.
674
+ It supports both of shifted and non-shifted window.
675
+
676
+ Args:
677
+ dim (int): Number of input channels.
678
+ window_size (tuple[int]): The height and width of the window.
679
+ num_heads (int): Number of attention heads.
680
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
681
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
682
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
683
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
684
+ """
685
+
686
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
687
+
688
+ super().__init__()
689
+ self.dim = dim
690
+ self.window_size = window_size # Wh, Ww
691
+ self.num_heads = num_heads
692
+ head_dim = dim // num_heads
693
+ self.scale = qk_scale or head_dim ** -0.5
694
+
695
+ # define a parameter table of relative position bias
696
+ self.relative_position_bias_table = nn.Parameter(
697
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
698
+
699
+ # get pair-wise relative position index for each token inside the window
700
+ coords_h = torch.arange(self.window_size[0])
701
+ coords_w = torch.arange(self.window_size[1])
702
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww
703
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
704
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
705
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
706
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
707
+ relative_coords[:, :, 1] += self.window_size[1] - 1
708
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
709
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
710
+ self.register_buffer("relative_position_index", relative_position_index)
711
+
712
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
713
+ self.attn_drop_prob = attn_drop
714
+ self.attn_drop = nn.Dropout(attn_drop)
715
+ self.proj = nn.Linear(dim, dim)
716
+ self.proj_drop = nn.Dropout(proj_drop)
717
+
718
+ trunc_normal_(self.relative_position_bias_table, std=.02)
719
+ self.softmax = nn.Softmax(dim=-1)
720
+
721
+ def forward(self, x, mask=None):
722
+ """ Forward function.
723
+
724
+ Args:
725
+ x: input features with shape of (num_windows*B, N, C)
726
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
727
+ """
728
+ B_, N, C = x.shape
729
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
730
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
731
+
732
+ q = q * self.scale
733
+
734
+ if config.SDPA_enabled:
735
+ x = torch.nn.functional.scaled_dot_product_attention(
736
+ q, k, v,
737
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
738
+ ).transpose(1, 2).reshape(B_, N, C)
739
+ else:
740
+ attn = (q @ k.transpose(-2, -1))
741
+
742
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
743
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
744
+ ) # Wh*Ww, Wh*Ww, nH
745
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
746
+ attn = attn + relative_position_bias.unsqueeze(0)
747
+
748
+ if mask is not None:
749
+ nW = mask.shape[0]
750
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
751
+ attn = attn.view(-1, self.num_heads, N, N)
752
+ attn = self.softmax(attn)
753
+ else:
754
+ attn = self.softmax(attn)
755
+
756
+ attn = self.attn_drop(attn)
757
+
758
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
759
+ x = self.proj(x)
760
+ x = self.proj_drop(x)
761
+ return x
762
+
763
+
764
+ class SwinTransformerBlock(nn.Module):
765
+ """ Swin Transformer Block.
766
+
767
+ Args:
768
+ dim (int): Number of input channels.
769
+ num_heads (int): Number of attention heads.
770
+ window_size (int): Window size.
771
+ shift_size (int): Shift size for SW-MSA.
772
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
773
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
774
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
775
+ drop (float, optional): Dropout rate. Default: 0.0
776
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
777
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
778
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
779
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
780
+ """
781
+
782
+ def __init__(self, dim, num_heads, window_size=7, shift_size=0,
783
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
784
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
785
+ super().__init__()
786
+ self.dim = dim
787
+ self.num_heads = num_heads
788
+ self.window_size = window_size
789
+ self.shift_size = shift_size
790
+ self.mlp_ratio = mlp_ratio
791
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
792
+
793
+ self.norm1 = norm_layer(dim)
794
+ self.attn = WindowAttention(
795
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
796
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
797
+
798
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
799
+ self.norm2 = norm_layer(dim)
800
+ mlp_hidden_dim = int(dim * mlp_ratio)
801
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
802
+
803
+ self.H = None
804
+ self.W = None
805
+
806
+ def forward(self, x, mask_matrix):
807
+ """ Forward function.
808
+
809
+ Args:
810
+ x: Input feature, tensor size (B, H*W, C).
811
+ H, W: Spatial resolution of the input feature.
812
+ mask_matrix: Attention mask for cyclic shift.
813
+ """
814
+ B, L, C = x.shape
815
+ H, W = self.H, self.W
816
+ assert L == H * W, "input feature has wrong size"
817
+
818
+ shortcut = x
819
+ x = self.norm1(x)
820
+ x = x.view(B, H, W, C)
821
+
822
+ # pad feature maps to multiples of window size
823
+ pad_l = pad_t = 0
824
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
825
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
826
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
827
+ _, Hp, Wp, _ = x.shape
828
+
829
+ # cyclic shift
830
+ if self.shift_size > 0:
831
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
832
+ attn_mask = mask_matrix
833
+ else:
834
+ shifted_x = x
835
+ attn_mask = None
836
+
837
+ # partition windows
838
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
839
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
840
+
841
+ # W-MSA/SW-MSA
842
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
843
+
844
+ # merge windows
845
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
846
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
847
+
848
+ # reverse cyclic shift
849
+ if self.shift_size > 0:
850
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
851
+ else:
852
+ x = shifted_x
853
+
854
+ if pad_r > 0 or pad_b > 0:
855
+ x = x[:, :H, :W, :].contiguous()
856
+
857
+ x = x.view(B, H * W, C)
858
+
859
+ # FFN
860
+ x = shortcut + self.drop_path(x)
861
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
862
+
863
+ return x
864
+
865
+
866
+ class PatchMerging(nn.Module):
867
+ """ Patch Merging Layer
868
+
869
+ Args:
870
+ dim (int): Number of input channels.
871
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
872
+ """
873
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
874
+ super().__init__()
875
+ self.dim = dim
876
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
877
+ self.norm = norm_layer(4 * dim)
878
+
879
+ def forward(self, x, H, W):
880
+ """ Forward function.
881
+
882
+ Args:
883
+ x: Input feature, tensor size (B, H*W, C).
884
+ H, W: Spatial resolution of the input feature.
885
+ """
886
+ B, L, C = x.shape
887
+ assert L == H * W, "input feature has wrong size"
888
+
889
+ x = x.view(B, H, W, C)
890
+
891
+ # padding
892
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
893
+ if pad_input:
894
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
895
+
896
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
897
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
898
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
899
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
900
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
901
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
902
+
903
+ x = self.norm(x)
904
+ x = self.reduction(x)
905
+
906
+ return x
907
+
908
+
909
+ class BasicLayer(nn.Module):
910
+ """ A basic Swin Transformer layer for one stage.
911
+
912
+ Args:
913
+ dim (int): Number of feature channels
914
+ depth (int): Depths of this stage.
915
+ num_heads (int): Number of attention head.
916
+ window_size (int): Local window size. Default: 7.
917
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
918
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
919
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
920
+ drop (float, optional): Dropout rate. Default: 0.0
921
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
922
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
923
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
924
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
925
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
926
+ """
927
+
928
+ def __init__(self,
929
+ dim,
930
+ depth,
931
+ num_heads,
932
+ window_size=7,
933
+ mlp_ratio=4.,
934
+ qkv_bias=True,
935
+ qk_scale=None,
936
+ drop=0.,
937
+ attn_drop=0.,
938
+ drop_path=0.,
939
+ norm_layer=nn.LayerNorm,
940
+ downsample=None,
941
+ use_checkpoint=False):
942
+ super().__init__()
943
+ self.window_size = window_size
944
+ self.shift_size = window_size // 2
945
+ self.depth = depth
946
+ self.use_checkpoint = use_checkpoint
947
+
948
+ # build blocks
949
+ self.blocks = nn.ModuleList([
950
+ SwinTransformerBlock(
951
+ dim=dim,
952
+ num_heads=num_heads,
953
+ window_size=window_size,
954
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
955
+ mlp_ratio=mlp_ratio,
956
+ qkv_bias=qkv_bias,
957
+ qk_scale=qk_scale,
958
+ drop=drop,
959
+ attn_drop=attn_drop,
960
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
961
+ norm_layer=norm_layer)
962
+ for i in range(depth)])
963
+
964
+ # patch merging layer
965
+ if downsample is not None:
966
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
967
+ else:
968
+ self.downsample = None
969
+
970
+ def forward(self, x, H, W):
971
+ """ Forward function.
972
+
973
+ Args:
974
+ x: Input feature, tensor size (B, H*W, C).
975
+ H, W: Spatial resolution of the input feature.
976
+ """
977
+
978
+ # calculate attention mask for SW-MSA
979
+ # Turn int to torch.tensor for the compatiability with torch.compile in PyTorch 2.5.
980
+ Hp = torch.ceil(torch.tensor(H) / self.window_size).to(torch.int64) * self.window_size
981
+ Wp = torch.ceil(torch.tensor(W) / self.window_size).to(torch.int64) * self.window_size
982
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
983
+ h_slices = (slice(0, -self.window_size),
984
+ slice(-self.window_size, -self.shift_size),
985
+ slice(-self.shift_size, None))
986
+ w_slices = (slice(0, -self.window_size),
987
+ slice(-self.window_size, -self.shift_size),
988
+ slice(-self.shift_size, None))
989
+ cnt = 0
990
+ for h in h_slices:
991
+ for w in w_slices:
992
+ img_mask[:, h, w, :] = cnt
993
+ cnt += 1
994
+
995
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
996
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
997
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
998
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)).to(x.dtype)
999
+
1000
+ for blk in self.blocks:
1001
+ blk.H, blk.W = H, W
1002
+ if self.use_checkpoint:
1003
+ x = checkpoint.checkpoint(blk, x, attn_mask)
1004
+ else:
1005
+ x = blk(x, attn_mask)
1006
+ if self.downsample is not None:
1007
+ x_down = self.downsample(x, H, W)
1008
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
1009
+ return x, H, W, x_down, Wh, Ww
1010
+ else:
1011
+ return x, H, W, x, H, W
1012
+
1013
+
1014
+ class PatchEmbed(nn.Module):
1015
+ """ Image to Patch Embedding
1016
+
1017
+ Args:
1018
+ patch_size (int): Patch token size. Default: 4.
1019
+ in_channels (int): Number of input image channels. Default: 3.
1020
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1021
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
1022
+ """
1023
+
1024
+ def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None):
1025
+ super().__init__()
1026
+ patch_size = to_2tuple(patch_size)
1027
+ self.patch_size = patch_size
1028
+
1029
+ self.in_channels = in_channels
1030
+ self.embed_dim = embed_dim
1031
+
1032
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
1033
+ if norm_layer is not None:
1034
+ self.norm = norm_layer(embed_dim)
1035
+ else:
1036
+ self.norm = None
1037
+
1038
+ def forward(self, x):
1039
+ """Forward function."""
1040
+ # padding
1041
+ _, _, H, W = x.size()
1042
+ if W % self.patch_size[1] != 0:
1043
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
1044
+ if H % self.patch_size[0] != 0:
1045
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
1046
+
1047
+ x = self.proj(x) # B C Wh Ww
1048
+ if self.norm is not None:
1049
+ Wh, Ww = x.size(2), x.size(3)
1050
+ x = x.flatten(2).transpose(1, 2)
1051
+ x = self.norm(x)
1052
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
1053
+
1054
+ return x
1055
+
1056
+
1057
+ class SwinTransformer(nn.Module):
1058
+ """ Swin Transformer backbone.
1059
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
1060
+ https://arxiv.org/pdf/2103.14030
1061
+
1062
+ Args:
1063
+ pretrain_img_size (int): Input image size for training the pretrained model,
1064
+ used in absolute postion embedding. Default 224.
1065
+ patch_size (int | tuple(int)): Patch size. Default: 4.
1066
+ in_channels (int): Number of input image channels. Default: 3.
1067
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1068
+ depths (tuple[int]): Depths of each Swin Transformer stage.
1069
+ num_heads (tuple[int]): Number of attention head of each stage.
1070
+ window_size (int): Window size. Default: 7.
1071
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
1072
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
1073
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
1074
+ drop_rate (float): Dropout rate.
1075
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
1076
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
1077
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
1078
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
1079
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
1080
+ out_indices (Sequence[int]): Output from which stages.
1081
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
1082
+ -1 means not freezing any parameters.
1083
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
1084
+ """
1085
+
1086
+ def __init__(self,
1087
+ pretrain_img_size=224,
1088
+ patch_size=4,
1089
+ in_channels=3,
1090
+ embed_dim=96,
1091
+ depths=[2, 2, 6, 2],
1092
+ num_heads=[3, 6, 12, 24],
1093
+ window_size=7,
1094
+ mlp_ratio=4.,
1095
+ qkv_bias=True,
1096
+ qk_scale=None,
1097
+ drop_rate=0.,
1098
+ attn_drop_rate=0.,
1099
+ drop_path_rate=0.2,
1100
+ norm_layer=nn.LayerNorm,
1101
+ ape=False,
1102
+ patch_norm=True,
1103
+ out_indices=(0, 1, 2, 3),
1104
+ frozen_stages=-1,
1105
+ use_checkpoint=False):
1106
+ super().__init__()
1107
+
1108
+ self.pretrain_img_size = pretrain_img_size
1109
+ self.num_layers = len(depths)
1110
+ self.embed_dim = embed_dim
1111
+ self.ape = ape
1112
+ self.patch_norm = patch_norm
1113
+ self.out_indices = out_indices
1114
+ self.frozen_stages = frozen_stages
1115
+
1116
+ # split image into non-overlapping patches
1117
+ self.patch_embed = PatchEmbed(
1118
+ patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim,
1119
+ norm_layer=norm_layer if self.patch_norm else None)
1120
+
1121
+ # absolute position embedding
1122
+ if self.ape:
1123
+ pretrain_img_size = to_2tuple(pretrain_img_size)
1124
+ patch_size = to_2tuple(patch_size)
1125
+ patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
1126
+
1127
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
1128
+ trunc_normal_(self.absolute_pos_embed, std=.02)
1129
+
1130
+ self.pos_drop = nn.Dropout(p=drop_rate)
1131
+
1132
+ # stochastic depth
1133
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
1134
+
1135
+ # build layers
1136
+ self.layers = nn.ModuleList()
1137
+ for i_layer in range(self.num_layers):
1138
+ layer = BasicLayer(
1139
+ dim=int(embed_dim * 2 ** i_layer),
1140
+ depth=depths[i_layer],
1141
+ num_heads=num_heads[i_layer],
1142
+ window_size=window_size,
1143
+ mlp_ratio=mlp_ratio,
1144
+ qkv_bias=qkv_bias,
1145
+ qk_scale=qk_scale,
1146
+ drop=drop_rate,
1147
+ attn_drop=attn_drop_rate,
1148
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
1149
+ norm_layer=norm_layer,
1150
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
1151
+ use_checkpoint=use_checkpoint)
1152
+ self.layers.append(layer)
1153
+
1154
+ num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
1155
+ self.num_features = num_features
1156
+
1157
+ # add a norm layer for each output
1158
+ for i_layer in out_indices:
1159
+ layer = norm_layer(num_features[i_layer])
1160
+ layer_name = f'norm{i_layer}'
1161
+ self.add_module(layer_name, layer)
1162
+
1163
+ self._freeze_stages()
1164
+
1165
+ def _freeze_stages(self):
1166
+ if self.frozen_stages >= 0:
1167
+ self.patch_embed.eval()
1168
+ for param in self.patch_embed.parameters():
1169
+ param.requires_grad = False
1170
+
1171
+ if self.frozen_stages >= 1 and self.ape:
1172
+ self.absolute_pos_embed.requires_grad = False
1173
+
1174
+ if self.frozen_stages >= 2:
1175
+ self.pos_drop.eval()
1176
+ for i in range(0, self.frozen_stages - 1):
1177
+ m = self.layers[i]
1178
+ m.eval()
1179
+ for param in m.parameters():
1180
+ param.requires_grad = False
1181
+
1182
+
1183
+ def forward(self, x):
1184
+ """Forward function."""
1185
+ x = self.patch_embed(x)
1186
+
1187
+ Wh, Ww = x.size(2), x.size(3)
1188
+ if self.ape:
1189
+ # interpolate the position embedding to the corresponding size
1190
+ absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
1191
+ x = (x + absolute_pos_embed) # B Wh*Ww C
1192
+
1193
+ outs = []#x.contiguous()]
1194
+ x = x.flatten(2).transpose(1, 2)
1195
+ x = self.pos_drop(x)
1196
+ for i in range(self.num_layers):
1197
+ layer = self.layers[i]
1198
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
1199
+
1200
+ if i in self.out_indices:
1201
+ norm_layer = getattr(self, f'norm{i}')
1202
+ x_out = norm_layer(x_out)
1203
+
1204
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
1205
+ outs.append(out)
1206
+
1207
+ return tuple(outs)
1208
+
1209
+ def train(self, mode=True):
1210
+ """Convert the model into training mode while keep layers freezed."""
1211
+ super(SwinTransformer, self).train(mode)
1212
+ self._freeze_stages()
1213
+
1214
+ def swin_v1_t():
1215
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7)
1216
+ return model
1217
+
1218
+ def swin_v1_s():
1219
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7)
1220
+ return model
1221
+
1222
+ def swin_v1_b():
1223
+ model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
1224
+ return model
1225
+
1226
+ def swin_v1_l():
1227
+ model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12)
1228
+ return model
1229
+
1230
+
1231
+
1232
+ ### models/modules/deform_conv.py
1233
+
1234
+ import torch
1235
+ import torch.nn as nn
1236
+ from torchvision.ops import deform_conv2d
1237
+
1238
+
1239
+ class DeformableConv2d(nn.Module):
1240
+ def __init__(self,
1241
+ in_channels,
1242
+ out_channels,
1243
+ kernel_size=3,
1244
+ stride=1,
1245
+ padding=1,
1246
+ bias=False):
1247
+
1248
+ super(DeformableConv2d, self).__init__()
1249
+
1250
+ assert type(kernel_size) == tuple or type(kernel_size) == int
1251
+
1252
+ kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size)
1253
+ self.stride = stride if type(stride) == tuple else (stride, stride)
1254
+ self.padding = padding
1255
+
1256
+ self.offset_conv = nn.Conv2d(in_channels,
1257
+ 2 * kernel_size[0] * kernel_size[1],
1258
+ kernel_size=kernel_size,
1259
+ stride=stride,
1260
+ padding=self.padding,
1261
+ bias=True)
1262
+
1263
+ nn.init.constant_(self.offset_conv.weight, 0.)
1264
+ nn.init.constant_(self.offset_conv.bias, 0.)
1265
+
1266
+ self.modulator_conv = nn.Conv2d(in_channels,
1267
+ 1 * kernel_size[0] * kernel_size[1],
1268
+ kernel_size=kernel_size,
1269
+ stride=stride,
1270
+ padding=self.padding,
1271
+ bias=True)
1272
+
1273
+ nn.init.constant_(self.modulator_conv.weight, 0.)
1274
+ nn.init.constant_(self.modulator_conv.bias, 0.)
1275
+
1276
+ self.regular_conv = nn.Conv2d(in_channels,
1277
+ out_channels=out_channels,
1278
+ kernel_size=kernel_size,
1279
+ stride=stride,
1280
+ padding=self.padding,
1281
+ bias=bias)
1282
+
1283
+ def forward(self, x):
1284
+ #h, w = x.shape[2:]
1285
+ #max_offset = max(h, w)/4.
1286
+
1287
+ offset = self.offset_conv(x)#.clamp(-max_offset, max_offset)
1288
+ modulator = 2. * torch.sigmoid(self.modulator_conv(x))
1289
+
1290
+ x = deform_conv2d(
1291
+ input=x,
1292
+ offset=offset,
1293
+ weight=self.regular_conv.weight,
1294
+ bias=self.regular_conv.bias,
1295
+ padding=self.padding,
1296
+ mask=modulator,
1297
+ stride=self.stride,
1298
+ )
1299
+ return x
1300
+
1301
+
1302
+
1303
+
1304
+ ### utils.py
1305
+
1306
+ import torch.nn as nn
1307
+
1308
+
1309
+ def build_act_layer(act_layer):
1310
+ if act_layer == 'ReLU':
1311
+ return nn.ReLU(inplace=True)
1312
+ elif act_layer == 'SiLU':
1313
+ return nn.SiLU(inplace=True)
1314
+ elif act_layer == 'GELU':
1315
+ return nn.GELU()
1316
+
1317
+ raise NotImplementedError(f'build_act_layer does not support {act_layer}')
1318
+
1319
+
1320
+ def build_norm_layer(dim,
1321
+ norm_layer,
1322
+ in_format='channels_last',
1323
+ out_format='channels_last',
1324
+ eps=1e-6):
1325
+ layers = []
1326
+ if norm_layer == 'BN':
1327
+ if in_format == 'channels_last':
1328
+ layers.append(to_channels_first())
1329
+ layers.append(nn.BatchNorm2d(dim))
1330
+ if out_format == 'channels_last':
1331
+ layers.append(to_channels_last())
1332
+ elif norm_layer == 'LN':
1333
+ if in_format == 'channels_first':
1334
+ layers.append(to_channels_last())
1335
+ layers.append(nn.LayerNorm(dim, eps=eps))
1336
+ if out_format == 'channels_first':
1337
+ layers.append(to_channels_first())
1338
+ else:
1339
+ raise NotImplementedError(
1340
+ f'build_norm_layer does not support {norm_layer}')
1341
+ return nn.Sequential(*layers)
1342
+
1343
+
1344
+ class to_channels_first(nn.Module):
1345
+
1346
+ def __init__(self):
1347
+ super().__init__()
1348
+
1349
+ def forward(self, x):
1350
+ return x.permute(0, 3, 1, 2)
1351
+
1352
+
1353
+ class to_channels_last(nn.Module):
1354
+
1355
+ def __init__(self):
1356
+ super().__init__()
1357
+
1358
+ def forward(self, x):
1359
+ return x.permute(0, 2, 3, 1)
1360
+
1361
+
1362
+
1363
+ ### dataset.py
1364
+
1365
+ _class_labels_TR_sorted = (
1366
+ 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, '
1367
+ 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, '
1368
+ 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, '
1369
+ 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, '
1370
+ 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, '
1371
+ 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, '
1372
+ 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, '
1373
+ 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, '
1374
+ 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, '
1375
+ 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, '
1376
+ 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, '
1377
+ 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, '
1378
+ 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, '
1379
+ 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht'
1380
+ )
1381
+ class_labels_TR_sorted = _class_labels_TR_sorted.split(', ')
1382
+
1383
+
1384
+ ### models/backbones/build_backbones.py
1385
+
1386
+ import torch
1387
+ import torch.nn as nn
1388
+ from collections import OrderedDict
1389
+ from torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights
1390
+ # from models.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5
1391
+ # from models.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l
1392
+ # from config import Config
1393
+
1394
+
1395
+ config = Config()
1396
+
1397
+ def build_backbone(bb_name, pretrained=True, params_settings=''):
1398
+ if bb_name == 'vgg16':
1399
+ bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0]
1400
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]}))
1401
+ elif bb_name == 'vgg16bn':
1402
+ bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0]
1403
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]}))
1404
+ elif bb_name == 'resnet50':
1405
+ bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children())
1406
+ bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]}))
1407
+ else:
1408
+ bb = eval('{}({})'.format(bb_name, params_settings))
1409
+ if pretrained:
1410
+ bb = load_weights(bb, bb_name)
1411
+ return bb
1412
+
1413
+ def load_weights(model, model_name):
1414
+ save_model = torch.load(config.weights[model_name], map_location='cpu')
1415
+ model_dict = model.state_dict()
1416
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model.items() if k in model_dict.keys()}
1417
+ # to ignore the weights with mismatched size when I modify the backbone itself.
1418
+ if not state_dict:
1419
+ save_model_keys = list(save_model.keys())
1420
+ sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None
1421
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model[sub_item].items() if k in model_dict.keys()}
1422
+ if not state_dict or not sub_item:
1423
+ print('Weights are not successully loaded. Check the state dict of weights file.')
1424
+ return None
1425
+ else:
1426
+ print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item))
1427
+ model_dict.update(state_dict)
1428
+ model.load_state_dict(model_dict)
1429
+ return model
1430
+
1431
+
1432
+
1433
+ ### models/modules/decoder_blocks.py
1434
+
1435
+ import torch
1436
+ import torch.nn as nn
1437
+ # from models.aspp import ASPP, ASPPDeformable
1438
+ # from config import Config
1439
+
1440
+
1441
+ # config = Config()
1442
+
1443
+
1444
+ class BasicDecBlk(nn.Module):
1445
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1446
+ super(BasicDecBlk, self).__init__()
1447
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1448
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1449
+ self.relu_in = nn.ReLU(inplace=True)
1450
+ if config.dec_att == 'ASPP':
1451
+ self.dec_att = ASPP(in_channels=inter_channels)
1452
+ elif config.dec_att == 'ASPPDeformable':
1453
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1454
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1455
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1456
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1457
+
1458
+ def forward(self, x):
1459
+ x = self.conv_in(x)
1460
+ x = self.bn_in(x)
1461
+ x = self.relu_in(x)
1462
+ if hasattr(self, 'dec_att'):
1463
+ x = self.dec_att(x)
1464
+ x = self.conv_out(x)
1465
+ x = self.bn_out(x)
1466
+ return x
1467
+
1468
+
1469
+ class ResBlk(nn.Module):
1470
+ def __init__(self, in_channels=64, out_channels=None, inter_channels=64):
1471
+ super(ResBlk, self).__init__()
1472
+ if out_channels is None:
1473
+ out_channels = in_channels
1474
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1475
+
1476
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1477
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1478
+ self.relu_in = nn.ReLU(inplace=True)
1479
+
1480
+ if config.dec_att == 'ASPP':
1481
+ self.dec_att = ASPP(in_channels=inter_channels)
1482
+ elif config.dec_att == 'ASPPDeformable':
1483
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1484
+
1485
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1486
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1487
+
1488
+ self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1489
+
1490
+ def forward(self, x):
1491
+ _x = self.conv_resi(x)
1492
+ x = self.conv_in(x)
1493
+ x = self.bn_in(x)
1494
+ x = self.relu_in(x)
1495
+ if hasattr(self, 'dec_att'):
1496
+ x = self.dec_att(x)
1497
+ x = self.conv_out(x)
1498
+ x = self.bn_out(x)
1499
+ return x + _x
1500
+
1501
+
1502
+
1503
+ ### models/modules/lateral_blocks.py
1504
+
1505
+ import numpy as np
1506
+ import torch
1507
+ import torch.nn as nn
1508
+ import torch.nn.functional as F
1509
+ from functools import partial
1510
+
1511
+ # from config import Config
1512
+
1513
+
1514
+ # config = Config()
1515
+
1516
+
1517
+ class BasicLatBlk(nn.Module):
1518
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1519
+ super(BasicLatBlk, self).__init__()
1520
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1521
+ self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1522
+
1523
+ def forward(self, x):
1524
+ x = self.conv(x)
1525
+ return x
1526
+
1527
+
1528
+
1529
+ ### models/modules/aspp.py
1530
+
1531
+ import torch
1532
+ import torch.nn as nn
1533
+ import torch.nn.functional as F
1534
+ # from models.deform_conv import DeformableConv2d
1535
+ # from config import Config
1536
+
1537
+
1538
+ # config = Config()
1539
+
1540
+
1541
+ class _ASPPModule(nn.Module):
1542
+ def __init__(self, in_channels, planes, kernel_size, padding, dilation):
1543
+ super(_ASPPModule, self).__init__()
1544
+ self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size,
1545
+ stride=1, padding=padding, dilation=dilation, bias=False)
1546
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1547
+ self.relu = nn.ReLU(inplace=True)
1548
+
1549
+ def forward(self, x):
1550
+ x = self.atrous_conv(x)
1551
+ x = self.bn(x)
1552
+
1553
+ return self.relu(x)
1554
+
1555
+
1556
+ class ASPP(nn.Module):
1557
+ def __init__(self, in_channels=64, out_channels=None, output_stride=16):
1558
+ super(ASPP, self).__init__()
1559
+ self.down_scale = 1
1560
+ if out_channels is None:
1561
+ out_channels = in_channels
1562
+ self.in_channelster = 256 // self.down_scale
1563
+ if output_stride == 16:
1564
+ dilations = [1, 6, 12, 18]
1565
+ elif output_stride == 8:
1566
+ dilations = [1, 12, 24, 36]
1567
+ else:
1568
+ raise NotImplementedError
1569
+
1570
+ self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0])
1571
+ self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1])
1572
+ self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2])
1573
+ self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3])
1574
+
1575
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1576
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1577
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1578
+ nn.ReLU(inplace=True))
1579
+ self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False)
1580
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1581
+ self.relu = nn.ReLU(inplace=True)
1582
+ self.dropout = nn.Dropout(0.5)
1583
+
1584
+ def forward(self, x):
1585
+ x1 = self.aspp1(x)
1586
+ x2 = self.aspp2(x)
1587
+ x3 = self.aspp3(x)
1588
+ x4 = self.aspp4(x)
1589
+ x5 = self.global_avg_pool(x)
1590
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1591
+ x = torch.cat((x1, x2, x3, x4, x5), dim=1)
1592
+
1593
+ x = self.conv1(x)
1594
+ x = self.bn1(x)
1595
+ x = self.relu(x)
1596
+
1597
+ return self.dropout(x)
1598
+
1599
+
1600
+ ##################### Deformable
1601
+ class _ASPPModuleDeformable(nn.Module):
1602
+ def __init__(self, in_channels, planes, kernel_size, padding):
1603
+ super(_ASPPModuleDeformable, self).__init__()
1604
+ self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size,
1605
+ stride=1, padding=padding, bias=False)
1606
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1607
+ self.relu = nn.ReLU(inplace=True)
1608
+
1609
+ def forward(self, x):
1610
+ x = self.atrous_conv(x)
1611
+ x = self.bn(x)
1612
+
1613
+ return self.relu(x)
1614
+
1615
+
1616
+ class ASPPDeformable(nn.Module):
1617
+ def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]):
1618
+ super(ASPPDeformable, self).__init__()
1619
+ self.down_scale = 1
1620
+ if out_channels is None:
1621
+ out_channels = in_channels
1622
+ self.in_channelster = 256 // self.down_scale
1623
+
1624
+ self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0)
1625
+ self.aspp_deforms = nn.ModuleList([
1626
+ _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes
1627
+ ])
1628
+
1629
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1630
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1631
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1632
+ nn.ReLU(inplace=True))
1633
+ self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False)
1634
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1635
+ self.relu = nn.ReLU(inplace=True)
1636
+ self.dropout = nn.Dropout(0.5)
1637
+
1638
+ def forward(self, x):
1639
+ x1 = self.aspp1(x)
1640
+ x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms]
1641
+ x5 = self.global_avg_pool(x)
1642
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1643
+ x = torch.cat((x1, *x_aspp_deforms, x5), dim=1)
1644
+
1645
+ x = self.conv1(x)
1646
+ x = self.bn1(x)
1647
+ x = self.relu(x)
1648
+
1649
+ return self.dropout(x)
1650
+
1651
+
1652
+
1653
+ ### models/refinement/refiner.py
1654
+
1655
+ import torch
1656
+ import torch.nn as nn
1657
+ from collections import OrderedDict
1658
+ import torch
1659
+ import torch.nn as nn
1660
+ import torch.nn.functional as F
1661
+ from torchvision.models import vgg16, vgg16_bn
1662
+ from torchvision.models import resnet50
1663
+
1664
+ # from config import Config
1665
+ # from dataset import class_labels_TR_sorted
1666
+ # from models.build_backbone import build_backbone
1667
+ # from models.decoder_blocks import BasicDecBlk
1668
+ # from models.lateral_blocks import BasicLatBlk
1669
+ # from models.ing import *
1670
+ # from models.stem_layer import StemLayer
1671
+
1672
+
1673
+ class RefinerPVTInChannels4(nn.Module):
1674
+ def __init__(self, in_channels=3+1):
1675
+ super(RefinerPVTInChannels4, self).__init__()
1676
+ self.config = Config()
1677
+ self.epoch = 1
1678
+ self.bb = build_backbone(self.config.bb, params_settings='in_channels=4')
1679
+
1680
+ lateral_channels_in_collection = {
1681
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1682
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1683
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1684
+ }
1685
+ channels = lateral_channels_in_collection[self.config.bb]
1686
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1687
+
1688
+ self.decoder = Decoder(channels)
1689
+
1690
+ if 0:
1691
+ for key, value in self.named_parameters():
1692
+ if 'bb.' in key:
1693
+ value.requires_grad = False
1694
+
1695
+ def forward(self, x):
1696
+ if isinstance(x, list):
1697
+ x = torch.cat(x, dim=1)
1698
+ ########## Encoder ##########
1699
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1700
+ x1 = self.bb.conv1(x)
1701
+ x2 = self.bb.conv2(x1)
1702
+ x3 = self.bb.conv3(x2)
1703
+ x4 = self.bb.conv4(x3)
1704
+ else:
1705
+ x1, x2, x3, x4 = self.bb(x)
1706
+
1707
+ x4 = self.squeeze_module(x4)
1708
+
1709
+ ########## Decoder ##########
1710
+
1711
+ features = [x, x1, x2, x3, x4]
1712
+ scaled_preds = self.decoder(features)
1713
+
1714
+ return scaled_preds
1715
+
1716
+
1717
+ class Refiner(nn.Module):
1718
+ def __init__(self, in_channels=3+1):
1719
+ super(Refiner, self).__init__()
1720
+ self.config = Config()
1721
+ self.epoch = 1
1722
+ self.stem_layer = StemLayer(in_channels=in_channels, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
1723
+ self.bb = build_backbone(self.config.bb)
1724
+
1725
+ lateral_channels_in_collection = {
1726
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1727
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1728
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1729
+ }
1730
+ channels = lateral_channels_in_collection[self.config.bb]
1731
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1732
+
1733
+ self.decoder = Decoder(channels)
1734
+
1735
+ if 0:
1736
+ for key, value in self.named_parameters():
1737
+ if 'bb.' in key:
1738
+ value.requires_grad = False
1739
+
1740
+ def forward(self, x):
1741
+ if isinstance(x, list):
1742
+ x = torch.cat(x, dim=1)
1743
+ x = self.stem_layer(x)
1744
+ ########## Encoder ##########
1745
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1746
+ x1 = self.bb.conv1(x)
1747
+ x2 = self.bb.conv2(x1)
1748
+ x3 = self.bb.conv3(x2)
1749
+ x4 = self.bb.conv4(x3)
1750
+ else:
1751
+ x1, x2, x3, x4 = self.bb(x)
1752
+
1753
+ x4 = self.squeeze_module(x4)
1754
+
1755
+ ########## Decoder ##########
1756
+
1757
+ features = [x, x1, x2, x3, x4]
1758
+ scaled_preds = self.decoder(features)
1759
+
1760
+ return scaled_preds
1761
+
1762
+
1763
+ class Decoder(nn.Module):
1764
+ def __init__(self, channels):
1765
+ super(Decoder, self).__init__()
1766
+ self.config = Config()
1767
+ DecoderBlock = eval('BasicDecBlk')
1768
+ LateralBlock = eval('BasicLatBlk')
1769
+
1770
+ self.decoder_block4 = DecoderBlock(channels[0], channels[1])
1771
+ self.decoder_block3 = DecoderBlock(channels[1], channels[2])
1772
+ self.decoder_block2 = DecoderBlock(channels[2], channels[3])
1773
+ self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2)
1774
+
1775
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
1776
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
1777
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
1778
+
1779
+ if self.config.ms_supervision:
1780
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
1781
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
1782
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
1783
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0))
1784
+
1785
+ def forward(self, features):
1786
+ x, x1, x2, x3, x4 = features
1787
+ outs = []
1788
+ p4 = self.decoder_block4(x4)
1789
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
1790
+ _p3 = _p4 + self.lateral_block4(x3)
1791
+
1792
+ p3 = self.decoder_block3(_p3)
1793
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
1794
+ _p2 = _p3 + self.lateral_block3(x2)
1795
+
1796
+ p2 = self.decoder_block2(_p2)
1797
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
1798
+ _p1 = _p2 + self.lateral_block2(x1)
1799
+
1800
+ _p1 = self.decoder_block1(_p1)
1801
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
1802
+ p1_out = self.conv_out1(_p1)
1803
+
1804
+ if self.config.ms_supervision:
1805
+ outs.append(self.conv_ms_spvn_4(p4))
1806
+ outs.append(self.conv_ms_spvn_3(p3))
1807
+ outs.append(self.conv_ms_spvn_2(p2))
1808
+ outs.append(p1_out)
1809
+ return outs
1810
+
1811
+
1812
+ class RefUNet(nn.Module):
1813
+ # Refinement
1814
+ def __init__(self, in_channels=3+1):
1815
+ super(RefUNet, self).__init__()
1816
+ self.encoder_1 = nn.Sequential(
1817
+ nn.Conv2d(in_channels, 64, 3, 1, 1),
1818
+ nn.Conv2d(64, 64, 3, 1, 1),
1819
+ nn.BatchNorm2d(64),
1820
+ nn.ReLU(inplace=True)
1821
+ )
1822
+
1823
+ self.encoder_2 = nn.Sequential(
1824
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1825
+ nn.Conv2d(64, 64, 3, 1, 1),
1826
+ nn.BatchNorm2d(64),
1827
+ nn.ReLU(inplace=True)
1828
+ )
1829
+
1830
+ self.encoder_3 = nn.Sequential(
1831
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1832
+ nn.Conv2d(64, 64, 3, 1, 1),
1833
+ nn.BatchNorm2d(64),
1834
+ nn.ReLU(inplace=True)
1835
+ )
1836
+
1837
+ self.encoder_4 = nn.Sequential(
1838
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1839
+ nn.Conv2d(64, 64, 3, 1, 1),
1840
+ nn.BatchNorm2d(64),
1841
+ nn.ReLU(inplace=True)
1842
+ )
1843
+
1844
+ self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True)
1845
+ #####
1846
+ self.decoder_5 = nn.Sequential(
1847
+ nn.Conv2d(64, 64, 3, 1, 1),
1848
+ nn.BatchNorm2d(64),
1849
+ nn.ReLU(inplace=True)
1850
+ )
1851
+ #####
1852
+ self.decoder_4 = nn.Sequential(
1853
+ nn.Conv2d(128, 64, 3, 1, 1),
1854
+ nn.BatchNorm2d(64),
1855
+ nn.ReLU(inplace=True)
1856
+ )
1857
+
1858
+ self.decoder_3 = nn.Sequential(
1859
+ nn.Conv2d(128, 64, 3, 1, 1),
1860
+ nn.BatchNorm2d(64),
1861
+ nn.ReLU(inplace=True)
1862
+ )
1863
+
1864
+ self.decoder_2 = nn.Sequential(
1865
+ nn.Conv2d(128, 64, 3, 1, 1),
1866
+ nn.BatchNorm2d(64),
1867
+ nn.ReLU(inplace=True)
1868
+ )
1869
+
1870
+ self.decoder_1 = nn.Sequential(
1871
+ nn.Conv2d(128, 64, 3, 1, 1),
1872
+ nn.BatchNorm2d(64),
1873
+ nn.ReLU(inplace=True)
1874
+ )
1875
+
1876
+ self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1)
1877
+
1878
+ self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
1879
+
1880
+ def forward(self, x):
1881
+ outs = []
1882
+ if isinstance(x, list):
1883
+ x = torch.cat(x, dim=1)
1884
+ hx = x
1885
+
1886
+ hx1 = self.encoder_1(hx)
1887
+ hx2 = self.encoder_2(hx1)
1888
+ hx3 = self.encoder_3(hx2)
1889
+ hx4 = self.encoder_4(hx3)
1890
+
1891
+ hx = self.decoder_5(self.pool4(hx4))
1892
+ hx = torch.cat((self.upscore2(hx), hx4), 1)
1893
+
1894
+ d4 = self.decoder_4(hx)
1895
+ hx = torch.cat((self.upscore2(d4), hx3), 1)
1896
+
1897
+ d3 = self.decoder_3(hx)
1898
+ hx = torch.cat((self.upscore2(d3), hx2), 1)
1899
+
1900
+ d2 = self.decoder_2(hx)
1901
+ hx = torch.cat((self.upscore2(d2), hx1), 1)
1902
+
1903
+ d1 = self.decoder_1(hx)
1904
+
1905
+ x = self.conv_d0(d1)
1906
+ outs.append(x)
1907
+ return outs
1908
+
1909
+
1910
+
1911
+ ### models/stem_layer.py
1912
+
1913
+ import torch.nn as nn
1914
+ # from utils import build_act_layer, build_norm_layer
1915
+
1916
+
1917
+ class StemLayer(nn.Module):
1918
+ r""" Stem layer of InternImage
1919
+ Args:
1920
+ in_channels (int): number of input channels
1921
+ out_channels (int): number of output channels
1922
+ act_layer (str): activation layer
1923
+ norm_layer (str): normalization layer
1924
+ """
1925
+
1926
+ def __init__(self,
1927
+ in_channels=3+1,
1928
+ inter_channels=48,
1929
+ out_channels=96,
1930
+ act_layer='GELU',
1931
+ norm_layer='BN'):
1932
+ super().__init__()
1933
+ self.conv1 = nn.Conv2d(in_channels,
1934
+ inter_channels,
1935
+ kernel_size=3,
1936
+ stride=1,
1937
+ padding=1)
1938
+ self.norm1 = build_norm_layer(
1939
+ inter_channels, norm_layer, 'channels_first', 'channels_first'
1940
+ )
1941
+ self.act = build_act_layer(act_layer)
1942
+ self.conv2 = nn.Conv2d(inter_channels,
1943
+ out_channels,
1944
+ kernel_size=3,
1945
+ stride=1,
1946
+ padding=1)
1947
+ self.norm2 = build_norm_layer(
1948
+ out_channels, norm_layer, 'channels_first', 'channels_first'
1949
+ )
1950
+
1951
+ def forward(self, x):
1952
+ x = self.conv1(x)
1953
+ x = self.norm1(x)
1954
+ x = self.act(x)
1955
+ x = self.conv2(x)
1956
+ x = self.norm2(x)
1957
+ return x
1958
+
1959
+
1960
+ ### models/birefnet.py
1961
+
1962
+ import torch
1963
+ import torch.nn as nn
1964
+ import torch.nn.functional as F
1965
+ from kornia.filters import laplacian
1966
+ from transformers import PreTrainedModel
1967
+ from einops import rearrange
1968
+
1969
+ # from config import Config
1970
+ # from dataset import class_labels_TR_sorted
1971
+ # from models.build_backbone import build_backbone
1972
+ # from models.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk
1973
+ # from models.lateral_blocks import BasicLatBlk
1974
+ # from models.aspp import ASPP, ASPPDeformable
1975
+ # from models.ing import *
1976
+ # from models.refiner import Refiner, RefinerPVTInChannels4, RefUNet
1977
+ # from models.stem_layer import StemLayer
1978
+ from BiRefNet_config import BiRefNetConfig
1979
+
1980
+
1981
+ def image2patches(image, grid_h=2, grid_w=2, patch_ref=None, transformation='b c (hg h) (wg w) -> (b hg wg) c h w'):
1982
+ if patch_ref is not None:
1983
+ grid_h, grid_w = image.shape[-2] // patch_ref.shape[-2], image.shape[-1] // patch_ref.shape[-1]
1984
+ patches = rearrange(image, transformation, hg=grid_h, wg=grid_w)
1985
+ return patches
1986
+
1987
+ def patches2image(patches, grid_h=2, grid_w=2, patch_ref=None, transformation='(b hg wg) c h w -> b c (hg h) (wg w)'):
1988
+ if patch_ref is not None:
1989
+ grid_h, grid_w = patch_ref.shape[-2] // patches[0].shape[-2], patch_ref.shape[-1] // patches[0].shape[-1]
1990
+ image = rearrange(patches, transformation, hg=grid_h, wg=grid_w)
1991
+ return image
1992
+
1993
+ class BiRefNet(
1994
+ PreTrainedModel
1995
+ ):
1996
+ config_class = BiRefNetConfig
1997
+ def __init__(self, bb_pretrained=True, config=BiRefNetConfig()):
1998
+ super(BiRefNet, self).__init__(config)
1999
+ bb_pretrained = config.bb_pretrained
2000
+ self.config = Config()
2001
+ self.epoch = 1
2002
+ self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained)
2003
+
2004
+ channels = self.config.lateral_channels_in_collection
2005
+
2006
+ if self.config.auxiliary_classification:
2007
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
2008
+ self.cls_head = nn.Sequential(
2009
+ nn.Linear(channels[0], len(class_labels_TR_sorted))
2010
+ )
2011
+
2012
+ if self.config.squeeze_block:
2013
+ self.squeeze_module = nn.Sequential(*[
2014
+ eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0])
2015
+ for _ in range(eval(self.config.squeeze_block.split('_x')[1]))
2016
+ ])
2017
+
2018
+ self.decoder = Decoder(channels)
2019
+
2020
+ if self.config.ender:
2021
+ self.dec_end = nn.Sequential(
2022
+ nn.Conv2d(1, 16, 3, 1, 1),
2023
+ nn.Conv2d(16, 1, 3, 1, 1),
2024
+ nn.ReLU(inplace=True),
2025
+ )
2026
+
2027
+ # refine patch-level segmentation
2028
+ if self.config.refine:
2029
+ if self.config.refine == 'itself':
2030
+ self.stem_layer = StemLayer(in_channels=3+1, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
2031
+ else:
2032
+ self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1'))
2033
+
2034
+ if self.config.freeze_bb:
2035
+ # Freeze the backbone...
2036
+ print(self.named_parameters())
2037
+ for key, value in self.named_parameters():
2038
+ if 'bb.' in key and 'refiner.' not in key:
2039
+ value.requires_grad = False
2040
+
2041
+ def forward_enc(self, x):
2042
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
2043
+ x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3)
2044
+ else:
2045
+ x1, x2, x3, x4 = self.bb(x)
2046
+ if self.config.mul_scl_ipt == 'cat':
2047
+ B, C, H, W = x.shape
2048
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2049
+ x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2050
+ x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2051
+ x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2052
+ x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2053
+ elif self.config.mul_scl_ipt == 'add':
2054
+ B, C, H, W = x.shape
2055
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2056
+ x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)
2057
+ x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)
2058
+ x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)
2059
+ x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)
2060
+ class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None
2061
+ if self.config.cxt:
2062
+ x4 = torch.cat(
2063
+ (
2064
+ *[
2065
+ F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True),
2066
+ F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True),
2067
+ F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True),
2068
+ ][-len(self.config.cxt):],
2069
+ x4
2070
+ ),
2071
+ dim=1
2072
+ )
2073
+ return (x1, x2, x3, x4), class_preds
2074
+
2075
+ def forward_ori(self, x):
2076
+ ########## Encoder ##########
2077
+ (x1, x2, x3, x4), class_preds = self.forward_enc(x)
2078
+ if self.config.squeeze_block:
2079
+ x4 = self.squeeze_module(x4)
2080
+ ########## Decoder ##########
2081
+ features = [x, x1, x2, x3, x4]
2082
+ if self.training and self.config.out_ref:
2083
+ features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5))
2084
+ scaled_preds = self.decoder(features)
2085
+ return scaled_preds, class_preds
2086
+
2087
+ def forward(self, x):
2088
+ scaled_preds, class_preds = self.forward_ori(x)
2089
+ class_preds_lst = [class_preds]
2090
+ return [scaled_preds, class_preds_lst] if self.training else scaled_preds
2091
+
2092
+
2093
+ class Decoder(nn.Module):
2094
+ def __init__(self, channels):
2095
+ super(Decoder, self).__init__()
2096
+ self.config = Config()
2097
+ DecoderBlock = eval(self.config.dec_blk)
2098
+ LateralBlock = eval(self.config.lat_blk)
2099
+
2100
+ if self.config.dec_ipt:
2101
+ self.split = self.config.dec_ipt_split
2102
+ N_dec_ipt = 64
2103
+ DBlock = SimpleConvs
2104
+ ic = 64
2105
+ ipt_cha_opt = 1
2106
+ self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2107
+ self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2108
+ self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic)
2109
+ self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic)
2110
+ self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic)
2111
+ else:
2112
+ self.split = None
2113
+
2114
+ self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1])
2115
+ self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2])
2116
+ self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3])
2117
+ self.decoder_block1 = DecoderBlock(channels[3]+([N_dec_ipt, channels[2]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]//2)
2118
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2+([N_dec_ipt, channels[3]//8][ipt_cha_opt] if self.config.dec_ipt else 0), 1, 1, 1, 0))
2119
+
2120
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
2121
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
2122
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
2123
+
2124
+ if self.config.ms_supervision:
2125
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
2126
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
2127
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
2128
+
2129
+ if self.config.out_ref:
2130
+ _N = 16
2131
+ self.gdt_convs_4 = nn.Sequential(nn.Conv2d(channels[1], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2132
+ self.gdt_convs_3 = nn.Sequential(nn.Conv2d(channels[2], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2133
+ self.gdt_convs_2 = nn.Sequential(nn.Conv2d(channels[3], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2134
+
2135
+ self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2136
+ self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2137
+ self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2138
+
2139
+ self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2140
+ self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2141
+ self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2142
+
2143
+ def forward(self, features):
2144
+ if self.training and self.config.out_ref:
2145
+ outs_gdt_pred = []
2146
+ outs_gdt_label = []
2147
+ x, x1, x2, x3, x4, gdt_gt = features
2148
+ else:
2149
+ x, x1, x2, x3, x4 = features
2150
+ outs = []
2151
+
2152
+ if self.config.dec_ipt:
2153
+ patches_batch = image2patches(x, patch_ref=x4, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2154
+ x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1)
2155
+ p4 = self.decoder_block4(x4)
2156
+ m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision and self.training else None
2157
+ if self.config.out_ref:
2158
+ p4_gdt = self.gdt_convs_4(p4)
2159
+ if self.training:
2160
+ # >> GT:
2161
+ m4_dia = m4
2162
+ gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2163
+ outs_gdt_label.append(gdt_label_main_4)
2164
+ # >> Pred:
2165
+ gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt)
2166
+ outs_gdt_pred.append(gdt_pred_4)
2167
+ gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid()
2168
+ # >> Finally:
2169
+ p4 = p4 * gdt_attn_4
2170
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
2171
+ _p3 = _p4 + self.lateral_block4(x3)
2172
+
2173
+ if self.config.dec_ipt:
2174
+ patches_batch = image2patches(x, patch_ref=_p3, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2175
+ _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1)
2176
+ p3 = self.decoder_block3(_p3)
2177
+ m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision and self.training else None
2178
+ if self.config.out_ref:
2179
+ p3_gdt = self.gdt_convs_3(p3)
2180
+ if self.training:
2181
+ # >> GT:
2182
+ # m3 --dilation--> m3_dia
2183
+ # G_3^gt * m3_dia --> G_3^m, which is the label of gradient
2184
+ m3_dia = m3
2185
+ gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2186
+ outs_gdt_label.append(gdt_label_main_3)
2187
+ # >> Pred:
2188
+ # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx
2189
+ # F_3^G --sigmoid--> A_3^G
2190
+ gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt)
2191
+ outs_gdt_pred.append(gdt_pred_3)
2192
+ gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid()
2193
+ # >> Finally:
2194
+ # p3 = p3 * A_3^G
2195
+ p3 = p3 * gdt_attn_3
2196
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
2197
+ _p2 = _p3 + self.lateral_block3(x2)
2198
+
2199
+ if self.config.dec_ipt:
2200
+ patches_batch = image2patches(x, patch_ref=_p2, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2201
+ _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1)
2202
+ p2 = self.decoder_block2(_p2)
2203
+ m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision and self.training else None
2204
+ if self.config.out_ref:
2205
+ p2_gdt = self.gdt_convs_2(p2)
2206
+ if self.training:
2207
+ # >> GT:
2208
+ m2_dia = m2
2209
+ gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2210
+ outs_gdt_label.append(gdt_label_main_2)
2211
+ # >> Pred:
2212
+ gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt)
2213
+ outs_gdt_pred.append(gdt_pred_2)
2214
+ gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid()
2215
+ # >> Finally:
2216
+ p2 = p2 * gdt_attn_2
2217
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
2218
+ _p1 = _p2 + self.lateral_block2(x1)
2219
+
2220
+ if self.config.dec_ipt:
2221
+ patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2222
+ _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1)
2223
+ _p1 = self.decoder_block1(_p1)
2224
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
2225
+
2226
+ if self.config.dec_ipt:
2227
+ patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2228
+ _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1)
2229
+ p1_out = self.conv_out1(_p1)
2230
+
2231
+ if self.config.ms_supervision and self.training:
2232
+ outs.append(m4)
2233
+ outs.append(m3)
2234
+ outs.append(m2)
2235
+ outs.append(p1_out)
2236
+ return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs)
2237
+
2238
+
2239
+ class SimpleConvs(nn.Module):
2240
+ def __init__(
2241
+ self, in_channels: int, out_channels: int, inter_channels=64
2242
+ ) -> None:
2243
+ super().__init__()
2244
+ self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1)
2245
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
2246
+
2247
+ def forward(self, x):
2248
+ return self.conv_out(self.conv1(x))
models/RMBG/BiRefNet/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "1038lab/BiRefNet",
3
+ "architectures": [
4
+ "BiRefNet"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "BiRefNet_config.BiRefNetConfig",
8
+ "AutoModelForImageSegmentation": "birefnet.BiRefNet"
9
+ },
10
+ "custom_pipelines": {
11
+ "image-segmentation": {
12
+ "pt": [
13
+ "AutoModelForImageSegmentation"
14
+ ],
15
+ "tf": [],
16
+ "type": "image"
17
+ }
18
+ },
19
+ "bb_pretrained": false
20
+ }
models/RMBG/BiRefNet/gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
models/RMBG/INSPYRENET/gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
models/RMBG/INSPYRENET/inspyrenet.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a6fe2a73ab0532d6d0b8d82849a9760a226df719e3063d09b4149ece6f80fcd
3
+ size 367520613
models/RMBG/INSPYRENET/inspyrenet.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c8ab4541f9a960b376a80362b07f1d96262e689c501365e6323faa958de47ea
3
+ size 367120444
models/RMBG/RMBG-2.0/BiRefNet_config.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class BiRefNetConfig(PretrainedConfig):
4
+ model_type = "SegformerForSemanticSegmentation"
5
+ def __init__(
6
+ self,
7
+ bb_pretrained=False,
8
+ **kwargs
9
+ ):
10
+ self.bb_pretrained = bb_pretrained
11
+ super().__init__(**kwargs)
models/RMBG/RMBG-2.0/__pycache__/BiRefNet_config.cpython-310.pyc ADDED
Binary file (648 Bytes). View file
 
models/RMBG/RMBG-2.0/birefnet.py ADDED
@@ -0,0 +1,2244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### config.py
2
+
3
+ import os
4
+ import math
5
+
6
+
7
+ class Config():
8
+ def __init__(self) -> None:
9
+ # PATH settings
10
+ self.sys_home_dir = os.path.expanduser('~') # Make up your file system as: SYS_HOME_DIR/codes/dis/BiRefNet, SYS_HOME_DIR/datasets/dis/xx, SYS_HOME_DIR/weights/xx
11
+
12
+ # TASK settings
13
+ self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0]
14
+ self.training_set = {
15
+ 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0],
16
+ 'COD': 'TR-COD10K+TR-CAMO',
17
+ 'HRSOD': ['TR-DUTS', 'TR-HRSOD', 'TR-UHRSD', 'TR-DUTS+TR-HRSOD', 'TR-DUTS+TR-UHRSD', 'TR-HRSOD+TR-UHRSD', 'TR-DUTS+TR-HRSOD+TR-UHRSD'][5],
18
+ 'DIS5K+HRSOD+HRS10K': 'DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4+DIS-TR+TE-HRS10K+TE-HRSOD+TE-UHRSD+TR-HRS10K+TR-HRSOD+TR-UHRSD', # leave DIS-VD for evaluation.
19
+ 'P3M-10k': 'TR-P3M-10k',
20
+ }[self.task]
21
+ self.prompt4loc = ['dense', 'sparse'][0]
22
+
23
+ # Faster-Training settings
24
+ self.load_all = True
25
+ self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch.
26
+ # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting.
27
+ # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607.
28
+ # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training.
29
+ self.precisionHigh = True
30
+
31
+ # MODEL settings
32
+ self.ms_supervision = True
33
+ self.out_ref = self.ms_supervision and True
34
+ self.dec_ipt = True
35
+ self.dec_ipt_split = True
36
+ self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder
37
+ self.mul_scl_ipt = ['', 'add', 'cat'][2]
38
+ self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2]
39
+ self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1]
40
+ self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]
41
+
42
+ # TRAINING settings
43
+ self.batch_size = 4
44
+ self.IoU_finetune_last_epochs = [
45
+ 0,
46
+ {
47
+ 'DIS5K': -50,
48
+ 'COD': -20,
49
+ 'HRSOD': -20,
50
+ 'DIS5K+HRSOD+HRS10K': -20,
51
+ 'P3M-10k': -20,
52
+ }[self.task]
53
+ ][1] # choose 0 to skip
54
+ self.lr = (1e-4 if 'DIS5K' in self.task else 1e-5) * math.sqrt(self.batch_size / 4) # DIS needs high lr to converge faster. Adapt the lr linearly
55
+ self.size = 1024
56
+ self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader
57
+
58
+ # Backbone settings
59
+ self.bb = [
60
+ 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2
61
+ 'swin_v1_t', 'swin_v1_s', # 3, 4
62
+ 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4
63
+ 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8
64
+ 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5
65
+ ][6]
66
+ self.lateral_channels_in_collection = {
67
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
68
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
69
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
70
+ 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96],
71
+ 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64],
72
+ }[self.bb]
73
+ if self.mul_scl_ipt == 'cat':
74
+ self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection]
75
+ self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
76
+
77
+ # MODEL settings - inactive
78
+ self.lat_blk = ['BasicLatBlk'][0]
79
+ self.dec_channels_inter = ['fixed', 'adap'][0]
80
+ self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0]
81
+ self.progressive_ref = self.refine and True
82
+ self.ender = self.progressive_ref and False
83
+ self.scale = self.progressive_ref and 2
84
+ self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`.
85
+ self.refine_iteration = 1
86
+ self.freeze_bb = False
87
+ self.model = [
88
+ 'BiRefNet',
89
+ ][0]
90
+ if self.dec_blk == 'HierarAttDecBlk':
91
+ self.batch_size = 2 ** [0, 1, 2, 3, 4][2]
92
+
93
+ # TRAINING settings - inactive
94
+ self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4]
95
+ self.optimizer = ['Adam', 'AdamW'][1]
96
+ self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch.
97
+ self.lr_decay_rate = 0.5
98
+ # Loss
99
+ self.lambdas_pix_last = {
100
+ # not 0 means opening this loss
101
+ # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30
102
+ 'bce': 30 * 1, # high performance
103
+ 'iou': 0.5 * 1, # 0 / 255
104
+ 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64)
105
+ 'mse': 150 * 0, # can smooth the saliency map
106
+ 'triplet': 3 * 0,
107
+ 'reg': 100 * 0,
108
+ 'ssim': 10 * 1, # help contours,
109
+ 'cnt': 5 * 0, # help contours
110
+ 'structure': 5 * 0, # structure loss from codes of MVANet. A little improvement on DIS-TE[1,2,3], a bit more decrease on DIS-TE4.
111
+ }
112
+ self.lambdas_cls = {
113
+ 'ce': 5.0
114
+ }
115
+ # Adv
116
+ self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training
117
+ self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)
118
+
119
+ # PATH settings - inactive
120
+ self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis')
121
+ self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights')
122
+ self.weights = {
123
+ 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'),
124
+ 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]),
125
+ 'swin_v1_b': os.path.join(self.weights_root_dir, ['swin_base_patch4_window12_384_22kto1k.pth', 'swin_base_patch4_window12_384_22k.pth'][0]),
126
+ 'swin_v1_l': os.path.join(self.weights_root_dir, ['swin_large_patch4_window12_384_22kto1k.pth', 'swin_large_patch4_window12_384_22k.pth'][0]),
127
+ 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]),
128
+ 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]),
129
+ 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]),
130
+ 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]),
131
+ }
132
+
133
+ # Callbacks - inactive
134
+ self.verbose_eval = True
135
+ self.only_S_MAE = False
136
+ self.use_fp16 = False # Bugs. It may cause nan in training.
137
+ self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs
138
+
139
+ # others
140
+ self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
141
+
142
+ self.batch_size_valid = 1
143
+ self.rand_seed = 7
144
+ # run_sh_file = [f for f in os.listdir('.') if 'train.sh' == f] + [os.path.join('..', f) for f in os.listdir('..') if 'train.sh' == f]
145
+ # with open(run_sh_file[0], 'r') as f:
146
+ # lines = f.readlines()
147
+ # self.save_last = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'val_last=' in l][0].split('val_last=')[-1].split()[0])
148
+ # self.save_step = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'step=' in l][0].split('step=')[-1].split()[0])
149
+ # self.val_step = [0, self.save_step][0]
150
+
151
+ def print_task(self) -> None:
152
+ # Return task for choosing settings in shell scripts.
153
+ print(self.task)
154
+
155
+
156
+
157
+ ### models/backbones/pvt_v2.py
158
+
159
+ import torch
160
+ import torch.nn as nn
161
+ from functools import partial
162
+
163
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
164
+ from timm.models.registry import register_model
165
+
166
+ import math
167
+
168
+ # from config import Config
169
+
170
+ # config = Config()
171
+
172
+ class Mlp(nn.Module):
173
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
174
+ super().__init__()
175
+ out_features = out_features or in_features
176
+ hidden_features = hidden_features or in_features
177
+ self.fc1 = nn.Linear(in_features, hidden_features)
178
+ self.dwconv = DWConv(hidden_features)
179
+ self.act = act_layer()
180
+ self.fc2 = nn.Linear(hidden_features, out_features)
181
+ self.drop = nn.Dropout(drop)
182
+
183
+ self.apply(self._init_weights)
184
+
185
+ def _init_weights(self, m):
186
+ if isinstance(m, nn.Linear):
187
+ trunc_normal_(m.weight, std=.02)
188
+ if isinstance(m, nn.Linear) and m.bias is not None:
189
+ nn.init.constant_(m.bias, 0)
190
+ elif isinstance(m, nn.LayerNorm):
191
+ nn.init.constant_(m.bias, 0)
192
+ nn.init.constant_(m.weight, 1.0)
193
+ elif isinstance(m, nn.Conv2d):
194
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
195
+ fan_out //= m.groups
196
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
197
+ if m.bias is not None:
198
+ m.bias.data.zero_()
199
+
200
+ def forward(self, x, H, W):
201
+ x = self.fc1(x)
202
+ x = self.dwconv(x, H, W)
203
+ x = self.act(x)
204
+ x = self.drop(x)
205
+ x = self.fc2(x)
206
+ x = self.drop(x)
207
+ return x
208
+
209
+
210
+ class Attention(nn.Module):
211
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
212
+ super().__init__()
213
+ assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
214
+
215
+ self.dim = dim
216
+ self.num_heads = num_heads
217
+ head_dim = dim // num_heads
218
+ self.scale = qk_scale or head_dim ** -0.5
219
+
220
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
221
+ self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
222
+ self.attn_drop_prob = attn_drop
223
+ self.attn_drop = nn.Dropout(attn_drop)
224
+ self.proj = nn.Linear(dim, dim)
225
+ self.proj_drop = nn.Dropout(proj_drop)
226
+
227
+ self.sr_ratio = sr_ratio
228
+ if sr_ratio > 1:
229
+ self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
230
+ self.norm = nn.LayerNorm(dim)
231
+
232
+ self.apply(self._init_weights)
233
+
234
+ def _init_weights(self, m):
235
+ if isinstance(m, nn.Linear):
236
+ trunc_normal_(m.weight, std=.02)
237
+ if isinstance(m, nn.Linear) and m.bias is not None:
238
+ nn.init.constant_(m.bias, 0)
239
+ elif isinstance(m, nn.LayerNorm):
240
+ nn.init.constant_(m.bias, 0)
241
+ nn.init.constant_(m.weight, 1.0)
242
+ elif isinstance(m, nn.Conv2d):
243
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
244
+ fan_out //= m.groups
245
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
246
+ if m.bias is not None:
247
+ m.bias.data.zero_()
248
+
249
+ def forward(self, x, H, W):
250
+ B, N, C = x.shape
251
+ q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
252
+
253
+ if self.sr_ratio > 1:
254
+ x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
255
+ x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
256
+ x_ = self.norm(x_)
257
+ kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
258
+ else:
259
+ kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
260
+ k, v = kv[0], kv[1]
261
+
262
+ if config.SDPA_enabled:
263
+ x = torch.nn.functional.scaled_dot_product_attention(
264
+ q, k, v,
265
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
266
+ ).transpose(1, 2).reshape(B, N, C)
267
+ else:
268
+ attn = (q @ k.transpose(-2, -1)) * self.scale
269
+ attn = attn.softmax(dim=-1)
270
+ attn = self.attn_drop(attn)
271
+
272
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
273
+ x = self.proj(x)
274
+ x = self.proj_drop(x)
275
+
276
+ return x
277
+
278
+
279
+ class Block(nn.Module):
280
+
281
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
282
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
283
+ super().__init__()
284
+ self.norm1 = norm_layer(dim)
285
+ self.attn = Attention(
286
+ dim,
287
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
288
+ attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
289
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
290
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
291
+ self.norm2 = norm_layer(dim)
292
+ mlp_hidden_dim = int(dim * mlp_ratio)
293
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
294
+
295
+ self.apply(self._init_weights)
296
+
297
+ def _init_weights(self, m):
298
+ if isinstance(m, nn.Linear):
299
+ trunc_normal_(m.weight, std=.02)
300
+ if isinstance(m, nn.Linear) and m.bias is not None:
301
+ nn.init.constant_(m.bias, 0)
302
+ elif isinstance(m, nn.LayerNorm):
303
+ nn.init.constant_(m.bias, 0)
304
+ nn.init.constant_(m.weight, 1.0)
305
+ elif isinstance(m, nn.Conv2d):
306
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
307
+ fan_out //= m.groups
308
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
309
+ if m.bias is not None:
310
+ m.bias.data.zero_()
311
+
312
+ def forward(self, x, H, W):
313
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
314
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
315
+
316
+ return x
317
+
318
+
319
+ class OverlapPatchEmbed(nn.Module):
320
+ """ Image to Patch Embedding
321
+ """
322
+
323
+ def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768):
324
+ super().__init__()
325
+ img_size = to_2tuple(img_size)
326
+ patch_size = to_2tuple(patch_size)
327
+
328
+ self.img_size = img_size
329
+ self.patch_size = patch_size
330
+ self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
331
+ self.num_patches = self.H * self.W
332
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride,
333
+ padding=(patch_size[0] // 2, patch_size[1] // 2))
334
+ self.norm = nn.LayerNorm(embed_dim)
335
+
336
+ self.apply(self._init_weights)
337
+
338
+ def _init_weights(self, m):
339
+ if isinstance(m, nn.Linear):
340
+ trunc_normal_(m.weight, std=.02)
341
+ if isinstance(m, nn.Linear) and m.bias is not None:
342
+ nn.init.constant_(m.bias, 0)
343
+ elif isinstance(m, nn.LayerNorm):
344
+ nn.init.constant_(m.bias, 0)
345
+ nn.init.constant_(m.weight, 1.0)
346
+ elif isinstance(m, nn.Conv2d):
347
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
348
+ fan_out //= m.groups
349
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
350
+ if m.bias is not None:
351
+ m.bias.data.zero_()
352
+
353
+ def forward(self, x):
354
+ x = self.proj(x)
355
+ _, _, H, W = x.shape
356
+ x = x.flatten(2).transpose(1, 2)
357
+ x = self.norm(x)
358
+
359
+ return x, H, W
360
+
361
+
362
+ class PyramidVisionTransformerImpr(nn.Module):
363
+ def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
364
+ num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
365
+ attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
366
+ depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
367
+ super().__init__()
368
+ self.num_classes = num_classes
369
+ self.depths = depths
370
+
371
+ # patch_embed
372
+ self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels,
373
+ embed_dim=embed_dims[0])
374
+ self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0],
375
+ embed_dim=embed_dims[1])
376
+ self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1],
377
+ embed_dim=embed_dims[2])
378
+ self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2],
379
+ embed_dim=embed_dims[3])
380
+
381
+ # transformer encoder
382
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
383
+ cur = 0
384
+ self.block1 = nn.ModuleList([Block(
385
+ dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
386
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
387
+ sr_ratio=sr_ratios[0])
388
+ for i in range(depths[0])])
389
+ self.norm1 = norm_layer(embed_dims[0])
390
+
391
+ cur += depths[0]
392
+ self.block2 = nn.ModuleList([Block(
393
+ dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
394
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
395
+ sr_ratio=sr_ratios[1])
396
+ for i in range(depths[1])])
397
+ self.norm2 = norm_layer(embed_dims[1])
398
+
399
+ cur += depths[1]
400
+ self.block3 = nn.ModuleList([Block(
401
+ dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
402
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
403
+ sr_ratio=sr_ratios[2])
404
+ for i in range(depths[2])])
405
+ self.norm3 = norm_layer(embed_dims[2])
406
+
407
+ cur += depths[2]
408
+ self.block4 = nn.ModuleList([Block(
409
+ dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
410
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
411
+ sr_ratio=sr_ratios[3])
412
+ for i in range(depths[3])])
413
+ self.norm4 = norm_layer(embed_dims[3])
414
+
415
+ # classification head
416
+ # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
417
+
418
+ self.apply(self._init_weights)
419
+
420
+ def _init_weights(self, m):
421
+ if isinstance(m, nn.Linear):
422
+ trunc_normal_(m.weight, std=.02)
423
+ if isinstance(m, nn.Linear) and m.bias is not None:
424
+ nn.init.constant_(m.bias, 0)
425
+ elif isinstance(m, nn.LayerNorm):
426
+ nn.init.constant_(m.bias, 0)
427
+ nn.init.constant_(m.weight, 1.0)
428
+ elif isinstance(m, nn.Conv2d):
429
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
430
+ fan_out //= m.groups
431
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
432
+ if m.bias is not None:
433
+ m.bias.data.zero_()
434
+
435
+ def init_weights(self, pretrained=None):
436
+ if isinstance(pretrained, str):
437
+ logger = 1
438
+ #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
439
+
440
+ def reset_drop_path(self, drop_path_rate):
441
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
442
+ cur = 0
443
+ for i in range(self.depths[0]):
444
+ self.block1[i].drop_path.drop_prob = dpr[cur + i]
445
+
446
+ cur += self.depths[0]
447
+ for i in range(self.depths[1]):
448
+ self.block2[i].drop_path.drop_prob = dpr[cur + i]
449
+
450
+ cur += self.depths[1]
451
+ for i in range(self.depths[2]):
452
+ self.block3[i].drop_path.drop_prob = dpr[cur + i]
453
+
454
+ cur += self.depths[2]
455
+ for i in range(self.depths[3]):
456
+ self.block4[i].drop_path.drop_prob = dpr[cur + i]
457
+
458
+ def freeze_patch_emb(self):
459
+ self.patch_embed1.requires_grad = False
460
+
461
+ @torch.jit.ignore
462
+ def no_weight_decay(self):
463
+ return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
464
+
465
+ def get_classifier(self):
466
+ return self.head
467
+
468
+ def reset_classifier(self, num_classes, global_pool=''):
469
+ self.num_classes = num_classes
470
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
471
+
472
+ def forward_features(self, x):
473
+ B = x.shape[0]
474
+ outs = []
475
+
476
+ # stage 1
477
+ x, H, W = self.patch_embed1(x)
478
+ for i, blk in enumerate(self.block1):
479
+ x = blk(x, H, W)
480
+ x = self.norm1(x)
481
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
482
+ outs.append(x)
483
+
484
+ # stage 2
485
+ x, H, W = self.patch_embed2(x)
486
+ for i, blk in enumerate(self.block2):
487
+ x = blk(x, H, W)
488
+ x = self.norm2(x)
489
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
490
+ outs.append(x)
491
+
492
+ # stage 3
493
+ x, H, W = self.patch_embed3(x)
494
+ for i, blk in enumerate(self.block3):
495
+ x = blk(x, H, W)
496
+ x = self.norm3(x)
497
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
498
+ outs.append(x)
499
+
500
+ # stage 4
501
+ x, H, W = self.patch_embed4(x)
502
+ for i, blk in enumerate(self.block4):
503
+ x = blk(x, H, W)
504
+ x = self.norm4(x)
505
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
506
+ outs.append(x)
507
+
508
+ return outs
509
+
510
+ # return x.mean(dim=1)
511
+
512
+ def forward(self, x):
513
+ x = self.forward_features(x)
514
+ # x = self.head(x)
515
+
516
+ return x
517
+
518
+
519
+ class DWConv(nn.Module):
520
+ def __init__(self, dim=768):
521
+ super(DWConv, self).__init__()
522
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
523
+
524
+ def forward(self, x, H, W):
525
+ B, N, C = x.shape
526
+ x = x.transpose(1, 2).view(B, C, H, W).contiguous()
527
+ x = self.dwconv(x)
528
+ x = x.flatten(2).transpose(1, 2)
529
+
530
+ return x
531
+
532
+
533
+ def _conv_filter(state_dict, patch_size=16):
534
+ """ convert patch embedding weight from manual patchify + linear proj to conv"""
535
+ out_dict = {}
536
+ for k, v in state_dict.items():
537
+ if 'patch_embed.proj.weight' in k:
538
+ v = v.reshape((v.shape[0], 3, patch_size, patch_size))
539
+ out_dict[k] = v
540
+
541
+ return out_dict
542
+
543
+
544
+ ## @register_model
545
+ class pvt_v2_b0(PyramidVisionTransformerImpr):
546
+ def __init__(self, **kwargs):
547
+ super(pvt_v2_b0, self).__init__(
548
+ patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
549
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
550
+ drop_rate=0.0, drop_path_rate=0.1)
551
+
552
+
553
+
554
+ ## @register_model
555
+ class pvt_v2_b1(PyramidVisionTransformerImpr):
556
+ def __init__(self, **kwargs):
557
+ super(pvt_v2_b1, self).__init__(
558
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
559
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
560
+ drop_rate=0.0, drop_path_rate=0.1)
561
+
562
+ ## @register_model
563
+ class pvt_v2_b2(PyramidVisionTransformerImpr):
564
+ def __init__(self, in_channels=3, **kwargs):
565
+ super(pvt_v2_b2, self).__init__(
566
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
567
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],
568
+ drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
569
+
570
+ ## @register_model
571
+ class pvt_v2_b3(PyramidVisionTransformerImpr):
572
+ def __init__(self, **kwargs):
573
+ super(pvt_v2_b3, self).__init__(
574
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
575
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
576
+ drop_rate=0.0, drop_path_rate=0.1)
577
+
578
+ ## @register_model
579
+ class pvt_v2_b4(PyramidVisionTransformerImpr):
580
+ def __init__(self, **kwargs):
581
+ super(pvt_v2_b4, self).__init__(
582
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
583
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],
584
+ drop_rate=0.0, drop_path_rate=0.1)
585
+
586
+
587
+ ## @register_model
588
+ class pvt_v2_b5(PyramidVisionTransformerImpr):
589
+ def __init__(self, **kwargs):
590
+ super(pvt_v2_b5, self).__init__(
591
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
592
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
593
+ drop_rate=0.0, drop_path_rate=0.1)
594
+
595
+
596
+
597
+ ### models/backbones/swin_v1.py
598
+
599
+ # --------------------------------------------------------
600
+ # Swin Transformer
601
+ # Copyright (c) 2021 Microsoft
602
+ # Licensed under The MIT License [see LICENSE for details]
603
+ # Written by Ze Liu, Yutong Lin, Yixuan Wei
604
+ # --------------------------------------------------------
605
+
606
+ import torch
607
+ import torch.nn as nn
608
+ import torch.nn.functional as F
609
+ import torch.utils.checkpoint as checkpoint
610
+ import numpy as np
611
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
612
+
613
+ # from config import Config
614
+
615
+
616
+ # config = Config()
617
+
618
+ class Mlp(nn.Module):
619
+ """ Multilayer perceptron."""
620
+
621
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
622
+ super().__init__()
623
+ out_features = out_features or in_features
624
+ hidden_features = hidden_features or in_features
625
+ self.fc1 = nn.Linear(in_features, hidden_features)
626
+ self.act = act_layer()
627
+ self.fc2 = nn.Linear(hidden_features, out_features)
628
+ self.drop = nn.Dropout(drop)
629
+
630
+ def forward(self, x):
631
+ x = self.fc1(x)
632
+ x = self.act(x)
633
+ x = self.drop(x)
634
+ x = self.fc2(x)
635
+ x = self.drop(x)
636
+ return x
637
+
638
+
639
+ def window_partition(x, window_size):
640
+ """
641
+ Args:
642
+ x: (B, H, W, C)
643
+ window_size (int): window size
644
+
645
+ Returns:
646
+ windows: (num_windows*B, window_size, window_size, C)
647
+ """
648
+ B, H, W, C = x.shape
649
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
650
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
651
+ return windows
652
+
653
+
654
+ def window_reverse(windows, window_size, H, W):
655
+ """
656
+ Args:
657
+ windows: (num_windows*B, window_size, window_size, C)
658
+ window_size (int): Window size
659
+ H (int): Height of image
660
+ W (int): Width of image
661
+
662
+ Returns:
663
+ x: (B, H, W, C)
664
+ """
665
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
666
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
667
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
668
+ return x
669
+
670
+
671
+ class WindowAttention(nn.Module):
672
+ """ Window based multi-head self attention (W-MSA) module with relative position bias.
673
+ It supports both of shifted and non-shifted window.
674
+
675
+ Args:
676
+ dim (int): Number of input channels.
677
+ window_size (tuple[int]): The height and width of the window.
678
+ num_heads (int): Number of attention heads.
679
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
680
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
681
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
682
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
683
+ """
684
+
685
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
686
+
687
+ super().__init__()
688
+ self.dim = dim
689
+ self.window_size = window_size # Wh, Ww
690
+ self.num_heads = num_heads
691
+ head_dim = dim // num_heads
692
+ self.scale = qk_scale or head_dim ** -0.5
693
+
694
+ # define a parameter table of relative position bias
695
+ self.relative_position_bias_table = nn.Parameter(
696
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
697
+
698
+ # get pair-wise relative position index for each token inside the window
699
+ coords_h = torch.arange(self.window_size[0])
700
+ coords_w = torch.arange(self.window_size[1])
701
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww
702
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
703
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
704
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
705
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
706
+ relative_coords[:, :, 1] += self.window_size[1] - 1
707
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
708
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
709
+ self.register_buffer("relative_position_index", relative_position_index)
710
+
711
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
712
+ self.attn_drop_prob = attn_drop
713
+ self.attn_drop = nn.Dropout(attn_drop)
714
+ self.proj = nn.Linear(dim, dim)
715
+ self.proj_drop = nn.Dropout(proj_drop)
716
+
717
+ trunc_normal_(self.relative_position_bias_table, std=.02)
718
+ self.softmax = nn.Softmax(dim=-1)
719
+
720
+ def forward(self, x, mask=None):
721
+ """ Forward function.
722
+
723
+ Args:
724
+ x: input features with shape of (num_windows*B, N, C)
725
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
726
+ """
727
+ B_, N, C = x.shape
728
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
729
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
730
+
731
+ q = q * self.scale
732
+
733
+ if config.SDPA_enabled:
734
+ x = torch.nn.functional.scaled_dot_product_attention(
735
+ q, k, v,
736
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
737
+ ).transpose(1, 2).reshape(B_, N, C)
738
+ else:
739
+ attn = (q @ k.transpose(-2, -1))
740
+
741
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
742
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
743
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
744
+ attn = attn + relative_position_bias.unsqueeze(0)
745
+
746
+ if mask is not None:
747
+ nW = mask.shape[0]
748
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
749
+ attn = attn.view(-1, self.num_heads, N, N)
750
+ attn = self.softmax(attn)
751
+ else:
752
+ attn = self.softmax(attn)
753
+
754
+ attn = self.attn_drop(attn)
755
+
756
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
757
+ x = self.proj(x)
758
+ x = self.proj_drop(x)
759
+ return x
760
+
761
+
762
+ class SwinTransformerBlock(nn.Module):
763
+ """ Swin Transformer Block.
764
+
765
+ Args:
766
+ dim (int): Number of input channels.
767
+ num_heads (int): Number of attention heads.
768
+ window_size (int): Window size.
769
+ shift_size (int): Shift size for SW-MSA.
770
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
771
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
772
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
773
+ drop (float, optional): Dropout rate. Default: 0.0
774
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
775
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
776
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
777
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
778
+ """
779
+
780
+ def __init__(self, dim, num_heads, window_size=7, shift_size=0,
781
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
782
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
783
+ super().__init__()
784
+ self.dim = dim
785
+ self.num_heads = num_heads
786
+ self.window_size = window_size
787
+ self.shift_size = shift_size
788
+ self.mlp_ratio = mlp_ratio
789
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
790
+
791
+ self.norm1 = norm_layer(dim)
792
+ self.attn = WindowAttention(
793
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
794
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
795
+
796
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
797
+ self.norm2 = norm_layer(dim)
798
+ mlp_hidden_dim = int(dim * mlp_ratio)
799
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
800
+
801
+ self.H = None
802
+ self.W = None
803
+
804
+ def forward(self, x, mask_matrix):
805
+ """ Forward function.
806
+
807
+ Args:
808
+ x: Input feature, tensor size (B, H*W, C).
809
+ H, W: Spatial resolution of the input feature.
810
+ mask_matrix: Attention mask for cyclic shift.
811
+ """
812
+ B, L, C = x.shape
813
+ H, W = self.H, self.W
814
+ assert L == H * W, "input feature has wrong size"
815
+
816
+ shortcut = x
817
+ x = self.norm1(x)
818
+ x = x.view(B, H, W, C)
819
+
820
+ # pad feature maps to multiples of window size
821
+ pad_l = pad_t = 0
822
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
823
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
824
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
825
+ _, Hp, Wp, _ = x.shape
826
+
827
+ # cyclic shift
828
+ if self.shift_size > 0:
829
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
830
+ attn_mask = mask_matrix
831
+ else:
832
+ shifted_x = x
833
+ attn_mask = None
834
+
835
+ # partition windows
836
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
837
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
838
+
839
+ # W-MSA/SW-MSA
840
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
841
+
842
+ # merge windows
843
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
844
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
845
+
846
+ # reverse cyclic shift
847
+ if self.shift_size > 0:
848
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
849
+ else:
850
+ x = shifted_x
851
+
852
+ if pad_r > 0 or pad_b > 0:
853
+ x = x[:, :H, :W, :].contiguous()
854
+
855
+ x = x.view(B, H * W, C)
856
+
857
+ # FFN
858
+ x = shortcut + self.drop_path(x)
859
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
860
+
861
+ return x
862
+
863
+
864
+ class PatchMerging(nn.Module):
865
+ """ Patch Merging Layer
866
+
867
+ Args:
868
+ dim (int): Number of input channels.
869
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
870
+ """
871
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
872
+ super().__init__()
873
+ self.dim = dim
874
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
875
+ self.norm = norm_layer(4 * dim)
876
+
877
+ def forward(self, x, H, W):
878
+ """ Forward function.
879
+
880
+ Args:
881
+ x: Input feature, tensor size (B, H*W, C).
882
+ H, W: Spatial resolution of the input feature.
883
+ """
884
+ B, L, C = x.shape
885
+ assert L == H * W, "input feature has wrong size"
886
+
887
+ x = x.view(B, H, W, C)
888
+
889
+ # padding
890
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
891
+ if pad_input:
892
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
893
+
894
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
895
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
896
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
897
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
898
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
899
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
900
+
901
+ x = self.norm(x)
902
+ x = self.reduction(x)
903
+
904
+ return x
905
+
906
+
907
+ class BasicLayer(nn.Module):
908
+ """ A basic Swin Transformer layer for one stage.
909
+
910
+ Args:
911
+ dim (int): Number of feature channels
912
+ depth (int): Depths of this stage.
913
+ num_heads (int): Number of attention head.
914
+ window_size (int): Local window size. Default: 7.
915
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
916
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
917
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
918
+ drop (float, optional): Dropout rate. Default: 0.0
919
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
920
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
921
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
922
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
923
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
924
+ """
925
+
926
+ def __init__(self,
927
+ dim,
928
+ depth,
929
+ num_heads,
930
+ window_size=7,
931
+ mlp_ratio=4.,
932
+ qkv_bias=True,
933
+ qk_scale=None,
934
+ drop=0.,
935
+ attn_drop=0.,
936
+ drop_path=0.,
937
+ norm_layer=nn.LayerNorm,
938
+ downsample=None,
939
+ use_checkpoint=False):
940
+ super().__init__()
941
+ self.window_size = window_size
942
+ self.shift_size = window_size // 2
943
+ self.depth = depth
944
+ self.use_checkpoint = use_checkpoint
945
+
946
+ # build blocks
947
+ self.blocks = nn.ModuleList([
948
+ SwinTransformerBlock(
949
+ dim=dim,
950
+ num_heads=num_heads,
951
+ window_size=window_size,
952
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
953
+ mlp_ratio=mlp_ratio,
954
+ qkv_bias=qkv_bias,
955
+ qk_scale=qk_scale,
956
+ drop=drop,
957
+ attn_drop=attn_drop,
958
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
959
+ norm_layer=norm_layer)
960
+ for i in range(depth)])
961
+
962
+ # patch merging layer
963
+ if downsample is not None:
964
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
965
+ else:
966
+ self.downsample = None
967
+
968
+ def forward(self, x, H, W):
969
+ """ Forward function.
970
+
971
+ Args:
972
+ x: Input feature, tensor size (B, H*W, C).
973
+ H, W: Spatial resolution of the input feature.
974
+ """
975
+
976
+ # calculate attention mask for SW-MSA
977
+ Hp = int(np.ceil(H / self.window_size)) * self.window_size
978
+ Wp = int(np.ceil(W / self.window_size)) * self.window_size
979
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
980
+ h_slices = (slice(0, -self.window_size),
981
+ slice(-self.window_size, -self.shift_size),
982
+ slice(-self.shift_size, None))
983
+ w_slices = (slice(0, -self.window_size),
984
+ slice(-self.window_size, -self.shift_size),
985
+ slice(-self.shift_size, None))
986
+ cnt = 0
987
+ for h in h_slices:
988
+ for w in w_slices:
989
+ img_mask[:, h, w, :] = cnt
990
+ cnt += 1
991
+
992
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
993
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
994
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
995
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
996
+
997
+ for blk in self.blocks:
998
+ blk.H, blk.W = H, W
999
+ if self.use_checkpoint:
1000
+ x = checkpoint.checkpoint(blk, x, attn_mask)
1001
+ else:
1002
+ x = blk(x, attn_mask)
1003
+ if self.downsample is not None:
1004
+ x_down = self.downsample(x, H, W)
1005
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
1006
+ return x, H, W, x_down, Wh, Ww
1007
+ else:
1008
+ return x, H, W, x, H, W
1009
+
1010
+
1011
+ class PatchEmbed(nn.Module):
1012
+ """ Image to Patch Embedding
1013
+
1014
+ Args:
1015
+ patch_size (int): Patch token size. Default: 4.
1016
+ in_channels (int): Number of input image channels. Default: 3.
1017
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1018
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
1019
+ """
1020
+
1021
+ def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None):
1022
+ super().__init__()
1023
+ patch_size = to_2tuple(patch_size)
1024
+ self.patch_size = patch_size
1025
+
1026
+ self.in_channels = in_channels
1027
+ self.embed_dim = embed_dim
1028
+
1029
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
1030
+ if norm_layer is not None:
1031
+ self.norm = norm_layer(embed_dim)
1032
+ else:
1033
+ self.norm = None
1034
+
1035
+ def forward(self, x):
1036
+ """Forward function."""
1037
+ # padding
1038
+ _, _, H, W = x.size()
1039
+ if W % self.patch_size[1] != 0:
1040
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
1041
+ if H % self.patch_size[0] != 0:
1042
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
1043
+
1044
+ x = self.proj(x) # B C Wh Ww
1045
+ if self.norm is not None:
1046
+ Wh, Ww = x.size(2), x.size(3)
1047
+ x = x.flatten(2).transpose(1, 2)
1048
+ x = self.norm(x)
1049
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
1050
+
1051
+ return x
1052
+
1053
+
1054
+ class SwinTransformer(nn.Module):
1055
+ """ Swin Transformer backbone.
1056
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
1057
+ https://arxiv.org/pdf/2103.14030
1058
+
1059
+ Args:
1060
+ pretrain_img_size (int): Input image size for training the pretrained model,
1061
+ used in absolute postion embedding. Default 224.
1062
+ patch_size (int | tuple(int)): Patch size. Default: 4.
1063
+ in_channels (int): Number of input image channels. Default: 3.
1064
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1065
+ depths (tuple[int]): Depths of each Swin Transformer stage.
1066
+ num_heads (tuple[int]): Number of attention head of each stage.
1067
+ window_size (int): Window size. Default: 7.
1068
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
1069
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
1070
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
1071
+ drop_rate (float): Dropout rate.
1072
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
1073
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
1074
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
1075
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
1076
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
1077
+ out_indices (Sequence[int]): Output from which stages.
1078
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
1079
+ -1 means not freezing any parameters.
1080
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
1081
+ """
1082
+
1083
+ def __init__(self,
1084
+ pretrain_img_size=224,
1085
+ patch_size=4,
1086
+ in_channels=3,
1087
+ embed_dim=96,
1088
+ depths=[2, 2, 6, 2],
1089
+ num_heads=[3, 6, 12, 24],
1090
+ window_size=7,
1091
+ mlp_ratio=4.,
1092
+ qkv_bias=True,
1093
+ qk_scale=None,
1094
+ drop_rate=0.,
1095
+ attn_drop_rate=0.,
1096
+ drop_path_rate=0.2,
1097
+ norm_layer=nn.LayerNorm,
1098
+ ape=False,
1099
+ patch_norm=True,
1100
+ out_indices=(0, 1, 2, 3),
1101
+ frozen_stages=-1,
1102
+ use_checkpoint=False):
1103
+ super().__init__()
1104
+
1105
+ self.pretrain_img_size = pretrain_img_size
1106
+ self.num_layers = len(depths)
1107
+ self.embed_dim = embed_dim
1108
+ self.ape = ape
1109
+ self.patch_norm = patch_norm
1110
+ self.out_indices = out_indices
1111
+ self.frozen_stages = frozen_stages
1112
+
1113
+ # split image into non-overlapping patches
1114
+ self.patch_embed = PatchEmbed(
1115
+ patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim,
1116
+ norm_layer=norm_layer if self.patch_norm else None)
1117
+
1118
+ # absolute position embedding
1119
+ if self.ape:
1120
+ pretrain_img_size = to_2tuple(pretrain_img_size)
1121
+ patch_size = to_2tuple(patch_size)
1122
+ patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
1123
+
1124
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
1125
+ trunc_normal_(self.absolute_pos_embed, std=.02)
1126
+
1127
+ self.pos_drop = nn.Dropout(p=drop_rate)
1128
+
1129
+ # stochastic depth
1130
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
1131
+
1132
+ # build layers
1133
+ self.layers = nn.ModuleList()
1134
+ for i_layer in range(self.num_layers):
1135
+ layer = BasicLayer(
1136
+ dim=int(embed_dim * 2 ** i_layer),
1137
+ depth=depths[i_layer],
1138
+ num_heads=num_heads[i_layer],
1139
+ window_size=window_size,
1140
+ mlp_ratio=mlp_ratio,
1141
+ qkv_bias=qkv_bias,
1142
+ qk_scale=qk_scale,
1143
+ drop=drop_rate,
1144
+ attn_drop=attn_drop_rate,
1145
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
1146
+ norm_layer=norm_layer,
1147
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
1148
+ use_checkpoint=use_checkpoint)
1149
+ self.layers.append(layer)
1150
+
1151
+ num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
1152
+ self.num_features = num_features
1153
+
1154
+ # add a norm layer for each output
1155
+ for i_layer in out_indices:
1156
+ layer = norm_layer(num_features[i_layer])
1157
+ layer_name = f'norm{i_layer}'
1158
+ self.add_module(layer_name, layer)
1159
+
1160
+ self._freeze_stages()
1161
+
1162
+ def _freeze_stages(self):
1163
+ if self.frozen_stages >= 0:
1164
+ self.patch_embed.eval()
1165
+ for param in self.patch_embed.parameters():
1166
+ param.requires_grad = False
1167
+
1168
+ if self.frozen_stages >= 1 and self.ape:
1169
+ self.absolute_pos_embed.requires_grad = False
1170
+
1171
+ if self.frozen_stages >= 2:
1172
+ self.pos_drop.eval()
1173
+ for i in range(0, self.frozen_stages - 1):
1174
+ m = self.layers[i]
1175
+ m.eval()
1176
+ for param in m.parameters():
1177
+ param.requires_grad = False
1178
+
1179
+
1180
+ def forward(self, x):
1181
+ """Forward function."""
1182
+ x = self.patch_embed(x)
1183
+
1184
+ Wh, Ww = x.size(2), x.size(3)
1185
+ if self.ape:
1186
+ # interpolate the position embedding to the corresponding size
1187
+ absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
1188
+ x = (x + absolute_pos_embed) # B Wh*Ww C
1189
+
1190
+ outs = []#x.contiguous()]
1191
+ x = x.flatten(2).transpose(1, 2)
1192
+ x = self.pos_drop(x)
1193
+ for i in range(self.num_layers):
1194
+ layer = self.layers[i]
1195
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
1196
+
1197
+ if i in self.out_indices:
1198
+ norm_layer = getattr(self, f'norm{i}')
1199
+ x_out = norm_layer(x_out)
1200
+
1201
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
1202
+ outs.append(out)
1203
+
1204
+ return tuple(outs)
1205
+
1206
+ def train(self, mode=True):
1207
+ """Convert the model into training mode while keep layers freezed."""
1208
+ super(SwinTransformer, self).train(mode)
1209
+ self._freeze_stages()
1210
+
1211
+ def swin_v1_t():
1212
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7)
1213
+ return model
1214
+
1215
+ def swin_v1_s():
1216
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7)
1217
+ return model
1218
+
1219
+ def swin_v1_b():
1220
+ model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
1221
+ return model
1222
+
1223
+ def swin_v1_l():
1224
+ model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12)
1225
+ return model
1226
+
1227
+
1228
+
1229
+ ### models/modules/deform_conv.py
1230
+
1231
+ import torch
1232
+ import torch.nn as nn
1233
+ from torchvision.ops import deform_conv2d
1234
+
1235
+
1236
+ class DeformableConv2d(nn.Module):
1237
+ def __init__(self,
1238
+ in_channels,
1239
+ out_channels,
1240
+ kernel_size=3,
1241
+ stride=1,
1242
+ padding=1,
1243
+ bias=False):
1244
+
1245
+ super(DeformableConv2d, self).__init__()
1246
+
1247
+ assert type(kernel_size) == tuple or type(kernel_size) == int
1248
+
1249
+ kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size)
1250
+ self.stride = stride if type(stride) == tuple else (stride, stride)
1251
+ self.padding = padding
1252
+
1253
+ self.offset_conv = nn.Conv2d(in_channels,
1254
+ 2 * kernel_size[0] * kernel_size[1],
1255
+ kernel_size=kernel_size,
1256
+ stride=stride,
1257
+ padding=self.padding,
1258
+ bias=True)
1259
+
1260
+ nn.init.constant_(self.offset_conv.weight, 0.)
1261
+ nn.init.constant_(self.offset_conv.bias, 0.)
1262
+
1263
+ self.modulator_conv = nn.Conv2d(in_channels,
1264
+ 1 * kernel_size[0] * kernel_size[1],
1265
+ kernel_size=kernel_size,
1266
+ stride=stride,
1267
+ padding=self.padding,
1268
+ bias=True)
1269
+
1270
+ nn.init.constant_(self.modulator_conv.weight, 0.)
1271
+ nn.init.constant_(self.modulator_conv.bias, 0.)
1272
+
1273
+ self.regular_conv = nn.Conv2d(in_channels,
1274
+ out_channels=out_channels,
1275
+ kernel_size=kernel_size,
1276
+ stride=stride,
1277
+ padding=self.padding,
1278
+ bias=bias)
1279
+
1280
+ def forward(self, x):
1281
+ #h, w = x.shape[2:]
1282
+ #max_offset = max(h, w)/4.
1283
+
1284
+ offset = self.offset_conv(x)#.clamp(-max_offset, max_offset)
1285
+ modulator = 2. * torch.sigmoid(self.modulator_conv(x))
1286
+
1287
+ x = deform_conv2d(
1288
+ input=x,
1289
+ offset=offset,
1290
+ weight=self.regular_conv.weight,
1291
+ bias=self.regular_conv.bias,
1292
+ padding=self.padding,
1293
+ mask=modulator,
1294
+ stride=self.stride,
1295
+ )
1296
+ return x
1297
+
1298
+
1299
+
1300
+
1301
+ ### utils.py
1302
+
1303
+ import torch.nn as nn
1304
+
1305
+
1306
+ def build_act_layer(act_layer):
1307
+ if act_layer == 'ReLU':
1308
+ return nn.ReLU(inplace=True)
1309
+ elif act_layer == 'SiLU':
1310
+ return nn.SiLU(inplace=True)
1311
+ elif act_layer == 'GELU':
1312
+ return nn.GELU()
1313
+
1314
+ raise NotImplementedError(f'build_act_layer does not support {act_layer}')
1315
+
1316
+
1317
+ def build_norm_layer(dim,
1318
+ norm_layer,
1319
+ in_format='channels_last',
1320
+ out_format='channels_last',
1321
+ eps=1e-6):
1322
+ layers = []
1323
+ if norm_layer == 'BN':
1324
+ if in_format == 'channels_last':
1325
+ layers.append(to_channels_first())
1326
+ layers.append(nn.BatchNorm2d(dim))
1327
+ if out_format == 'channels_last':
1328
+ layers.append(to_channels_last())
1329
+ elif norm_layer == 'LN':
1330
+ if in_format == 'channels_first':
1331
+ layers.append(to_channels_last())
1332
+ layers.append(nn.LayerNorm(dim, eps=eps))
1333
+ if out_format == 'channels_first':
1334
+ layers.append(to_channels_first())
1335
+ else:
1336
+ raise NotImplementedError(
1337
+ f'build_norm_layer does not support {norm_layer}')
1338
+ return nn.Sequential(*layers)
1339
+
1340
+
1341
+ class to_channels_first(nn.Module):
1342
+
1343
+ def __init__(self):
1344
+ super().__init__()
1345
+
1346
+ def forward(self, x):
1347
+ return x.permute(0, 3, 1, 2)
1348
+
1349
+
1350
+ class to_channels_last(nn.Module):
1351
+
1352
+ def __init__(self):
1353
+ super().__init__()
1354
+
1355
+ def forward(self, x):
1356
+ return x.permute(0, 2, 3, 1)
1357
+
1358
+
1359
+
1360
+ ### dataset.py
1361
+
1362
+ _class_labels_TR_sorted = (
1363
+ 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, '
1364
+ 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, '
1365
+ 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, '
1366
+ 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, '
1367
+ 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, '
1368
+ 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, '
1369
+ 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, '
1370
+ 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, '
1371
+ 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, '
1372
+ 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, '
1373
+ 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, '
1374
+ 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, '
1375
+ 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, '
1376
+ 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht'
1377
+ )
1378
+ class_labels_TR_sorted = _class_labels_TR_sorted.split(', ')
1379
+
1380
+
1381
+ ### models/backbones/build_backbones.py
1382
+
1383
+ import torch
1384
+ import torch.nn as nn
1385
+ from collections import OrderedDict
1386
+ from torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights
1387
+ # from models.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5
1388
+ # from models.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l
1389
+ # from config import Config
1390
+
1391
+
1392
+ config = Config()
1393
+
1394
+ def build_backbone(bb_name, pretrained=True, params_settings=''):
1395
+ if bb_name == 'vgg16':
1396
+ bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0]
1397
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]}))
1398
+ elif bb_name == 'vgg16bn':
1399
+ bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0]
1400
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]}))
1401
+ elif bb_name == 'resnet50':
1402
+ bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children())
1403
+ bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]}))
1404
+ else:
1405
+ bb = eval('{}({})'.format(bb_name, params_settings))
1406
+ if pretrained:
1407
+ bb = load_weights(bb, bb_name)
1408
+ return bb
1409
+
1410
+ def load_weights(model, model_name):
1411
+ save_model = torch.load(config.weights[model_name], map_location='cpu')
1412
+ model_dict = model.state_dict()
1413
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model.items() if k in model_dict.keys()}
1414
+ # to ignore the weights with mismatched size when I modify the backbone itself.
1415
+ if not state_dict:
1416
+ save_model_keys = list(save_model.keys())
1417
+ sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None
1418
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model[sub_item].items() if k in model_dict.keys()}
1419
+ if not state_dict or not sub_item:
1420
+ print('Weights are not successully loaded. Check the state dict of weights file.')
1421
+ return None
1422
+ else:
1423
+ print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item))
1424
+ model_dict.update(state_dict)
1425
+ model.load_state_dict(model_dict)
1426
+ return model
1427
+
1428
+
1429
+
1430
+ ### models/modules/decoder_blocks.py
1431
+
1432
+ import torch
1433
+ import torch.nn as nn
1434
+ # from models.aspp import ASPP, ASPPDeformable
1435
+ # from config import Config
1436
+
1437
+
1438
+ # config = Config()
1439
+
1440
+
1441
+ class BasicDecBlk(nn.Module):
1442
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1443
+ super(BasicDecBlk, self).__init__()
1444
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1445
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1446
+ self.relu_in = nn.ReLU(inplace=True)
1447
+ if config.dec_att == 'ASPP':
1448
+ self.dec_att = ASPP(in_channels=inter_channels)
1449
+ elif config.dec_att == 'ASPPDeformable':
1450
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1451
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1452
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1453
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1454
+
1455
+ def forward(self, x):
1456
+ x = self.conv_in(x)
1457
+ x = self.bn_in(x)
1458
+ x = self.relu_in(x)
1459
+ if hasattr(self, 'dec_att'):
1460
+ x = self.dec_att(x)
1461
+ x = self.conv_out(x)
1462
+ x = self.bn_out(x)
1463
+ return x
1464
+
1465
+
1466
+ class ResBlk(nn.Module):
1467
+ def __init__(self, in_channels=64, out_channels=None, inter_channels=64):
1468
+ super(ResBlk, self).__init__()
1469
+ if out_channels is None:
1470
+ out_channels = in_channels
1471
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1472
+
1473
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1474
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1475
+ self.relu_in = nn.ReLU(inplace=True)
1476
+
1477
+ if config.dec_att == 'ASPP':
1478
+ self.dec_att = ASPP(in_channels=inter_channels)
1479
+ elif config.dec_att == 'ASPPDeformable':
1480
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1481
+
1482
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1483
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1484
+
1485
+ self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1486
+
1487
+ def forward(self, x):
1488
+ _x = self.conv_resi(x)
1489
+ x = self.conv_in(x)
1490
+ x = self.bn_in(x)
1491
+ x = self.relu_in(x)
1492
+ if hasattr(self, 'dec_att'):
1493
+ x = self.dec_att(x)
1494
+ x = self.conv_out(x)
1495
+ x = self.bn_out(x)
1496
+ return x + _x
1497
+
1498
+
1499
+
1500
+ ### models/modules/lateral_blocks.py
1501
+
1502
+ import numpy as np
1503
+ import torch
1504
+ import torch.nn as nn
1505
+ import torch.nn.functional as F
1506
+ from functools import partial
1507
+
1508
+ # from config import Config
1509
+
1510
+
1511
+ # config = Config()
1512
+
1513
+
1514
+ class BasicLatBlk(nn.Module):
1515
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1516
+ super(BasicLatBlk, self).__init__()
1517
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1518
+ self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1519
+
1520
+ def forward(self, x):
1521
+ x = self.conv(x)
1522
+ return x
1523
+
1524
+
1525
+
1526
+ ### models/modules/aspp.py
1527
+
1528
+ import torch
1529
+ import torch.nn as nn
1530
+ import torch.nn.functional as F
1531
+ # from models.deform_conv import DeformableConv2d
1532
+ # from config import Config
1533
+
1534
+
1535
+ # config = Config()
1536
+
1537
+
1538
+ class _ASPPModule(nn.Module):
1539
+ def __init__(self, in_channels, planes, kernel_size, padding, dilation):
1540
+ super(_ASPPModule, self).__init__()
1541
+ self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size,
1542
+ stride=1, padding=padding, dilation=dilation, bias=False)
1543
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1544
+ self.relu = nn.ReLU(inplace=True)
1545
+
1546
+ def forward(self, x):
1547
+ x = self.atrous_conv(x)
1548
+ x = self.bn(x)
1549
+
1550
+ return self.relu(x)
1551
+
1552
+
1553
+ class ASPP(nn.Module):
1554
+ def __init__(self, in_channels=64, out_channels=None, output_stride=16):
1555
+ super(ASPP, self).__init__()
1556
+ self.down_scale = 1
1557
+ if out_channels is None:
1558
+ out_channels = in_channels
1559
+ self.in_channelster = 256 // self.down_scale
1560
+ if output_stride == 16:
1561
+ dilations = [1, 6, 12, 18]
1562
+ elif output_stride == 8:
1563
+ dilations = [1, 12, 24, 36]
1564
+ else:
1565
+ raise NotImplementedError
1566
+
1567
+ self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0])
1568
+ self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1])
1569
+ self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2])
1570
+ self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3])
1571
+
1572
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1573
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1574
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1575
+ nn.ReLU(inplace=True))
1576
+ self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False)
1577
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1578
+ self.relu = nn.ReLU(inplace=True)
1579
+ self.dropout = nn.Dropout(0.5)
1580
+
1581
+ def forward(self, x):
1582
+ x1 = self.aspp1(x)
1583
+ x2 = self.aspp2(x)
1584
+ x3 = self.aspp3(x)
1585
+ x4 = self.aspp4(x)
1586
+ x5 = self.global_avg_pool(x)
1587
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1588
+ x = torch.cat((x1, x2, x3, x4, x5), dim=1)
1589
+
1590
+ x = self.conv1(x)
1591
+ x = self.bn1(x)
1592
+ x = self.relu(x)
1593
+
1594
+ return self.dropout(x)
1595
+
1596
+
1597
+ ##################### Deformable
1598
+ class _ASPPModuleDeformable(nn.Module):
1599
+ def __init__(self, in_channels, planes, kernel_size, padding):
1600
+ super(_ASPPModuleDeformable, self).__init__()
1601
+ self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size,
1602
+ stride=1, padding=padding, bias=False)
1603
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1604
+ self.relu = nn.ReLU(inplace=True)
1605
+
1606
+ def forward(self, x):
1607
+ x = self.atrous_conv(x)
1608
+ x = self.bn(x)
1609
+
1610
+ return self.relu(x)
1611
+
1612
+
1613
+ class ASPPDeformable(nn.Module):
1614
+ def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]):
1615
+ super(ASPPDeformable, self).__init__()
1616
+ self.down_scale = 1
1617
+ if out_channels is None:
1618
+ out_channels = in_channels
1619
+ self.in_channelster = 256 // self.down_scale
1620
+
1621
+ self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0)
1622
+ self.aspp_deforms = nn.ModuleList([
1623
+ _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes
1624
+ ])
1625
+
1626
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1627
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1628
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1629
+ nn.ReLU(inplace=True))
1630
+ self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False)
1631
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1632
+ self.relu = nn.ReLU(inplace=True)
1633
+ self.dropout = nn.Dropout(0.5)
1634
+
1635
+ def forward(self, x):
1636
+ x1 = self.aspp1(x)
1637
+ x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms]
1638
+ x5 = self.global_avg_pool(x)
1639
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1640
+ x = torch.cat((x1, *x_aspp_deforms, x5), dim=1)
1641
+
1642
+ x = self.conv1(x)
1643
+ x = self.bn1(x)
1644
+ x = self.relu(x)
1645
+
1646
+ return self.dropout(x)
1647
+
1648
+
1649
+
1650
+ ### models/refinement/refiner.py
1651
+
1652
+ import torch
1653
+ import torch.nn as nn
1654
+ from collections import OrderedDict
1655
+ import torch
1656
+ import torch.nn as nn
1657
+ import torch.nn.functional as F
1658
+ from torchvision.models import vgg16, vgg16_bn
1659
+ from torchvision.models import resnet50
1660
+
1661
+ # from config import Config
1662
+ # from dataset import class_labels_TR_sorted
1663
+ # from models.build_backbone import build_backbone
1664
+ # from models.decoder_blocks import BasicDecBlk
1665
+ # from models.lateral_blocks import BasicLatBlk
1666
+ # from models.ing import *
1667
+ # from models.stem_layer import StemLayer
1668
+
1669
+
1670
+ class RefinerPVTInChannels4(nn.Module):
1671
+ def __init__(self, in_channels=3+1):
1672
+ super(RefinerPVTInChannels4, self).__init__()
1673
+ self.config = Config()
1674
+ self.epoch = 1
1675
+ self.bb = build_backbone(self.config.bb, params_settings='in_channels=4')
1676
+
1677
+ lateral_channels_in_collection = {
1678
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1679
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1680
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1681
+ }
1682
+ channels = lateral_channels_in_collection[self.config.bb]
1683
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1684
+
1685
+ self.decoder = Decoder(channels)
1686
+
1687
+ if 0:
1688
+ for key, value in self.named_parameters():
1689
+ if 'bb.' in key:
1690
+ value.requires_grad = False
1691
+
1692
+ def forward(self, x):
1693
+ if isinstance(x, list):
1694
+ x = torch.cat(x, dim=1)
1695
+ ########## Encoder ##########
1696
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1697
+ x1 = self.bb.conv1(x)
1698
+ x2 = self.bb.conv2(x1)
1699
+ x3 = self.bb.conv3(x2)
1700
+ x4 = self.bb.conv4(x3)
1701
+ else:
1702
+ x1, x2, x3, x4 = self.bb(x)
1703
+
1704
+ x4 = self.squeeze_module(x4)
1705
+
1706
+ ########## Decoder ##########
1707
+
1708
+ features = [x, x1, x2, x3, x4]
1709
+ scaled_preds = self.decoder(features)
1710
+
1711
+ return scaled_preds
1712
+
1713
+
1714
+ class Refiner(nn.Module):
1715
+ def __init__(self, in_channels=3+1):
1716
+ super(Refiner, self).__init__()
1717
+ self.config = Config()
1718
+ self.epoch = 1
1719
+ self.stem_layer = StemLayer(in_channels=in_channels, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
1720
+ self.bb = build_backbone(self.config.bb)
1721
+
1722
+ lateral_channels_in_collection = {
1723
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1724
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1725
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1726
+ }
1727
+ channels = lateral_channels_in_collection[self.config.bb]
1728
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1729
+
1730
+ self.decoder = Decoder(channels)
1731
+
1732
+ if 0:
1733
+ for key, value in self.named_parameters():
1734
+ if 'bb.' in key:
1735
+ value.requires_grad = False
1736
+
1737
+ def forward(self, x):
1738
+ if isinstance(x, list):
1739
+ x = torch.cat(x, dim=1)
1740
+ x = self.stem_layer(x)
1741
+ ########## Encoder ##########
1742
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1743
+ x1 = self.bb.conv1(x)
1744
+ x2 = self.bb.conv2(x1)
1745
+ x3 = self.bb.conv3(x2)
1746
+ x4 = self.bb.conv4(x3)
1747
+ else:
1748
+ x1, x2, x3, x4 = self.bb(x)
1749
+
1750
+ x4 = self.squeeze_module(x4)
1751
+
1752
+ ########## Decoder ##########
1753
+
1754
+ features = [x, x1, x2, x3, x4]
1755
+ scaled_preds = self.decoder(features)
1756
+
1757
+ return scaled_preds
1758
+
1759
+
1760
+ class Decoder(nn.Module):
1761
+ def __init__(self, channels):
1762
+ super(Decoder, self).__init__()
1763
+ self.config = Config()
1764
+ DecoderBlock = eval('BasicDecBlk')
1765
+ LateralBlock = eval('BasicLatBlk')
1766
+
1767
+ self.decoder_block4 = DecoderBlock(channels[0], channels[1])
1768
+ self.decoder_block3 = DecoderBlock(channels[1], channels[2])
1769
+ self.decoder_block2 = DecoderBlock(channels[2], channels[3])
1770
+ self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2)
1771
+
1772
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
1773
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
1774
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
1775
+
1776
+ if self.config.ms_supervision:
1777
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
1778
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
1779
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
1780
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0))
1781
+
1782
+ def forward(self, features):
1783
+ x, x1, x2, x3, x4 = features
1784
+ outs = []
1785
+ p4 = self.decoder_block4(x4)
1786
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
1787
+ _p3 = _p4 + self.lateral_block4(x3)
1788
+
1789
+ p3 = self.decoder_block3(_p3)
1790
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
1791
+ _p2 = _p3 + self.lateral_block3(x2)
1792
+
1793
+ p2 = self.decoder_block2(_p2)
1794
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
1795
+ _p1 = _p2 + self.lateral_block2(x1)
1796
+
1797
+ _p1 = self.decoder_block1(_p1)
1798
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
1799
+ p1_out = self.conv_out1(_p1)
1800
+
1801
+ if self.config.ms_supervision:
1802
+ outs.append(self.conv_ms_spvn_4(p4))
1803
+ outs.append(self.conv_ms_spvn_3(p3))
1804
+ outs.append(self.conv_ms_spvn_2(p2))
1805
+ outs.append(p1_out)
1806
+ return outs
1807
+
1808
+
1809
+ class RefUNet(nn.Module):
1810
+ # Refinement
1811
+ def __init__(self, in_channels=3+1):
1812
+ super(RefUNet, self).__init__()
1813
+ self.encoder_1 = nn.Sequential(
1814
+ nn.Conv2d(in_channels, 64, 3, 1, 1),
1815
+ nn.Conv2d(64, 64, 3, 1, 1),
1816
+ nn.BatchNorm2d(64),
1817
+ nn.ReLU(inplace=True)
1818
+ )
1819
+
1820
+ self.encoder_2 = nn.Sequential(
1821
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1822
+ nn.Conv2d(64, 64, 3, 1, 1),
1823
+ nn.BatchNorm2d(64),
1824
+ nn.ReLU(inplace=True)
1825
+ )
1826
+
1827
+ self.encoder_3 = nn.Sequential(
1828
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1829
+ nn.Conv2d(64, 64, 3, 1, 1),
1830
+ nn.BatchNorm2d(64),
1831
+ nn.ReLU(inplace=True)
1832
+ )
1833
+
1834
+ self.encoder_4 = nn.Sequential(
1835
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1836
+ nn.Conv2d(64, 64, 3, 1, 1),
1837
+ nn.BatchNorm2d(64),
1838
+ nn.ReLU(inplace=True)
1839
+ )
1840
+
1841
+ self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True)
1842
+ #####
1843
+ self.decoder_5 = nn.Sequential(
1844
+ nn.Conv2d(64, 64, 3, 1, 1),
1845
+ nn.BatchNorm2d(64),
1846
+ nn.ReLU(inplace=True)
1847
+ )
1848
+ #####
1849
+ self.decoder_4 = nn.Sequential(
1850
+ nn.Conv2d(128, 64, 3, 1, 1),
1851
+ nn.BatchNorm2d(64),
1852
+ nn.ReLU(inplace=True)
1853
+ )
1854
+
1855
+ self.decoder_3 = nn.Sequential(
1856
+ nn.Conv2d(128, 64, 3, 1, 1),
1857
+ nn.BatchNorm2d(64),
1858
+ nn.ReLU(inplace=True)
1859
+ )
1860
+
1861
+ self.decoder_2 = nn.Sequential(
1862
+ nn.Conv2d(128, 64, 3, 1, 1),
1863
+ nn.BatchNorm2d(64),
1864
+ nn.ReLU(inplace=True)
1865
+ )
1866
+
1867
+ self.decoder_1 = nn.Sequential(
1868
+ nn.Conv2d(128, 64, 3, 1, 1),
1869
+ nn.BatchNorm2d(64),
1870
+ nn.ReLU(inplace=True)
1871
+ )
1872
+
1873
+ self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1)
1874
+
1875
+ self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
1876
+
1877
+ def forward(self, x):
1878
+ outs = []
1879
+ if isinstance(x, list):
1880
+ x = torch.cat(x, dim=1)
1881
+ hx = x
1882
+
1883
+ hx1 = self.encoder_1(hx)
1884
+ hx2 = self.encoder_2(hx1)
1885
+ hx3 = self.encoder_3(hx2)
1886
+ hx4 = self.encoder_4(hx3)
1887
+
1888
+ hx = self.decoder_5(self.pool4(hx4))
1889
+ hx = torch.cat((self.upscore2(hx), hx4), 1)
1890
+
1891
+ d4 = self.decoder_4(hx)
1892
+ hx = torch.cat((self.upscore2(d4), hx3), 1)
1893
+
1894
+ d3 = self.decoder_3(hx)
1895
+ hx = torch.cat((self.upscore2(d3), hx2), 1)
1896
+
1897
+ d2 = self.decoder_2(hx)
1898
+ hx = torch.cat((self.upscore2(d2), hx1), 1)
1899
+
1900
+ d1 = self.decoder_1(hx)
1901
+
1902
+ x = self.conv_d0(d1)
1903
+ outs.append(x)
1904
+ return outs
1905
+
1906
+
1907
+
1908
+ ### models/stem_layer.py
1909
+
1910
+ import torch.nn as nn
1911
+ # from utils import build_act_layer, build_norm_layer
1912
+
1913
+
1914
+ class StemLayer(nn.Module):
1915
+ r""" Stem layer of InternImage
1916
+ Args:
1917
+ in_channels (int): number of input channels
1918
+ out_channels (int): number of output channels
1919
+ act_layer (str): activation layer
1920
+ norm_layer (str): normalization layer
1921
+ """
1922
+
1923
+ def __init__(self,
1924
+ in_channels=3+1,
1925
+ inter_channels=48,
1926
+ out_channels=96,
1927
+ act_layer='GELU',
1928
+ norm_layer='BN'):
1929
+ super().__init__()
1930
+ self.conv1 = nn.Conv2d(in_channels,
1931
+ inter_channels,
1932
+ kernel_size=3,
1933
+ stride=1,
1934
+ padding=1)
1935
+ self.norm1 = build_norm_layer(
1936
+ inter_channels, norm_layer, 'channels_first', 'channels_first'
1937
+ )
1938
+ self.act = build_act_layer(act_layer)
1939
+ self.conv2 = nn.Conv2d(inter_channels,
1940
+ out_channels,
1941
+ kernel_size=3,
1942
+ stride=1,
1943
+ padding=1)
1944
+ self.norm2 = build_norm_layer(
1945
+ out_channels, norm_layer, 'channels_first', 'channels_first'
1946
+ )
1947
+
1948
+ def forward(self, x):
1949
+ x = self.conv1(x)
1950
+ x = self.norm1(x)
1951
+ x = self.act(x)
1952
+ x = self.conv2(x)
1953
+ x = self.norm2(x)
1954
+ return x
1955
+
1956
+
1957
+ ### models/birefnet.py
1958
+
1959
+ import torch
1960
+ import torch.nn as nn
1961
+ import torch.nn.functional as F
1962
+ from kornia.filters import laplacian
1963
+ from transformers import PreTrainedModel
1964
+
1965
+ # from config import Config
1966
+ # from dataset import class_labels_TR_sorted
1967
+ # from models.build_backbone import build_backbone
1968
+ # from models.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk
1969
+ # from models.lateral_blocks import BasicLatBlk
1970
+ # from models.aspp import ASPP, ASPPDeformable
1971
+ # from models.ing import *
1972
+ # from models.refiner import Refiner, RefinerPVTInChannels4, RefUNet
1973
+ # from models.stem_layer import StemLayer
1974
+ from .BiRefNet_config import BiRefNetConfig
1975
+
1976
+
1977
+ class BiRefNet(
1978
+ PreTrainedModel
1979
+ ):
1980
+ config_class = BiRefNetConfig
1981
+ def __init__(self, bb_pretrained=True, config=BiRefNetConfig()):
1982
+ super(BiRefNet, self).__init__(config)
1983
+ bb_pretrained = config.bb_pretrained
1984
+ self.config = Config()
1985
+ self.epoch = 1
1986
+ self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained)
1987
+
1988
+ channels = self.config.lateral_channels_in_collection
1989
+
1990
+ if self.config.auxiliary_classification:
1991
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
1992
+ self.cls_head = nn.Sequential(
1993
+ nn.Linear(channels[0], len(class_labels_TR_sorted))
1994
+ )
1995
+
1996
+ if self.config.squeeze_block:
1997
+ self.squeeze_module = nn.Sequential(*[
1998
+ eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0])
1999
+ for _ in range(eval(self.config.squeeze_block.split('_x')[1]))
2000
+ ])
2001
+
2002
+ self.decoder = Decoder(channels)
2003
+
2004
+ if self.config.ender:
2005
+ self.dec_end = nn.Sequential(
2006
+ nn.Conv2d(1, 16, 3, 1, 1),
2007
+ nn.Conv2d(16, 1, 3, 1, 1),
2008
+ nn.ReLU(inplace=True),
2009
+ )
2010
+
2011
+ # refine patch-level segmentation
2012
+ if self.config.refine:
2013
+ if self.config.refine == 'itself':
2014
+ self.stem_layer = StemLayer(in_channels=3+1, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
2015
+ else:
2016
+ self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1'))
2017
+
2018
+ if self.config.freeze_bb:
2019
+ # Freeze the backbone...
2020
+ print(self.named_parameters())
2021
+ for key, value in self.named_parameters():
2022
+ if 'bb.' in key and 'refiner.' not in key:
2023
+ value.requires_grad = False
2024
+
2025
+ def forward_enc(self, x):
2026
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
2027
+ x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3)
2028
+ else:
2029
+ x1, x2, x3, x4 = self.bb(x)
2030
+ if self.config.mul_scl_ipt == 'cat':
2031
+ B, C, H, W = x.shape
2032
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2033
+ x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2034
+ x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2035
+ x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2036
+ x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2037
+ elif self.config.mul_scl_ipt == 'add':
2038
+ B, C, H, W = x.shape
2039
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2040
+ x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)
2041
+ x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)
2042
+ x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)
2043
+ x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)
2044
+ class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None
2045
+ if self.config.cxt:
2046
+ x4 = torch.cat(
2047
+ (
2048
+ *[
2049
+ F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True),
2050
+ F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True),
2051
+ F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True),
2052
+ ][-len(self.config.cxt):],
2053
+ x4
2054
+ ),
2055
+ dim=1
2056
+ )
2057
+ return (x1, x2, x3, x4), class_preds
2058
+
2059
+ def forward_ori(self, x):
2060
+ ########## Encoder ##########
2061
+ (x1, x2, x3, x4), class_preds = self.forward_enc(x)
2062
+ if self.config.squeeze_block:
2063
+ x4 = self.squeeze_module(x4)
2064
+ ########## Decoder ##########
2065
+ features = [x, x1, x2, x3, x4]
2066
+ if self.training and self.config.out_ref:
2067
+ features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5))
2068
+ scaled_preds = self.decoder(features)
2069
+ return scaled_preds, class_preds
2070
+
2071
+ def forward(self, x):
2072
+ scaled_preds, class_preds = self.forward_ori(x)
2073
+ class_preds_lst = [class_preds]
2074
+ return [scaled_preds, class_preds_lst] if self.training else scaled_preds
2075
+
2076
+
2077
+ class Decoder(nn.Module):
2078
+ def __init__(self, channels):
2079
+ super(Decoder, self).__init__()
2080
+ self.config = Config()
2081
+ DecoderBlock = eval(self.config.dec_blk)
2082
+ LateralBlock = eval(self.config.lat_blk)
2083
+
2084
+ if self.config.dec_ipt:
2085
+ self.split = self.config.dec_ipt_split
2086
+ N_dec_ipt = 64
2087
+ DBlock = SimpleConvs
2088
+ ic = 64
2089
+ ipt_cha_opt = 1
2090
+ self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2091
+ self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2092
+ self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic)
2093
+ self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic)
2094
+ self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic)
2095
+ else:
2096
+ self.split = None
2097
+
2098
+ self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1])
2099
+ self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2])
2100
+ self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3])
2101
+ self.decoder_block1 = DecoderBlock(channels[3]+([N_dec_ipt, channels[2]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]//2)
2102
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2+([N_dec_ipt, channels[3]//8][ipt_cha_opt] if self.config.dec_ipt else 0), 1, 1, 1, 0))
2103
+
2104
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
2105
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
2106
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
2107
+
2108
+ if self.config.ms_supervision:
2109
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
2110
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
2111
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
2112
+
2113
+ if self.config.out_ref:
2114
+ _N = 16
2115
+ self.gdt_convs_4 = nn.Sequential(nn.Conv2d(channels[1], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2116
+ self.gdt_convs_3 = nn.Sequential(nn.Conv2d(channels[2], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2117
+ self.gdt_convs_2 = nn.Sequential(nn.Conv2d(channels[3], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2118
+
2119
+ self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2120
+ self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2121
+ self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2122
+
2123
+ self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2124
+ self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2125
+ self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2126
+
2127
+ def get_patches_batch(self, x, p):
2128
+ _size_h, _size_w = p.shape[2:]
2129
+ patches_batch = []
2130
+ for idx in range(x.shape[0]):
2131
+ columns_x = torch.split(x[idx], split_size_or_sections=_size_w, dim=-1)
2132
+ patches_x = []
2133
+ for column_x in columns_x:
2134
+ patches_x += [p.unsqueeze(0) for p in torch.split(column_x, split_size_or_sections=_size_h, dim=-2)]
2135
+ patch_sample = torch.cat(patches_x, dim=1)
2136
+ patches_batch.append(patch_sample)
2137
+ return torch.cat(patches_batch, dim=0)
2138
+
2139
+ def forward(self, features):
2140
+ if self.training and self.config.out_ref:
2141
+ outs_gdt_pred = []
2142
+ outs_gdt_label = []
2143
+ x, x1, x2, x3, x4, gdt_gt = features
2144
+ else:
2145
+ x, x1, x2, x3, x4 = features
2146
+ outs = []
2147
+
2148
+ if self.config.dec_ipt:
2149
+ patches_batch = self.get_patches_batch(x, x4) if self.split else x
2150
+ x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1)
2151
+ p4 = self.decoder_block4(x4)
2152
+ m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision else None
2153
+ if self.config.out_ref:
2154
+ p4_gdt = self.gdt_convs_4(p4)
2155
+ if self.training:
2156
+ # >> GT:
2157
+ m4_dia = m4
2158
+ gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2159
+ outs_gdt_label.append(gdt_label_main_4)
2160
+ # >> Pred:
2161
+ gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt)
2162
+ outs_gdt_pred.append(gdt_pred_4)
2163
+ gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid()
2164
+ # >> Finally:
2165
+ p4 = p4 * gdt_attn_4
2166
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
2167
+ _p3 = _p4 + self.lateral_block4(x3)
2168
+
2169
+ if self.config.dec_ipt:
2170
+ patches_batch = self.get_patches_batch(x, _p3) if self.split else x
2171
+ _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1)
2172
+ p3 = self.decoder_block3(_p3)
2173
+ m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision else None
2174
+ if self.config.out_ref:
2175
+ p3_gdt = self.gdt_convs_3(p3)
2176
+ if self.training:
2177
+ # >> GT:
2178
+ # m3 --dilation--> m3_dia
2179
+ # G_3^gt * m3_dia --> G_3^m, which is the label of gradient
2180
+ m3_dia = m3
2181
+ gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2182
+ outs_gdt_label.append(gdt_label_main_3)
2183
+ # >> Pred:
2184
+ # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx
2185
+ # F_3^G --sigmoid--> A_3^G
2186
+ gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt)
2187
+ outs_gdt_pred.append(gdt_pred_3)
2188
+ gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid()
2189
+ # >> Finally:
2190
+ # p3 = p3 * A_3^G
2191
+ p3 = p3 * gdt_attn_3
2192
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
2193
+ _p2 = _p3 + self.lateral_block3(x2)
2194
+
2195
+ if self.config.dec_ipt:
2196
+ patches_batch = self.get_patches_batch(x, _p2) if self.split else x
2197
+ _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1)
2198
+ p2 = self.decoder_block2(_p2)
2199
+ m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision else None
2200
+ if self.config.out_ref:
2201
+ p2_gdt = self.gdt_convs_2(p2)
2202
+ if self.training:
2203
+ # >> GT:
2204
+ m2_dia = m2
2205
+ gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2206
+ outs_gdt_label.append(gdt_label_main_2)
2207
+ # >> Pred:
2208
+ gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt)
2209
+ outs_gdt_pred.append(gdt_pred_2)
2210
+ gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid()
2211
+ # >> Finally:
2212
+ p2 = p2 * gdt_attn_2
2213
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
2214
+ _p1 = _p2 + self.lateral_block2(x1)
2215
+
2216
+ if self.config.dec_ipt:
2217
+ patches_batch = self.get_patches_batch(x, _p1) if self.split else x
2218
+ _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1)
2219
+ _p1 = self.decoder_block1(_p1)
2220
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
2221
+
2222
+ if self.config.dec_ipt:
2223
+ patches_batch = self.get_patches_batch(x, _p1) if self.split else x
2224
+ _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1)
2225
+ p1_out = self.conv_out1(_p1)
2226
+
2227
+ if self.config.ms_supervision:
2228
+ outs.append(m4)
2229
+ outs.append(m3)
2230
+ outs.append(m2)
2231
+ outs.append(p1_out)
2232
+ return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs)
2233
+
2234
+
2235
+ class SimpleConvs(nn.Module):
2236
+ def __init__(
2237
+ self, in_channels: int, out_channels: int, inter_channels=64
2238
+ ) -> None:
2239
+ super().__init__()
2240
+ self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1)
2241
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
2242
+
2243
+ def forward(self, x):
2244
+ return self.conv_out(self.conv1(x))
models/RMBG/RMBG-2.0/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "ZhengPeng7/BiRefNet",
3
+ "architectures": [
4
+ "BiRefNet"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "BiRefNet_config.BiRefNetConfig",
8
+ "AutoModelForImageSegmentation": "birefnet.BiRefNet"
9
+ },
10
+ "custom_pipelines": {
11
+ "image-segmentation": {
12
+ "pt": [
13
+ "AutoModelForImageSegmentation"
14
+ ],
15
+ "tf": [],
16
+ "type": "image"
17
+ }
18
+ },
19
+ "bb_pretrained": false
20
+ }
models/RMBG/RMBG-2.0/gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
models/RMBG/RMBG-2.0/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:566ed80c3d95f87ada6864d4cbe2290a1c5eb1c7bb0b123e984f60f76b02c3a7
3
+ size 884878856
models/RMBG/SAM/Moonlit Serenade.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a219a66c5d8590a19a4dc7f8bc661170fd6afeab9db8e642c474bb3571ede4a
3
+ size 4812946
models/RMBG/SAM/README.md ADDED
File without changes
models/RMBG/SAM/gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
models/RMBG/SAM/mobile_sam.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6dbb90523a35330fedd7f1d3dfc66f995213d81b29a5ca8108dbcdd4e37d6c2f
3
+ size 40728226
models/RMBG/SAM/mobile_sam.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:158f98ffe079d9a5f0c6ef6ed8a238ce2a61220754fa972d93156200d693c1bf
3
+ size 40613136
models/RMBG/SAM/sam_hq_vit_b.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14a9d662cd6f5a9c2dba6d40ab0058d88d287e4a18fd6fdc6ad5fb1a3fdeaa57
3
+ size 379335069
models/RMBG/SAM/sam_hq_vit_h.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7ac14a085326d9fa6199c8c698c4f0e7280afdbb974d2c4660ec60877b45e35
3
+ size 2570940653
models/RMBG/SAM/sam_hq_vit_l.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1a6c385d62bf005ded91a54d5ec55c985cfc4103ef89c08d90f39f04934c343
3
+ size 1254865805
models/RMBG/SAM/sam_vit_b.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec2df62732614e57411cdcf32a23ffdf28910380d03139ee0f4fcbe91eb8c912
3
+ size 375042383
models/RMBG/SAM/sam_vit_h.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7bf3b02f3ebf1267aba913ff637d9a2d5c33d3173bb679e46d9f338c26f262e
3
+ size 2564550879
models/RMBG/SAM/sam_vit_l.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3adcc4315b642a4d2101128f611684e8734c41232a17c648ed1693702a49a622
3
+ size 1249524607
models/RMBG/grounding-dino/GroundingDINO_SwinB.cfg.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ batch_size = 1
2
+ modelname = "groundingdino"
3
+ backbone = "swin_B_384_22k"
4
+ position_embedding = "sine"
5
+ pe_temperatureH = 20
6
+ pe_temperatureW = 20
7
+ return_interm_indices = [1, 2, 3]
8
+ backbone_freeze_keywords = None
9
+ enc_layers = 6
10
+ dec_layers = 6
11
+ pre_norm = False
12
+ dim_feedforward = 2048
13
+ hidden_dim = 256
14
+ dropout = 0.0
15
+ nheads = 8
16
+ num_queries = 900
17
+ query_dim = 4
18
+ num_patterns = 0
19
+ num_feature_levels = 4
20
+ enc_n_points = 4
21
+ dec_n_points = 4
22
+ two_stage_type = "standard"
23
+ two_stage_bbox_embed_share = False
24
+ two_stage_class_embed_share = False
25
+ transformer_activation = "relu"
26
+ dec_pred_bbox_embed_share = True
27
+ dn_box_noise_scale = 1.0
28
+ dn_label_noise_ratio = 0.5
29
+ dn_label_coef = 1.0
30
+ dn_bbox_coef = 1.0
31
+ embed_init_tgt = True
32
+ dn_labelbook_size = 2000
33
+ max_text_len = 256
34
+ text_encoder_type = "bert-base-uncased"
35
+ use_text_enhancer = True
36
+ use_fusion_layer = True
37
+ use_checkpoint = True
38
+ use_transformer_ckpt = True
39
+ use_text_cross_attention = True
40
+ text_dropout = 0.0
41
+ fusion_dropout = 0.0
42
+ fusion_droppath = 0.1
43
+ sub_sentence_present = True
models/RMBG/grounding-dino/GroundingDINO_SwinT_OGC.cfg.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ batch_size = 1
2
+ modelname = "groundingdino"
3
+ backbone = "swin_T_224_1k"
4
+ position_embedding = "sine"
5
+ pe_temperatureH = 20
6
+ pe_temperatureW = 20
7
+ return_interm_indices = [1, 2, 3]
8
+ backbone_freeze_keywords = None
9
+ enc_layers = 6
10
+ dec_layers = 6
11
+ pre_norm = False
12
+ dim_feedforward = 2048
13
+ hidden_dim = 256
14
+ dropout = 0.0
15
+ nheads = 8
16
+ num_queries = 900
17
+ query_dim = 4
18
+ num_patterns = 0
19
+ num_feature_levels = 4
20
+ enc_n_points = 4
21
+ dec_n_points = 4
22
+ two_stage_type = "standard"
23
+ two_stage_bbox_embed_share = False
24
+ two_stage_class_embed_share = False
25
+ transformer_activation = "relu"
26
+ dec_pred_bbox_embed_share = True
27
+ dn_box_noise_scale = 1.0
28
+ dn_label_noise_ratio = 0.5
29
+ dn_label_coef = 1.0
30
+ dn_bbox_coef = 1.0
31
+ embed_init_tgt = True
32
+ dn_labelbook_size = 2000
33
+ max_text_len = 256
34
+ text_encoder_type = "bert-base-uncased"
35
+ use_text_enhancer = True
36
+ use_fusion_layer = True
37
+ use_checkpoint = True
38
+ use_transformer_ckpt = True
39
+ use_text_cross_attention = True
40
+ text_dropout = 0.0
41
+ fusion_dropout = 0.0
42
+ fusion_droppath = 0.1
43
+ sub_sentence_present = True
models/RMBG/grounding-dino/gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
models/RMBG/grounding-dino/groundingdino_swinb_cogcoor.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46270f7a822e6906b655b729c90613e48929d0f2bb8b9b76fd10a856f3ac6ab7
3
+ size 938057991
models/RMBG/grounding-dino/groundingdino_swint_ogc.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b3ca2563c77c69f651d7bd133e97139c186df06231157a64c507099c52bc799
3
+ size 693997677