1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
| class VisionTransformer(nn.Module):
def __init__( self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True, qk_scale=None, representation_size=None, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, norm_layer=None, add_norm_before_transformer=False, no_patch_embed_bias=False, config=None, ): """ Args: img_size (int, tuple): input image size patch_size (int, tuple): patch size in_chans (int): number of input channels num_classes (int): number of classes for classification head embed_dim (int): embedding dimension depth (int): depth of transformer num_heads (int): number of attention heads mlp_ratio (int): ratio of mlp hidden dim to embedding dim qkv_bias (bool): enable bias for qkv if True qk_scale (float): override default qk scale of head_dim ** -0.5 if set representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set drop_rate (float): dropout rate attn_drop_rate (float): attention dropout rate drop_path_rate (float): stochastic depth rate hybrid_backbone (nn.Module): CNN backbone to use in-place of PatchEmbed module norm_layer: (nn.Module): normalization layer """ super().__init__() drop_rate = drop_rate if config is None else config["drop_rate"]
self.num_classes = num_classes self.num_features = ( self.embed_dim ) = embed_dim norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6) self.add_norm_before_transformer = add_norm_before_transformer
self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, ) num_patches = self.patch_embed.num_patches
self.patch_size = patch_size self.patch_dim = img_size // patch_size self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) self.pos_drop = nn.Dropout(p=drop_rate)
if add_norm_before_transformer: self.pre_norm = norm_layer(embed_dim)
dpr = [ x.item() for x in torch.linspace(0, drop_path_rate, depth) ] self.blocks = nn.ModuleList( [ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, ) for i in range(depth) ] ) self.norm = norm_layer(embed_dim)
trunc_normal_(self.pos_embed, std=0.02) trunc_normal_(self.cls_token, std=0.02) self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=0.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0)
@torch.jit.ignore def no_weight_decay(self): return {"pos_embed", "cls_token"}
def mask_tokens(self, orig_image, feats): """ Prepare masked tokens inputs/labels for masked patch prediction: 80% MASK, 10% random, 10% original. """ img_unnorm = orig_image * 0.5 + 0.5 _, _, ph, pw = self.patch_embed.proj.weight.shape with torch.no_grad(): img_unnorm_patch = F.conv2d( img_unnorm, weight=torch.ones(3, 1, ph, pw).to(img_unnorm) / (ph * pw), bias=None, stride=(ph, pw), padding=0, groups=3, ) labels = ( ((img_unnorm_patch * 255).long().flatten(start_dim=2, end_dim=3)) .permute(0, 2, 1) .contiguous() )
probability_matrix = torch.full(labels.shape[:-1], 0.15) masked_indices = torch.bernoulli(probability_matrix).bool() labels[~masked_indices] = -100
indices_replaced = ( torch.bernoulli(torch.full(labels.shape[:-1], 0.8)).bool() & masked_indices ) feats[indices_replaced] = self.mask_token.to(feats)
return feats, labels
def visual_embed(self, _x, max_image_len=200, mask_it=False): _, _, ph, pw = self.patch_embed.proj.weight.shape
x = self.patch_embed(_x) x_mask = (_x.sum(dim=1) != 0).float()[:, None, :, :] x_mask = F.interpolate(x_mask, size=(x.shape[2], x.shape[3])).long() x_h = x_mask[:, 0].sum(dim=1)[:, 0] x_w = x_mask[:, 0].sum(dim=2)[:, 0]
B, C, H, W = x.shape spatial_pos = ( self.pos_embed[:, 1:, :] .transpose(1, 2) .view(1, C, self.patch_dim, self.patch_dim) ) pos_embed = torch.cat( [ F.pad( F.interpolate( spatial_pos, size=(h, w), mode="bilinear", align_corners=True, ), (0, W - w, 0, H - h), ) for h, w in zip(x_h, x_w) ], dim=0, )
pos_embed = pos_embed.flatten(2).transpose(1, 2) x = x.flatten(2).transpose(1, 2) patch_index = ( torch.stack( torch.meshgrid( torch.arange(x_mask.shape[-2]), torch.arange(x_mask.shape[-1]) ), dim=-1, )[None, None, :, :, :] .expand(x_mask.shape[0], x_mask.shape[1], -1, -1, -1) .flatten(1, 3) ) x_mask = x_mask.flatten(1)
if mask_it: x, label = self.mask_tokens(_x, x)
if ( max_image_len < 0 or max_image_len is None or not isinstance(max_image_len, int) ): eff = x_h * x_w max_image_len = eff.max() else: eff = x_h * x_w max_image_len = min(eff.max(), max_image_len)
valid_idx = x_mask.nonzero(as_tuple=False) non_valid_idx = (1 - x_mask).nonzero(as_tuple=False) unique_rows = valid_idx[:, 0].unique() valid_row_idx = [valid_idx[valid_idx[:, 0] == u] for u in unique_rows] non_valid_row_idx = [ non_valid_idx[non_valid_idx[:, 0] == u] for u in unique_rows ]
valid_nums = [v.size(0) for v in valid_row_idx] non_valid_nums = [v.size(0) for v in non_valid_row_idx] pad_nums = [max_image_len - v for v in valid_nums]
select = list() for i, (v, nv, p) in enumerate(zip(valid_nums, non_valid_nums, pad_nums)): if p <= 0: valid_choice = torch.multinomial(torch.ones(v).float(), max_image_len) select.append(valid_row_idx[i][valid_choice]) else: pad_choice = torch.multinomial( torch.ones(nv).float(), p, replacement=True ) select.append( torch.cat( [valid_row_idx[i], non_valid_row_idx[i][pad_choice]], dim=0, ) )
select = torch.cat(select, dim=0) x = x[select[:, 0], select[:, 1]].view(B, -1, C) x_mask = x_mask[select[:, 0], select[:, 1]].view(B, -1) patch_index = patch_index[select[:, 0], select[:, 1]].view(B, -1, 2) pos_embed = pos_embed[select[:, 0], select[:, 1]].view(B, -1, C)
if mask_it: label = label[select[:, 0], select[:, 1]].view(B, -1, 3)
label[x_mask == 0] = -100 label = torch.cat( [torch.full((label.shape[0], 1, 3), -100).to(label), label,], dim=1, )
cls_tokens = self.cls_token.expand(B, -1, -1) x = torch.cat((cls_tokens, x), dim=1) pos_embed = torch.cat( (self.pos_embed[:, 0, :][:, None, :].expand(B, -1, -1), pos_embed), dim=1 ) x = x + pos_embed x = self.pos_drop(x)
if self.add_norm_before_transformer: x = self.pre_norm(x)
x_mask = torch.cat([torch.ones(x_mask.shape[0], 1).to(x_mask), x_mask], dim=1)
if mask_it: return x, x_mask, (patch_index, (H, W)), label else: return x, x_mask, (patch_index, (H, W)), None
def forward_features(self, _x, max_image_len=144, mask_it=False): x, x_mask, patch_index, label = self.visual_embed( _x, max_image_len=max_image_len, mask_it=mask_it )
for blk in self.blocks: x, _ = blk(x, mask=x_mask)
x = self.norm(x) return x, x_mask, label
def forward(self, x, max_image_len=-1): x, _, _ = self.forward_features(x, max_image_len=max_image_len) x = x[:, 0] x = self.head(x) return x
|