Upload folder using huggingface_hub
Browse files- .ipynb_checkpoints/__init__-checkpoint.py +1 -0
- .ipynb_checkpoints/head-checkpoint.py +241 -0
- .ipynb_checkpoints/puzzle_decoder-checkpoint.py +62 -0
- .ipynb_checkpoints/vision_transformer-checkpoint.py +283 -0
- models/__init__.py +1 -0
- models/__pycache__/__init__.cpython-311.pyc +0 -0
- models/__pycache__/head.cpython-311.pyc +0 -0
- models/__pycache__/puzzle_decoder.cpython-311.pyc +0 -0
- models/__pycache__/swin_transformer.cpython-311.pyc +0 -0
- models/__pycache__/vision_transformer.cpython-311.pyc +0 -0
- models/head.py +241 -0
- models/puzzle_decoder.py +62 -0
- models/vision_transformer.py +283 -0
.ipynb_checkpoints/__init__-checkpoint.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .vision_transformer import VisionTransformer, vit_tiny, vit_small, vit_base, vit_large
|
.ipynb_checkpoints/head-checkpoint.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
|
| 7 |
+
class CSyncBatchNorm(nn.SyncBatchNorm):
|
| 8 |
+
def __init__(self,
|
| 9 |
+
*args,
|
| 10 |
+
with_var=False,
|
| 11 |
+
**kwargs):
|
| 12 |
+
super(CSyncBatchNorm, self).__init__(*args, **kwargs)
|
| 13 |
+
self.with_var = with_var
|
| 14 |
+
|
| 15 |
+
def forward(self, x):
|
| 16 |
+
# center norm
|
| 17 |
+
self.training = False
|
| 18 |
+
if not self.with_var:
|
| 19 |
+
self.running_var = torch.ones_like(self.running_var)
|
| 20 |
+
normed_x = super(CSyncBatchNorm, self).forward(x)
|
| 21 |
+
# udpate center
|
| 22 |
+
self.training = True
|
| 23 |
+
_ = super(CSyncBatchNorm, self).forward(x)
|
| 24 |
+
return normed_x
|
| 25 |
+
|
| 26 |
+
class PSyncBatchNorm(nn.SyncBatchNorm):
|
| 27 |
+
def __init__(self,
|
| 28 |
+
*args,
|
| 29 |
+
bunch_size,
|
| 30 |
+
**kwargs):
|
| 31 |
+
procs_per_bunch = min(bunch_size, utils.get_world_size())
|
| 32 |
+
assert utils.get_world_size() % procs_per_bunch == 0
|
| 33 |
+
n_bunch = utils.get_world_size() // procs_per_bunch
|
| 34 |
+
#
|
| 35 |
+
ranks = list(range(utils.get_world_size()))
|
| 36 |
+
print('---ALL RANKS----\n{}'.format(ranks))
|
| 37 |
+
rank_groups = [ranks[i*procs_per_bunch: (i+1)*procs_per_bunch] for i in range(n_bunch)]
|
| 38 |
+
print('---RANK GROUPS----\n{}'.format(rank_groups))
|
| 39 |
+
process_groups = [torch.distributed.new_group(pids) for pids in rank_groups]
|
| 40 |
+
bunch_id = utils.get_rank() // procs_per_bunch
|
| 41 |
+
process_group = process_groups[bunch_id]
|
| 42 |
+
print('---CURRENT GROUP----\n{}'.format(process_group))
|
| 43 |
+
super(PSyncBatchNorm, self).__init__(*args, process_group=process_group, **kwargs)
|
| 44 |
+
|
| 45 |
+
class CustomSequential(nn.Sequential):
|
| 46 |
+
bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm)
|
| 47 |
+
|
| 48 |
+
def forward(self, input):
|
| 49 |
+
for module in self:
|
| 50 |
+
dim = len(input.shape)
|
| 51 |
+
if isinstance(module, self.bn_types) and dim > 2:
|
| 52 |
+
perm = list(range(dim - 1)); perm.insert(1, dim - 1)
|
| 53 |
+
inv_perm = list(range(dim)) + [1]; inv_perm.pop(1)
|
| 54 |
+
input = module(input.permute(*perm)).permute(*inv_perm)
|
| 55 |
+
else:
|
| 56 |
+
input = module(input)
|
| 57 |
+
return input
|
| 58 |
+
|
| 59 |
+
class DINOHead(nn.Module):
|
| 60 |
+
def __init__(self, in_dim, out_dim, norm=None, act='gelu', last_norm=None,
|
| 61 |
+
nlayers=3, hidden_dim=2048, bottleneck_dim=256, norm_last_layer=True, **kwargs):
|
| 62 |
+
super().__init__()
|
| 63 |
+
norm = self._build_norm(norm, hidden_dim)
|
| 64 |
+
last_norm = self._build_norm(last_norm, out_dim, affine=False, **kwargs)
|
| 65 |
+
act = self._build_act(act)
|
| 66 |
+
|
| 67 |
+
nlayers = max(nlayers, 1)
|
| 68 |
+
if nlayers == 1:
|
| 69 |
+
if bottleneck_dim > 0:
|
| 70 |
+
self.mlp = nn.Linear(in_dim, bottleneck_dim)
|
| 71 |
+
else:
|
| 72 |
+
self.mlp = nn.Linear(in_dim, out_dim)
|
| 73 |
+
else:
|
| 74 |
+
layers = [nn.Linear(in_dim, hidden_dim)]
|
| 75 |
+
if norm is not None:
|
| 76 |
+
layers.append(norm)
|
| 77 |
+
layers.append(act)
|
| 78 |
+
for _ in range(nlayers - 2):
|
| 79 |
+
layers.append(nn.Linear(hidden_dim, hidden_dim))
|
| 80 |
+
if norm is not None:
|
| 81 |
+
layers.append(norm)
|
| 82 |
+
layers.append(act)
|
| 83 |
+
if bottleneck_dim > 0:
|
| 84 |
+
layers.append(nn.Linear(hidden_dim, bottleneck_dim))
|
| 85 |
+
else:
|
| 86 |
+
layers.append(nn.Linear(hidden_dim, out_dim))
|
| 87 |
+
self.mlp = CustomSequential(*layers)
|
| 88 |
+
self.apply(self._init_weights)
|
| 89 |
+
|
| 90 |
+
if bottleneck_dim > 0:
|
| 91 |
+
self.last_layer = nn.utils.weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False))
|
| 92 |
+
self.last_layer.weight_g.data.fill_(1)
|
| 93 |
+
if norm_last_layer:
|
| 94 |
+
self.last_layer.weight_g.requires_grad = False
|
| 95 |
+
else:
|
| 96 |
+
self.last_layer = None
|
| 97 |
+
|
| 98 |
+
self.last_norm = last_norm
|
| 99 |
+
|
| 100 |
+
def _init_weights(self, m):
|
| 101 |
+
if isinstance(m, nn.Linear):
|
| 102 |
+
trunc_normal_(m.weight, std=.02)
|
| 103 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 104 |
+
nn.init.constant_(m.bias, 0)
|
| 105 |
+
|
| 106 |
+
def forward(self, x):
|
| 107 |
+
x = self.mlp(x)
|
| 108 |
+
if self.last_layer is not None:
|
| 109 |
+
x = nn.functional.normalize(x, dim=-1, p=2)
|
| 110 |
+
x = self.last_layer(x)
|
| 111 |
+
if self.last_norm is not None:
|
| 112 |
+
x = self.last_norm(x)
|
| 113 |
+
return x
|
| 114 |
+
|
| 115 |
+
def _build_norm(self, norm, hidden_dim, **kwargs):
|
| 116 |
+
if norm == 'bn':
|
| 117 |
+
norm = nn.BatchNorm1d(hidden_dim, **kwargs)
|
| 118 |
+
elif norm == 'syncbn':
|
| 119 |
+
norm = nn.SyncBatchNorm(hidden_dim, **kwargs)
|
| 120 |
+
elif norm == 'csyncbn':
|
| 121 |
+
norm = CSyncBatchNorm(hidden_dim, **kwargs)
|
| 122 |
+
elif norm == 'psyncbn':
|
| 123 |
+
norm = PSyncBatchNorm(hidden_dim, **kwargs)
|
| 124 |
+
elif norm == 'ln':
|
| 125 |
+
norm = nn.LayerNorm(hidden_dim, **kwargs)
|
| 126 |
+
else:
|
| 127 |
+
assert norm is None, "unknown norm type {}".format(norm)
|
| 128 |
+
return norm
|
| 129 |
+
|
| 130 |
+
def _build_act(self, act):
|
| 131 |
+
if act == 'relu':
|
| 132 |
+
act = nn.ReLU()
|
| 133 |
+
elif act == 'gelu':
|
| 134 |
+
act = nn.GELU()
|
| 135 |
+
else:
|
| 136 |
+
assert False, "unknown act type {}".format(act)
|
| 137 |
+
return act
|
| 138 |
+
|
| 139 |
+
class iBOTHead(DINOHead):
|
| 140 |
+
|
| 141 |
+
def __init__(self, *args, patch_out_dim=8192, norm=None, act='gelu', last_norm=None,
|
| 142 |
+
nlayers=3, hidden_dim=2048, bottleneck_dim=256, norm_last_layer=True,
|
| 143 |
+
shared_head=False, **kwargs):
|
| 144 |
+
|
| 145 |
+
super(iBOTHead, self).__init__(*args,
|
| 146 |
+
norm=norm,
|
| 147 |
+
act=act,
|
| 148 |
+
last_norm=last_norm,
|
| 149 |
+
nlayers=nlayers,
|
| 150 |
+
hidden_dim=hidden_dim,
|
| 151 |
+
bottleneck_dim=bottleneck_dim,
|
| 152 |
+
norm_last_layer=norm_last_layer,
|
| 153 |
+
**kwargs)
|
| 154 |
+
|
| 155 |
+
if not shared_head:
|
| 156 |
+
if bottleneck_dim > 0:
|
| 157 |
+
self.last_layer2 = nn.utils.weight_norm(nn.Linear(bottleneck_dim, patch_out_dim, bias=False))
|
| 158 |
+
self.last_layer2.weight_g.data.fill_(1)
|
| 159 |
+
if norm_last_layer:
|
| 160 |
+
self.last_layer2.weight_g.requires_grad = False
|
| 161 |
+
else:
|
| 162 |
+
self.mlp2 = nn.Linear(hidden_dim, patch_out_dim)
|
| 163 |
+
self.last_layer2 = None
|
| 164 |
+
|
| 165 |
+
self.last_norm2 = self._build_norm(last_norm, patch_out_dim, affine=False, **kwargs)
|
| 166 |
+
else:
|
| 167 |
+
if bottleneck_dim > 0:
|
| 168 |
+
self.last_layer2 = self.last_layer
|
| 169 |
+
else:
|
| 170 |
+
self.mlp2 = self.mlp[-1]
|
| 171 |
+
self.last_layer2 = None
|
| 172 |
+
|
| 173 |
+
self.last_norm2 = self.last_norm
|
| 174 |
+
|
| 175 |
+
def forward(self, x):
|
| 176 |
+
if len(x.shape) == 2:
|
| 177 |
+
return super(iBOTHead, self).forward(x)
|
| 178 |
+
|
| 179 |
+
if self.last_layer is not None:
|
| 180 |
+
x = self.mlp(x)
|
| 181 |
+
x = nn.functional.normalize(x, dim=-1, p=2)
|
| 182 |
+
x1 = self.last_layer(x[:, 0])
|
| 183 |
+
x2 = self.last_layer2(x[:, 1:])
|
| 184 |
+
else:
|
| 185 |
+
x = self.mlp[:-1](x)
|
| 186 |
+
x1 = self.mlp[-1](x[:, 0])
|
| 187 |
+
x2 = self.mlp2(x[:, 1:])
|
| 188 |
+
|
| 189 |
+
if self.last_norm is not None:
|
| 190 |
+
x1 = self.last_norm(x1)
|
| 191 |
+
x2 = self.last_norm2(x2)
|
| 192 |
+
|
| 193 |
+
return x1, x2
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class TemporalSideContext(nn.Module):
|
| 198 |
+
def __init__(self, D, max_len=64, n_layers=6, n_head=8, dropout=0.1):
|
| 199 |
+
super().__init__()
|
| 200 |
+
#self.pos_t = nn.Embedding(max_len, D) # learnable embedding for positions
|
| 201 |
+
layer = nn.TransformerEncoderLayer(D, n_head, 4*D,
|
| 202 |
+
dropout=dropout, batch_first=True)
|
| 203 |
+
self.enc = nn.TransformerEncoder(layer, n_layers)
|
| 204 |
+
|
| 205 |
+
def forward(self, x): # x [B,T,D]
|
| 206 |
+
B,T,D = x.shape
|
| 207 |
+
device = x.device
|
| 208 |
+
# Generate relative frame positions [0, 1, ..., T-1]
|
| 209 |
+
#pos_ids = torch.arange(T, device=device).unsqueeze(0) # [1, T]
|
| 210 |
+
#pos_embed = self.pos_t(pos_ids) # [1, T, D]
|
| 211 |
+
#x = x + pos_embed
|
| 212 |
+
return self.enc(x) # [B,T,D]
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class TemporalHead(nn.Module):
|
| 217 |
+
"""
|
| 218 |
+
Converts backbone features [B,T,D] → logits [B,T,1] for Plackett–Luce.
|
| 219 |
+
"""
|
| 220 |
+
def __init__(self, backbone_dim: int, hidden_mul: float = 0.5, max_len: int = 64):
|
| 221 |
+
super().__init__()
|
| 222 |
+
hidden_dim = int(backbone_dim * hidden_mul)
|
| 223 |
+
|
| 224 |
+
self.reduce = nn.Sequential(
|
| 225 |
+
nn.Linear(backbone_dim, hidden_dim),
|
| 226 |
+
nn.GELU()
|
| 227 |
+
)
|
| 228 |
+
self.temporal = TemporalSideContext(hidden_dim, max_len=max_len)
|
| 229 |
+
self.scorer = nn.Sequential(
|
| 230 |
+
nn.Linear(hidden_dim, hidden_dim // 2),
|
| 231 |
+
nn.GELU(),
|
| 232 |
+
nn.Linear(hidden_dim // 2, 1)
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
def forward(self, x: torch.Tensor): # x : [B,T,D]
|
| 236 |
+
x = self.reduce(x) # [B,T,hidden]
|
| 237 |
+
x = self.temporal(x) # [B,T,hidden]
|
| 238 |
+
return self.scorer(x) # [B,T,1]
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
|
.ipynb_checkpoints/puzzle_decoder-checkpoint.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
|
| 3 |
+
class AttentionBlock(nn.Module):
|
| 4 |
+
def __init__(self, attn_mul=1, embed_dim=384, num_heads=16):
|
| 5 |
+
super().__init__()
|
| 6 |
+
self.attn_mul = attn_mul
|
| 7 |
+
self.auxiliary_cross_attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
|
| 8 |
+
self.auxiliary_layer_norm1 = nn.LayerNorm(embed_dim)
|
| 9 |
+
self.auxiliary_self_attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
|
| 10 |
+
self.auxiliary_layer_norm2 = nn.LayerNorm(embed_dim)
|
| 11 |
+
self.auxiliary_linear = nn.Linear(embed_dim, embed_dim, bias=True)
|
| 12 |
+
self.auxiliary_layer_norm3 = nn.LayerNorm(embed_dim)
|
| 13 |
+
|
| 14 |
+
def forward(self, current_patch, neighbor_patch):
|
| 15 |
+
# shape of aux_crop and stu_crop: (batch_size, seq_len, embed_dim)
|
| 16 |
+
|
| 17 |
+
# MultiheadAttention takes in the query, key, value. Here we use stu_crop to attend to aux_crop.
|
| 18 |
+
cross_attn_output, cross_attn_output_weights = self.auxiliary_cross_attn(current_patch, neighbor_patch, neighbor_patch)
|
| 19 |
+
cross_attn_output = self.auxiliary_layer_norm1(self.attn_mul * cross_attn_output + current_patch) # layer norm with skip connection
|
| 20 |
+
|
| 21 |
+
# Then we use cross_attn_output to attend to cross_attn_output itself
|
| 22 |
+
self_attn_output, self_attn_output_weights = self.auxiliary_self_attn(cross_attn_output, cross_attn_output, cross_attn_output)
|
| 23 |
+
self_attn_output = self.auxiliary_layer_norm2(self_attn_output + cross_attn_output) # layer norm with skip connection
|
| 24 |
+
|
| 25 |
+
# Finally, apply feed forward.
|
| 26 |
+
output = self.auxiliary_linear(self_attn_output)
|
| 27 |
+
output = self.auxiliary_layer_norm3(output + self_attn_output) # layer norm with skip connection
|
| 28 |
+
|
| 29 |
+
return output, cross_attn_output_weights, self_attn_output_weights
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class PuzzleDecoder(nn.Module):
|
| 34 |
+
def __init__(self, attn_mul=4, num_blocks=1, embed_dim=384, num_heads=16):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.decoder = nn.ModuleList([AttentionBlock(attn_mul, embed_dim, num_heads) for _ in range(num_blocks)])
|
| 37 |
+
self.scorer = nn.Sequential(
|
| 38 |
+
nn.LayerNorm(embed_dim),
|
| 39 |
+
nn.Linear(embed_dim, embed_dim),
|
| 40 |
+
nn.GELU(),
|
| 41 |
+
nn.Linear(embed_dim, 1),
|
| 42 |
+
)
|
| 43 |
+
nn.init.trunc_normal_(self.scorer[-1].weight, std=0.02)
|
| 44 |
+
nn.init.zeros_(self.scorer[-1].bias)
|
| 45 |
+
|
| 46 |
+
def forward(self, current_patch, neighbor_patch, return_feats=False, return_attn=False):
|
| 47 |
+
x = current_patch
|
| 48 |
+
cross_ws, self_ws = [], []
|
| 49 |
+
for block in self.decoder:
|
| 50 |
+
x, cw, sw = block(x, neighbor_patch)
|
| 51 |
+
if return_attn:
|
| 52 |
+
cross_ws.append(cw); self_ws.append(sw)
|
| 53 |
+
|
| 54 |
+
scores = self.scorer(x).squeeze(-1) # [B, N]
|
| 55 |
+
if return_feats or return_attn:
|
| 56 |
+
out = {"scores": scores}
|
| 57 |
+
if return_feats: out["feats"] = x
|
| 58 |
+
if return_attn: out["cross_w"] = cross_ws; out["self_w"] = self_ws
|
| 59 |
+
return out
|
| 60 |
+
|
| 61 |
+
return scores
|
| 62 |
+
|
.ipynb_checkpoints/vision_transformer-checkpoint.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
|
| 5 |
+
from functools import partial
|
| 6 |
+
from utils import trunc_normal_
|
| 7 |
+
from timm.models.registry import register_model
|
| 8 |
+
|
| 9 |
+
def drop_path(x, drop_prob: float = 0., training: bool = False):
|
| 10 |
+
if drop_prob == 0. or not training:
|
| 11 |
+
return x
|
| 12 |
+
keep_prob = 1 - drop_prob
|
| 13 |
+
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 14 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
|
| 15 |
+
random_tensor.floor_() # binarize
|
| 16 |
+
output = x.div(keep_prob) * random_tensor
|
| 17 |
+
return output
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class DropPath(nn.Module):
|
| 21 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 22 |
+
"""
|
| 23 |
+
def __init__(self, drop_prob=None):
|
| 24 |
+
super(DropPath, self).__init__()
|
| 25 |
+
self.drop_prob = drop_prob
|
| 26 |
+
|
| 27 |
+
def forward(self, x):
|
| 28 |
+
return drop_path(x, self.drop_prob, self.training)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Mlp(nn.Module):
|
| 32 |
+
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
|
| 33 |
+
super().__init__()
|
| 34 |
+
out_features = out_features or in_features
|
| 35 |
+
hidden_features = hidden_features or in_features
|
| 36 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
| 37 |
+
self.act = act_layer()
|
| 38 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
| 39 |
+
self.drop = nn.Dropout(drop)
|
| 40 |
+
|
| 41 |
+
def forward(self, x):
|
| 42 |
+
x = self.fc1(x)
|
| 43 |
+
x = self.act(x)
|
| 44 |
+
x = self.drop(x)
|
| 45 |
+
x = self.fc2(x)
|
| 46 |
+
x = self.drop(x)
|
| 47 |
+
return x
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class Attention(nn.Module):
|
| 51 |
+
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.num_heads = num_heads
|
| 54 |
+
head_dim = dim // num_heads
|
| 55 |
+
self.scale = qk_scale or head_dim ** -0.5
|
| 56 |
+
|
| 57 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 58 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 59 |
+
self.proj = nn.Linear(dim, dim)
|
| 60 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 61 |
+
|
| 62 |
+
def forward(self, x):
|
| 63 |
+
B, N, C = x.shape
|
| 64 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 65 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
| 66 |
+
|
| 67 |
+
attn = (q @ k.transpose(-2, -1)) * self.scale
|
| 68 |
+
attn = attn.softmax(dim=-1)
|
| 69 |
+
attn = self.attn_drop(attn)
|
| 70 |
+
|
| 71 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 72 |
+
x = self.proj(x)
|
| 73 |
+
x = self.proj_drop(x)
|
| 74 |
+
return x, attn
|
| 75 |
+
|
| 76 |
+
class Block(nn.Module):
|
| 77 |
+
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0.,
|
| 78 |
+
attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, init_values=0):
|
| 79 |
+
super().__init__()
|
| 80 |
+
self.norm1 = norm_layer(dim)
|
| 81 |
+
self.attn = Attention(
|
| 82 |
+
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
|
| 83 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
| 84 |
+
self.norm2 = norm_layer(dim)
|
| 85 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
| 86 |
+
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
| 87 |
+
|
| 88 |
+
if init_values > 0:
|
| 89 |
+
self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
|
| 90 |
+
self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
|
| 91 |
+
else:
|
| 92 |
+
self.gamma_1, self.gamma_2 = None, None
|
| 93 |
+
|
| 94 |
+
def forward(self, x, return_attention=False):
|
| 95 |
+
y, attn = self.attn(self.norm1(x))
|
| 96 |
+
if return_attention:
|
| 97 |
+
return attn
|
| 98 |
+
if self.gamma_1 is None:
|
| 99 |
+
x = x + self.drop_path(y)
|
| 100 |
+
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
| 101 |
+
else:
|
| 102 |
+
x = x + self.drop_path(self.gamma_1 * y)
|
| 103 |
+
x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
|
| 104 |
+
return x
|
| 105 |
+
|
| 106 |
+
class PatchEmbed(nn.Module):
|
| 107 |
+
""" Image to Patch Embedding
|
| 108 |
+
"""
|
| 109 |
+
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
|
| 110 |
+
super().__init__()
|
| 111 |
+
num_patches = (img_size // patch_size) * (img_size // patch_size)
|
| 112 |
+
self.img_size = img_size
|
| 113 |
+
self.patch_size = patch_size
|
| 114 |
+
self.num_patches = num_patches
|
| 115 |
+
|
| 116 |
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
|
| 117 |
+
|
| 118 |
+
def forward(self, x):
|
| 119 |
+
B, C, H, W = x.shape
|
| 120 |
+
return self.proj(x)
|
| 121 |
+
|
| 122 |
+
class VisionTransformer(nn.Module):
|
| 123 |
+
""" Vision Transformer """
|
| 124 |
+
def __init__(self, img_size=[224], patch_size=16, in_chans=3, num_classes=0, embed_dim=768, depth=12,
|
| 125 |
+
num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
|
| 126 |
+
drop_path_rate=0., norm_layer=partial(nn.LayerNorm, eps=1e-6), return_all_tokens=False,
|
| 127 |
+
init_values=0, use_mean_pooling=False, masked_im_modeling=False):
|
| 128 |
+
super().__init__()
|
| 129 |
+
self.num_features = self.embed_dim = embed_dim
|
| 130 |
+
self.return_all_tokens = return_all_tokens
|
| 131 |
+
|
| 132 |
+
self.patch_embed = PatchEmbed(
|
| 133 |
+
img_size=img_size[0], patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
|
| 134 |
+
num_patches = self.patch_embed.num_patches
|
| 135 |
+
|
| 136 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
| 137 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
|
| 138 |
+
self.pos_drop = nn.Dropout(p=drop_rate)
|
| 139 |
+
|
| 140 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
|
| 141 |
+
self.blocks = nn.ModuleList([
|
| 142 |
+
Block(
|
| 143 |
+
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
|
| 144 |
+
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
|
| 145 |
+
init_values=init_values)
|
| 146 |
+
for i in range(depth)])
|
| 147 |
+
|
| 148 |
+
self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim)
|
| 149 |
+
self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None
|
| 150 |
+
# Classifier head
|
| 151 |
+
self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
|
| 152 |
+
|
| 153 |
+
trunc_normal_(self.pos_embed, std=.02)
|
| 154 |
+
trunc_normal_(self.cls_token, std=.02)
|
| 155 |
+
self.apply(self._init_weights)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
# masked image modeling
|
| 159 |
+
self.masked_im_modeling = masked_im_modeling
|
| 160 |
+
if masked_im_modeling:
|
| 161 |
+
self.masked_embed = nn.Parameter(torch.zeros(1, embed_dim))
|
| 162 |
+
|
| 163 |
+
def _init_weights(self, m):
|
| 164 |
+
if isinstance(m, nn.Linear):
|
| 165 |
+
trunc_normal_(m.weight, std=.02)
|
| 166 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 167 |
+
nn.init.constant_(m.bias, 0)
|
| 168 |
+
elif isinstance(m, nn.LayerNorm):
|
| 169 |
+
nn.init.constant_(m.bias, 0)
|
| 170 |
+
nn.init.constant_(m.weight, 1.0)
|
| 171 |
+
|
| 172 |
+
def interpolate_pos_encoding(self, x, w, h):
|
| 173 |
+
npatch = x.shape[1] - 1
|
| 174 |
+
N = self.pos_embed.shape[1] - 1
|
| 175 |
+
if npatch == N and w == h:
|
| 176 |
+
return self.pos_embed
|
| 177 |
+
class_pos_embed = self.pos_embed[:, 0]
|
| 178 |
+
patch_pos_embed = self.pos_embed[:, 1:]
|
| 179 |
+
dim = x.shape[-1]
|
| 180 |
+
w0 = w // self.patch_embed.patch_size
|
| 181 |
+
h0 = h // self.patch_embed.patch_size
|
| 182 |
+
# we add a small number to avoid floating point error in the interpolation
|
| 183 |
+
# see discussion at https://github.com/facebookresearch/dino/issues/8
|
| 184 |
+
w0, h0 = w0 + 0.1, h0 + 0.1
|
| 185 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 186 |
+
patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),
|
| 187 |
+
scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)),
|
| 188 |
+
mode='bicubic',
|
| 189 |
+
)
|
| 190 |
+
assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1]
|
| 191 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 192 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 193 |
+
|
| 194 |
+
def prepare_tokens(self, x, no_pe = False, mask=None):
|
| 195 |
+
B, nc, w, h = x.shape
|
| 196 |
+
# patch linear embedding
|
| 197 |
+
x = self.patch_embed(x)
|
| 198 |
+
|
| 199 |
+
# mask image modeling
|
| 200 |
+
if mask is not None:
|
| 201 |
+
x = self.mask_model(x, mask)
|
| 202 |
+
x = x.flatten(2).transpose(1, 2)
|
| 203 |
+
|
| 204 |
+
# add the [CLS] token to the embed patch tokens
|
| 205 |
+
cls_tokens = self.cls_token.expand(B, -1, -1)
|
| 206 |
+
x = torch.cat((cls_tokens, x), dim=1)
|
| 207 |
+
|
| 208 |
+
# add positional encoding to each token
|
| 209 |
+
if not no_pe:
|
| 210 |
+
x = x + self.interpolate_pos_encoding(x, w, h)
|
| 211 |
+
|
| 212 |
+
return self.pos_drop(x)
|
| 213 |
+
|
| 214 |
+
def forward(self, x, return_all_tokens=None, mask=None, no_pe=False):
|
| 215 |
+
# mim
|
| 216 |
+
if self.masked_im_modeling:
|
| 217 |
+
assert mask is not None
|
| 218 |
+
x = self.prepare_tokens(x, no_pe=no_pe, mask=mask)
|
| 219 |
+
else:
|
| 220 |
+
x = self.prepare_tokens(x, no_pe=no_pe)
|
| 221 |
+
|
| 222 |
+
for blk in self.blocks:
|
| 223 |
+
x = blk(x)
|
| 224 |
+
|
| 225 |
+
x = self.norm(x)
|
| 226 |
+
if self.fc_norm is not None:
|
| 227 |
+
x[:, 0] = self.fc_norm(x[:, 1:, :].mean(1))
|
| 228 |
+
|
| 229 |
+
return_all_tokens = self.return_all_tokens if \
|
| 230 |
+
return_all_tokens is None else return_all_tokens
|
| 231 |
+
if return_all_tokens:
|
| 232 |
+
return x
|
| 233 |
+
return x[:, 0]
|
| 234 |
+
|
| 235 |
+
def get_last_selfattention(self, x):
|
| 236 |
+
x = self.prepare_tokens(x)
|
| 237 |
+
for i, blk in enumerate(self.blocks):
|
| 238 |
+
if i < len(self.blocks) - 1:
|
| 239 |
+
x = blk(x)
|
| 240 |
+
else:
|
| 241 |
+
# return attention of the last block
|
| 242 |
+
return blk(x, return_attention=True)
|
| 243 |
+
|
| 244 |
+
def get_intermediate_layers(self, x, n=1):
|
| 245 |
+
x = self.prepare_tokens(x)
|
| 246 |
+
# we return the output tokens from the `n` last blocks
|
| 247 |
+
output = []
|
| 248 |
+
for i, blk in enumerate(self.blocks):
|
| 249 |
+
x = blk(x)
|
| 250 |
+
if len(self.blocks) - i <= n:
|
| 251 |
+
output.append(self.norm(x))
|
| 252 |
+
return output
|
| 253 |
+
|
| 254 |
+
def get_num_layers(self):
|
| 255 |
+
return len(self.blocks)
|
| 256 |
+
|
| 257 |
+
def mask_model(self, x, mask):
|
| 258 |
+
x.permute(0, 2, 3, 1)[mask, :] = self.masked_embed.to(x.dtype)
|
| 259 |
+
return x
|
| 260 |
+
|
| 261 |
+
def vit_tiny(patch_size=16, **kwargs):
|
| 262 |
+
model = VisionTransformer(
|
| 263 |
+
patch_size=patch_size, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4,
|
| 264 |
+
qkv_bias=True, **kwargs)
|
| 265 |
+
return model
|
| 266 |
+
|
| 267 |
+
def vit_small(patch_size=16, **kwargs):
|
| 268 |
+
model = VisionTransformer(
|
| 269 |
+
patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4,
|
| 270 |
+
qkv_bias=True, **kwargs)
|
| 271 |
+
return model
|
| 272 |
+
|
| 273 |
+
def vit_base(patch_size=16, **kwargs):
|
| 274 |
+
model = VisionTransformer(
|
| 275 |
+
patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4,
|
| 276 |
+
qkv_bias=True, **kwargs)
|
| 277 |
+
return model
|
| 278 |
+
|
| 279 |
+
def vit_large(patch_size=16, **kwargs):
|
| 280 |
+
model = VisionTransformer(
|
| 281 |
+
patch_size=patch_size, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4,
|
| 282 |
+
qkv_bias=True, **kwargs)
|
| 283 |
+
return model
|
models/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .vision_transformer import VisionTransformer, vit_tiny, vit_small, vit_base, vit_large
|
models/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (492 Bytes). View file
|
|
|
models/__pycache__/head.cpython-311.pyc
ADDED
|
Binary file (17.3 kB). View file
|
|
|
models/__pycache__/puzzle_decoder.cpython-311.pyc
ADDED
|
Binary file (4.73 kB). View file
|
|
|
models/__pycache__/swin_transformer.cpython-311.pyc
ADDED
|
Binary file (49.7 kB). View file
|
|
|
models/__pycache__/vision_transformer.cpython-311.pyc
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import utils
|
| 4 |
+
|
| 5 |
+
from utils import trunc_normal_
|
| 6 |
+
|
| 7 |
+
class CSyncBatchNorm(nn.SyncBatchNorm):
|
| 8 |
+
def __init__(self,
|
| 9 |
+
*args,
|
| 10 |
+
with_var=False,
|
| 11 |
+
**kwargs):
|
| 12 |
+
super(CSyncBatchNorm, self).__init__(*args, **kwargs)
|
| 13 |
+
self.with_var = with_var
|
| 14 |
+
|
| 15 |
+
def forward(self, x):
|
| 16 |
+
# center norm
|
| 17 |
+
self.training = False
|
| 18 |
+
if not self.with_var:
|
| 19 |
+
self.running_var = torch.ones_like(self.running_var)
|
| 20 |
+
normed_x = super(CSyncBatchNorm, self).forward(x)
|
| 21 |
+
# udpate center
|
| 22 |
+
self.training = True
|
| 23 |
+
_ = super(CSyncBatchNorm, self).forward(x)
|
| 24 |
+
return normed_x
|
| 25 |
+
|
| 26 |
+
class PSyncBatchNorm(nn.SyncBatchNorm):
|
| 27 |
+
def __init__(self,
|
| 28 |
+
*args,
|
| 29 |
+
bunch_size,
|
| 30 |
+
**kwargs):
|
| 31 |
+
procs_per_bunch = min(bunch_size, utils.get_world_size())
|
| 32 |
+
assert utils.get_world_size() % procs_per_bunch == 0
|
| 33 |
+
n_bunch = utils.get_world_size() // procs_per_bunch
|
| 34 |
+
#
|
| 35 |
+
ranks = list(range(utils.get_world_size()))
|
| 36 |
+
print('---ALL RANKS----\n{}'.format(ranks))
|
| 37 |
+
rank_groups = [ranks[i*procs_per_bunch: (i+1)*procs_per_bunch] for i in range(n_bunch)]
|
| 38 |
+
print('---RANK GROUPS----\n{}'.format(rank_groups))
|
| 39 |
+
process_groups = [torch.distributed.new_group(pids) for pids in rank_groups]
|
| 40 |
+
bunch_id = utils.get_rank() // procs_per_bunch
|
| 41 |
+
process_group = process_groups[bunch_id]
|
| 42 |
+
print('---CURRENT GROUP----\n{}'.format(process_group))
|
| 43 |
+
super(PSyncBatchNorm, self).__init__(*args, process_group=process_group, **kwargs)
|
| 44 |
+
|
| 45 |
+
class CustomSequential(nn.Sequential):
|
| 46 |
+
bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm)
|
| 47 |
+
|
| 48 |
+
def forward(self, input):
|
| 49 |
+
for module in self:
|
| 50 |
+
dim = len(input.shape)
|
| 51 |
+
if isinstance(module, self.bn_types) and dim > 2:
|
| 52 |
+
perm = list(range(dim - 1)); perm.insert(1, dim - 1)
|
| 53 |
+
inv_perm = list(range(dim)) + [1]; inv_perm.pop(1)
|
| 54 |
+
input = module(input.permute(*perm)).permute(*inv_perm)
|
| 55 |
+
else:
|
| 56 |
+
input = module(input)
|
| 57 |
+
return input
|
| 58 |
+
|
| 59 |
+
class DINOHead(nn.Module):
|
| 60 |
+
def __init__(self, in_dim, out_dim, norm=None, act='gelu', last_norm=None,
|
| 61 |
+
nlayers=3, hidden_dim=2048, bottleneck_dim=256, norm_last_layer=True, **kwargs):
|
| 62 |
+
super().__init__()
|
| 63 |
+
norm = self._build_norm(norm, hidden_dim)
|
| 64 |
+
last_norm = self._build_norm(last_norm, out_dim, affine=False, **kwargs)
|
| 65 |
+
act = self._build_act(act)
|
| 66 |
+
|
| 67 |
+
nlayers = max(nlayers, 1)
|
| 68 |
+
if nlayers == 1:
|
| 69 |
+
if bottleneck_dim > 0:
|
| 70 |
+
self.mlp = nn.Linear(in_dim, bottleneck_dim)
|
| 71 |
+
else:
|
| 72 |
+
self.mlp = nn.Linear(in_dim, out_dim)
|
| 73 |
+
else:
|
| 74 |
+
layers = [nn.Linear(in_dim, hidden_dim)]
|
| 75 |
+
if norm is not None:
|
| 76 |
+
layers.append(norm)
|
| 77 |
+
layers.append(act)
|
| 78 |
+
for _ in range(nlayers - 2):
|
| 79 |
+
layers.append(nn.Linear(hidden_dim, hidden_dim))
|
| 80 |
+
if norm is not None:
|
| 81 |
+
layers.append(norm)
|
| 82 |
+
layers.append(act)
|
| 83 |
+
if bottleneck_dim > 0:
|
| 84 |
+
layers.append(nn.Linear(hidden_dim, bottleneck_dim))
|
| 85 |
+
else:
|
| 86 |
+
layers.append(nn.Linear(hidden_dim, out_dim))
|
| 87 |
+
self.mlp = CustomSequential(*layers)
|
| 88 |
+
self.apply(self._init_weights)
|
| 89 |
+
|
| 90 |
+
if bottleneck_dim > 0:
|
| 91 |
+
self.last_layer = nn.utils.weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False))
|
| 92 |
+
self.last_layer.weight_g.data.fill_(1)
|
| 93 |
+
if norm_last_layer:
|
| 94 |
+
self.last_layer.weight_g.requires_grad = False
|
| 95 |
+
else:
|
| 96 |
+
self.last_layer = None
|
| 97 |
+
|
| 98 |
+
self.last_norm = last_norm
|
| 99 |
+
|
| 100 |
+
def _init_weights(self, m):
|
| 101 |
+
if isinstance(m, nn.Linear):
|
| 102 |
+
trunc_normal_(m.weight, std=.02)
|
| 103 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 104 |
+
nn.init.constant_(m.bias, 0)
|
| 105 |
+
|
| 106 |
+
def forward(self, x):
|
| 107 |
+
x = self.mlp(x)
|
| 108 |
+
if self.last_layer is not None:
|
| 109 |
+
x = nn.functional.normalize(x, dim=-1, p=2)
|
| 110 |
+
x = self.last_layer(x)
|
| 111 |
+
if self.last_norm is not None:
|
| 112 |
+
x = self.last_norm(x)
|
| 113 |
+
return x
|
| 114 |
+
|
| 115 |
+
def _build_norm(self, norm, hidden_dim, **kwargs):
|
| 116 |
+
if norm == 'bn':
|
| 117 |
+
norm = nn.BatchNorm1d(hidden_dim, **kwargs)
|
| 118 |
+
elif norm == 'syncbn':
|
| 119 |
+
norm = nn.SyncBatchNorm(hidden_dim, **kwargs)
|
| 120 |
+
elif norm == 'csyncbn':
|
| 121 |
+
norm = CSyncBatchNorm(hidden_dim, **kwargs)
|
| 122 |
+
elif norm == 'psyncbn':
|
| 123 |
+
norm = PSyncBatchNorm(hidden_dim, **kwargs)
|
| 124 |
+
elif norm == 'ln':
|
| 125 |
+
norm = nn.LayerNorm(hidden_dim, **kwargs)
|
| 126 |
+
else:
|
| 127 |
+
assert norm is None, "unknown norm type {}".format(norm)
|
| 128 |
+
return norm
|
| 129 |
+
|
| 130 |
+
def _build_act(self, act):
|
| 131 |
+
if act == 'relu':
|
| 132 |
+
act = nn.ReLU()
|
| 133 |
+
elif act == 'gelu':
|
| 134 |
+
act = nn.GELU()
|
| 135 |
+
else:
|
| 136 |
+
assert False, "unknown act type {}".format(act)
|
| 137 |
+
return act
|
| 138 |
+
|
| 139 |
+
class iBOTHead(DINOHead):
|
| 140 |
+
|
| 141 |
+
def __init__(self, *args, patch_out_dim=8192, norm=None, act='gelu', last_norm=None,
|
| 142 |
+
nlayers=3, hidden_dim=2048, bottleneck_dim=256, norm_last_layer=True,
|
| 143 |
+
shared_head=False, **kwargs):
|
| 144 |
+
|
| 145 |
+
super(iBOTHead, self).__init__(*args,
|
| 146 |
+
norm=norm,
|
| 147 |
+
act=act,
|
| 148 |
+
last_norm=last_norm,
|
| 149 |
+
nlayers=nlayers,
|
| 150 |
+
hidden_dim=hidden_dim,
|
| 151 |
+
bottleneck_dim=bottleneck_dim,
|
| 152 |
+
norm_last_layer=norm_last_layer,
|
| 153 |
+
**kwargs)
|
| 154 |
+
|
| 155 |
+
if not shared_head:
|
| 156 |
+
if bottleneck_dim > 0:
|
| 157 |
+
self.last_layer2 = nn.utils.weight_norm(nn.Linear(bottleneck_dim, patch_out_dim, bias=False))
|
| 158 |
+
self.last_layer2.weight_g.data.fill_(1)
|
| 159 |
+
if norm_last_layer:
|
| 160 |
+
self.last_layer2.weight_g.requires_grad = False
|
| 161 |
+
else:
|
| 162 |
+
self.mlp2 = nn.Linear(hidden_dim, patch_out_dim)
|
| 163 |
+
self.last_layer2 = None
|
| 164 |
+
|
| 165 |
+
self.last_norm2 = self._build_norm(last_norm, patch_out_dim, affine=False, **kwargs)
|
| 166 |
+
else:
|
| 167 |
+
if bottleneck_dim > 0:
|
| 168 |
+
self.last_layer2 = self.last_layer
|
| 169 |
+
else:
|
| 170 |
+
self.mlp2 = self.mlp[-1]
|
| 171 |
+
self.last_layer2 = None
|
| 172 |
+
|
| 173 |
+
self.last_norm2 = self.last_norm
|
| 174 |
+
|
| 175 |
+
def forward(self, x):
|
| 176 |
+
if len(x.shape) == 2:
|
| 177 |
+
return super(iBOTHead, self).forward(x)
|
| 178 |
+
|
| 179 |
+
if self.last_layer is not None:
|
| 180 |
+
x = self.mlp(x)
|
| 181 |
+
x = nn.functional.normalize(x, dim=-1, p=2)
|
| 182 |
+
x1 = self.last_layer(x[:, 0])
|
| 183 |
+
x2 = self.last_layer2(x[:, 1:])
|
| 184 |
+
else:
|
| 185 |
+
x = self.mlp[:-1](x)
|
| 186 |
+
x1 = self.mlp[-1](x[:, 0])
|
| 187 |
+
x2 = self.mlp2(x[:, 1:])
|
| 188 |
+
|
| 189 |
+
if self.last_norm is not None:
|
| 190 |
+
x1 = self.last_norm(x1)
|
| 191 |
+
x2 = self.last_norm2(x2)
|
| 192 |
+
|
| 193 |
+
return x1, x2
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class TemporalSideContext(nn.Module):
|
| 198 |
+
def __init__(self, D, max_len=64, n_layers=6, n_head=8, dropout=0.1):
|
| 199 |
+
super().__init__()
|
| 200 |
+
#self.pos_t = nn.Embedding(max_len, D) # learnable embedding for positions
|
| 201 |
+
layer = nn.TransformerEncoderLayer(D, n_head, 4*D,
|
| 202 |
+
dropout=dropout, batch_first=True)
|
| 203 |
+
self.enc = nn.TransformerEncoder(layer, n_layers)
|
| 204 |
+
|
| 205 |
+
def forward(self, x): # x [B,T,D]
|
| 206 |
+
B,T,D = x.shape
|
| 207 |
+
device = x.device
|
| 208 |
+
# Generate relative frame positions [0, 1, ..., T-1]
|
| 209 |
+
#pos_ids = torch.arange(T, device=device).unsqueeze(0) # [1, T]
|
| 210 |
+
#pos_embed = self.pos_t(pos_ids) # [1, T, D]
|
| 211 |
+
#x = x + pos_embed
|
| 212 |
+
return self.enc(x) # [B,T,D]
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class TemporalHead(nn.Module):
|
| 217 |
+
"""
|
| 218 |
+
Converts backbone features [B,T,D] → logits [B,T,1] for Plackett–Luce.
|
| 219 |
+
"""
|
| 220 |
+
def __init__(self, backbone_dim: int, hidden_mul: float = 0.5, max_len: int = 64):
|
| 221 |
+
super().__init__()
|
| 222 |
+
hidden_dim = int(backbone_dim * hidden_mul)
|
| 223 |
+
|
| 224 |
+
self.reduce = nn.Sequential(
|
| 225 |
+
nn.Linear(backbone_dim, hidden_dim),
|
| 226 |
+
nn.GELU()
|
| 227 |
+
)
|
| 228 |
+
self.temporal = TemporalSideContext(hidden_dim, max_len=max_len)
|
| 229 |
+
self.scorer = nn.Sequential(
|
| 230 |
+
nn.Linear(hidden_dim, hidden_dim // 2),
|
| 231 |
+
nn.GELU(),
|
| 232 |
+
nn.Linear(hidden_dim // 2, 1)
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
def forward(self, x: torch.Tensor): # x : [B,T,D]
|
| 236 |
+
x = self.reduce(x) # [B,T,hidden]
|
| 237 |
+
x = self.temporal(x) # [B,T,hidden]
|
| 238 |
+
return self.scorer(x) # [B,T,1]
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
|
models/puzzle_decoder.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
|
| 3 |
+
class AttentionBlock(nn.Module):
|
| 4 |
+
def __init__(self, attn_mul=1, embed_dim=384, num_heads=16):
|
| 5 |
+
super().__init__()
|
| 6 |
+
self.attn_mul = attn_mul
|
| 7 |
+
self.auxiliary_cross_attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
|
| 8 |
+
self.auxiliary_layer_norm1 = nn.LayerNorm(embed_dim)
|
| 9 |
+
self.auxiliary_self_attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
|
| 10 |
+
self.auxiliary_layer_norm2 = nn.LayerNorm(embed_dim)
|
| 11 |
+
self.auxiliary_linear = nn.Linear(embed_dim, embed_dim, bias=True)
|
| 12 |
+
self.auxiliary_layer_norm3 = nn.LayerNorm(embed_dim)
|
| 13 |
+
|
| 14 |
+
def forward(self, current_patch, neighbor_patch):
|
| 15 |
+
# shape of aux_crop and stu_crop: (batch_size, seq_len, embed_dim)
|
| 16 |
+
|
| 17 |
+
# MultiheadAttention takes in the query, key, value. Here we use stu_crop to attend to aux_crop.
|
| 18 |
+
cross_attn_output, cross_attn_output_weights = self.auxiliary_cross_attn(current_patch, neighbor_patch, neighbor_patch)
|
| 19 |
+
cross_attn_output = self.auxiliary_layer_norm1(self.attn_mul * cross_attn_output + current_patch) # layer norm with skip connection
|
| 20 |
+
|
| 21 |
+
# Then we use cross_attn_output to attend to cross_attn_output itself
|
| 22 |
+
self_attn_output, self_attn_output_weights = self.auxiliary_self_attn(cross_attn_output, cross_attn_output, cross_attn_output)
|
| 23 |
+
self_attn_output = self.auxiliary_layer_norm2(self_attn_output + cross_attn_output) # layer norm with skip connection
|
| 24 |
+
|
| 25 |
+
# Finally, apply feed forward.
|
| 26 |
+
output = self.auxiliary_linear(self_attn_output)
|
| 27 |
+
output = self.auxiliary_layer_norm3(output + self_attn_output) # layer norm with skip connection
|
| 28 |
+
|
| 29 |
+
return output, cross_attn_output_weights, self_attn_output_weights
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class PuzzleDecoder(nn.Module):
|
| 34 |
+
def __init__(self, attn_mul=4, num_blocks=1, embed_dim=384, num_heads=16):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.decoder = nn.ModuleList([AttentionBlock(attn_mul, embed_dim, num_heads) for _ in range(num_blocks)])
|
| 37 |
+
self.scorer = nn.Sequential(
|
| 38 |
+
nn.LayerNorm(embed_dim),
|
| 39 |
+
nn.Linear(embed_dim, embed_dim),
|
| 40 |
+
nn.GELU(),
|
| 41 |
+
nn.Linear(embed_dim, 1),
|
| 42 |
+
)
|
| 43 |
+
nn.init.trunc_normal_(self.scorer[-1].weight, std=0.02)
|
| 44 |
+
nn.init.zeros_(self.scorer[-1].bias)
|
| 45 |
+
|
| 46 |
+
def forward(self, current_patch, neighbor_patch, return_feats=False, return_attn=False):
|
| 47 |
+
x = current_patch
|
| 48 |
+
cross_ws, self_ws = [], []
|
| 49 |
+
for block in self.decoder:
|
| 50 |
+
x, cw, sw = block(x, neighbor_patch)
|
| 51 |
+
if return_attn:
|
| 52 |
+
cross_ws.append(cw); self_ws.append(sw)
|
| 53 |
+
|
| 54 |
+
scores = self.scorer(x).squeeze(-1) # [B, N]
|
| 55 |
+
if return_feats or return_attn:
|
| 56 |
+
out = {"scores": scores}
|
| 57 |
+
if return_feats: out["feats"] = x
|
| 58 |
+
if return_attn: out["cross_w"] = cross_ws; out["self_w"] = self_ws
|
| 59 |
+
return out
|
| 60 |
+
|
| 61 |
+
return scores
|
| 62 |
+
|
models/vision_transformer.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
|
| 5 |
+
from functools import partial
|
| 6 |
+
from utils import trunc_normal_
|
| 7 |
+
from timm.models.registry import register_model
|
| 8 |
+
|
| 9 |
+
def drop_path(x, drop_prob: float = 0., training: bool = False):
|
| 10 |
+
if drop_prob == 0. or not training:
|
| 11 |
+
return x
|
| 12 |
+
keep_prob = 1 - drop_prob
|
| 13 |
+
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 14 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
|
| 15 |
+
random_tensor.floor_() # binarize
|
| 16 |
+
output = x.div(keep_prob) * random_tensor
|
| 17 |
+
return output
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class DropPath(nn.Module):
|
| 21 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 22 |
+
"""
|
| 23 |
+
def __init__(self, drop_prob=None):
|
| 24 |
+
super(DropPath, self).__init__()
|
| 25 |
+
self.drop_prob = drop_prob
|
| 26 |
+
|
| 27 |
+
def forward(self, x):
|
| 28 |
+
return drop_path(x, self.drop_prob, self.training)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Mlp(nn.Module):
|
| 32 |
+
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
|
| 33 |
+
super().__init__()
|
| 34 |
+
out_features = out_features or in_features
|
| 35 |
+
hidden_features = hidden_features or in_features
|
| 36 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
| 37 |
+
self.act = act_layer()
|
| 38 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
| 39 |
+
self.drop = nn.Dropout(drop)
|
| 40 |
+
|
| 41 |
+
def forward(self, x):
|
| 42 |
+
x = self.fc1(x)
|
| 43 |
+
x = self.act(x)
|
| 44 |
+
x = self.drop(x)
|
| 45 |
+
x = self.fc2(x)
|
| 46 |
+
x = self.drop(x)
|
| 47 |
+
return x
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class Attention(nn.Module):
|
| 51 |
+
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.num_heads = num_heads
|
| 54 |
+
head_dim = dim // num_heads
|
| 55 |
+
self.scale = qk_scale or head_dim ** -0.5
|
| 56 |
+
|
| 57 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 58 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 59 |
+
self.proj = nn.Linear(dim, dim)
|
| 60 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 61 |
+
|
| 62 |
+
def forward(self, x):
|
| 63 |
+
B, N, C = x.shape
|
| 64 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 65 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
| 66 |
+
|
| 67 |
+
attn = (q @ k.transpose(-2, -1)) * self.scale
|
| 68 |
+
attn = attn.softmax(dim=-1)
|
| 69 |
+
attn = self.attn_drop(attn)
|
| 70 |
+
|
| 71 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 72 |
+
x = self.proj(x)
|
| 73 |
+
x = self.proj_drop(x)
|
| 74 |
+
return x, attn
|
| 75 |
+
|
| 76 |
+
class Block(nn.Module):
|
| 77 |
+
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0.,
|
| 78 |
+
attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, init_values=0):
|
| 79 |
+
super().__init__()
|
| 80 |
+
self.norm1 = norm_layer(dim)
|
| 81 |
+
self.attn = Attention(
|
| 82 |
+
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
|
| 83 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
| 84 |
+
self.norm2 = norm_layer(dim)
|
| 85 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
| 86 |
+
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
| 87 |
+
|
| 88 |
+
if init_values > 0:
|
| 89 |
+
self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
|
| 90 |
+
self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
|
| 91 |
+
else:
|
| 92 |
+
self.gamma_1, self.gamma_2 = None, None
|
| 93 |
+
|
| 94 |
+
def forward(self, x, return_attention=False):
|
| 95 |
+
y, attn = self.attn(self.norm1(x))
|
| 96 |
+
if return_attention:
|
| 97 |
+
return attn
|
| 98 |
+
if self.gamma_1 is None:
|
| 99 |
+
x = x + self.drop_path(y)
|
| 100 |
+
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
| 101 |
+
else:
|
| 102 |
+
x = x + self.drop_path(self.gamma_1 * y)
|
| 103 |
+
x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
|
| 104 |
+
return x
|
| 105 |
+
|
| 106 |
+
class PatchEmbed(nn.Module):
|
| 107 |
+
""" Image to Patch Embedding
|
| 108 |
+
"""
|
| 109 |
+
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
|
| 110 |
+
super().__init__()
|
| 111 |
+
num_patches = (img_size // patch_size) * (img_size // patch_size)
|
| 112 |
+
self.img_size = img_size
|
| 113 |
+
self.patch_size = patch_size
|
| 114 |
+
self.num_patches = num_patches
|
| 115 |
+
|
| 116 |
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
|
| 117 |
+
|
| 118 |
+
def forward(self, x):
|
| 119 |
+
B, C, H, W = x.shape
|
| 120 |
+
return self.proj(x)
|
| 121 |
+
|
| 122 |
+
class VisionTransformer(nn.Module):
|
| 123 |
+
""" Vision Transformer """
|
| 124 |
+
def __init__(self, img_size=[224], patch_size=16, in_chans=3, num_classes=0, embed_dim=768, depth=12,
|
| 125 |
+
num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
|
| 126 |
+
drop_path_rate=0., norm_layer=partial(nn.LayerNorm, eps=1e-6), return_all_tokens=False,
|
| 127 |
+
init_values=0, use_mean_pooling=False, masked_im_modeling=False):
|
| 128 |
+
super().__init__()
|
| 129 |
+
self.num_features = self.embed_dim = embed_dim
|
| 130 |
+
self.return_all_tokens = return_all_tokens
|
| 131 |
+
|
| 132 |
+
self.patch_embed = PatchEmbed(
|
| 133 |
+
img_size=img_size[0], patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
|
| 134 |
+
num_patches = self.patch_embed.num_patches
|
| 135 |
+
|
| 136 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
| 137 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
|
| 138 |
+
self.pos_drop = nn.Dropout(p=drop_rate)
|
| 139 |
+
|
| 140 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
|
| 141 |
+
self.blocks = nn.ModuleList([
|
| 142 |
+
Block(
|
| 143 |
+
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
|
| 144 |
+
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
|
| 145 |
+
init_values=init_values)
|
| 146 |
+
for i in range(depth)])
|
| 147 |
+
|
| 148 |
+
self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim)
|
| 149 |
+
self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None
|
| 150 |
+
# Classifier head
|
| 151 |
+
self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
|
| 152 |
+
|
| 153 |
+
trunc_normal_(self.pos_embed, std=.02)
|
| 154 |
+
trunc_normal_(self.cls_token, std=.02)
|
| 155 |
+
self.apply(self._init_weights)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
# masked image modeling
|
| 159 |
+
self.masked_im_modeling = masked_im_modeling
|
| 160 |
+
if masked_im_modeling:
|
| 161 |
+
self.masked_embed = nn.Parameter(torch.zeros(1, embed_dim))
|
| 162 |
+
|
| 163 |
+
def _init_weights(self, m):
|
| 164 |
+
if isinstance(m, nn.Linear):
|
| 165 |
+
trunc_normal_(m.weight, std=.02)
|
| 166 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 167 |
+
nn.init.constant_(m.bias, 0)
|
| 168 |
+
elif isinstance(m, nn.LayerNorm):
|
| 169 |
+
nn.init.constant_(m.bias, 0)
|
| 170 |
+
nn.init.constant_(m.weight, 1.0)
|
| 171 |
+
|
| 172 |
+
def interpolate_pos_encoding(self, x, w, h):
|
| 173 |
+
npatch = x.shape[1] - 1
|
| 174 |
+
N = self.pos_embed.shape[1] - 1
|
| 175 |
+
if npatch == N and w == h:
|
| 176 |
+
return self.pos_embed
|
| 177 |
+
class_pos_embed = self.pos_embed[:, 0]
|
| 178 |
+
patch_pos_embed = self.pos_embed[:, 1:]
|
| 179 |
+
dim = x.shape[-1]
|
| 180 |
+
w0 = w // self.patch_embed.patch_size
|
| 181 |
+
h0 = h // self.patch_embed.patch_size
|
| 182 |
+
# we add a small number to avoid floating point error in the interpolation
|
| 183 |
+
# see discussion at https://github.com/facebookresearch/dino/issues/8
|
| 184 |
+
w0, h0 = w0 + 0.1, h0 + 0.1
|
| 185 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 186 |
+
patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),
|
| 187 |
+
scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)),
|
| 188 |
+
mode='bicubic',
|
| 189 |
+
)
|
| 190 |
+
assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1]
|
| 191 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 192 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 193 |
+
|
| 194 |
+
def prepare_tokens(self, x, no_pe = False, mask=None):
|
| 195 |
+
B, nc, w, h = x.shape
|
| 196 |
+
# patch linear embedding
|
| 197 |
+
x = self.patch_embed(x)
|
| 198 |
+
|
| 199 |
+
# mask image modeling
|
| 200 |
+
if mask is not None:
|
| 201 |
+
x = self.mask_model(x, mask)
|
| 202 |
+
x = x.flatten(2).transpose(1, 2)
|
| 203 |
+
|
| 204 |
+
# add the [CLS] token to the embed patch tokens
|
| 205 |
+
cls_tokens = self.cls_token.expand(B, -1, -1)
|
| 206 |
+
x = torch.cat((cls_tokens, x), dim=1)
|
| 207 |
+
|
| 208 |
+
# add positional encoding to each token
|
| 209 |
+
if not no_pe:
|
| 210 |
+
x = x + self.interpolate_pos_encoding(x, w, h)
|
| 211 |
+
|
| 212 |
+
return self.pos_drop(x)
|
| 213 |
+
|
| 214 |
+
def forward(self, x, return_all_tokens=None, mask=None, no_pe=False):
|
| 215 |
+
# mim
|
| 216 |
+
if self.masked_im_modeling:
|
| 217 |
+
assert mask is not None
|
| 218 |
+
x = self.prepare_tokens(x, no_pe=no_pe, mask=mask)
|
| 219 |
+
else:
|
| 220 |
+
x = self.prepare_tokens(x, no_pe=no_pe)
|
| 221 |
+
|
| 222 |
+
for blk in self.blocks:
|
| 223 |
+
x = blk(x)
|
| 224 |
+
|
| 225 |
+
x = self.norm(x)
|
| 226 |
+
if self.fc_norm is not None:
|
| 227 |
+
x[:, 0] = self.fc_norm(x[:, 1:, :].mean(1))
|
| 228 |
+
|
| 229 |
+
return_all_tokens = self.return_all_tokens if \
|
| 230 |
+
return_all_tokens is None else return_all_tokens
|
| 231 |
+
if return_all_tokens:
|
| 232 |
+
return x
|
| 233 |
+
return x[:, 0]
|
| 234 |
+
|
| 235 |
+
def get_last_selfattention(self, x):
|
| 236 |
+
x = self.prepare_tokens(x)
|
| 237 |
+
for i, blk in enumerate(self.blocks):
|
| 238 |
+
if i < len(self.blocks) - 1:
|
| 239 |
+
x = blk(x)
|
| 240 |
+
else:
|
| 241 |
+
# return attention of the last block
|
| 242 |
+
return blk(x, return_attention=True)
|
| 243 |
+
|
| 244 |
+
def get_intermediate_layers(self, x, n=1):
|
| 245 |
+
x = self.prepare_tokens(x)
|
| 246 |
+
# we return the output tokens from the `n` last blocks
|
| 247 |
+
output = []
|
| 248 |
+
for i, blk in enumerate(self.blocks):
|
| 249 |
+
x = blk(x)
|
| 250 |
+
if len(self.blocks) - i <= n:
|
| 251 |
+
output.append(self.norm(x))
|
| 252 |
+
return output
|
| 253 |
+
|
| 254 |
+
def get_num_layers(self):
|
| 255 |
+
return len(self.blocks)
|
| 256 |
+
|
| 257 |
+
def mask_model(self, x, mask):
|
| 258 |
+
x.permute(0, 2, 3, 1)[mask, :] = self.masked_embed.to(x.dtype)
|
| 259 |
+
return x
|
| 260 |
+
|
| 261 |
+
def vit_tiny(patch_size=16, **kwargs):
|
| 262 |
+
model = VisionTransformer(
|
| 263 |
+
patch_size=patch_size, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4,
|
| 264 |
+
qkv_bias=True, **kwargs)
|
| 265 |
+
return model
|
| 266 |
+
|
| 267 |
+
def vit_small(patch_size=16, **kwargs):
|
| 268 |
+
model = VisionTransformer(
|
| 269 |
+
patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4,
|
| 270 |
+
qkv_bias=True, **kwargs)
|
| 271 |
+
return model
|
| 272 |
+
|
| 273 |
+
def vit_base(patch_size=16, **kwargs):
|
| 274 |
+
model = VisionTransformer(
|
| 275 |
+
patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4,
|
| 276 |
+
qkv_bias=True, **kwargs)
|
| 277 |
+
return model
|
| 278 |
+
|
| 279 |
+
def vit_large(patch_size=16, **kwargs):
|
| 280 |
+
model = VisionTransformer(
|
| 281 |
+
patch_size=patch_size, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4,
|
| 282 |
+
qkv_bias=True, **kwargs)
|
| 283 |
+
return model
|