Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,9 +14,9 @@ cfg = {
|
|
| 14 |
"patch_size": 4,
|
| 15 |
"in_channels": 3,
|
| 16 |
"num_classes": 100,
|
| 17 |
-
"emb_dim":
|
| 18 |
-
"num_heads":
|
| 19 |
-
"depth":
|
| 20 |
"mlp_ratio": 4.0,
|
| 21 |
"drop": 0.1
|
| 22 |
}
|
|
@@ -43,16 +43,33 @@ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
| 43 |
|
| 44 |
# ------------------------
|
| 45 |
# Model definition
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
| 48 |
super().__init__()
|
| 49 |
-
|
| 50 |
-
self.
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
def forward(self, x):
|
| 54 |
-
x
|
| 55 |
-
x =
|
|
|
|
|
|
|
| 56 |
return x
|
| 57 |
|
| 58 |
class MLP(nn.Module):
|
|
@@ -77,60 +94,75 @@ class Attention(nn.Module):
|
|
| 77 |
self.num_heads = num_heads
|
| 78 |
head_dim = dim // num_heads
|
| 79 |
self.scale = head_dim ** -0.5
|
|
|
|
| 80 |
self.qkv = nn.Linear(dim, dim*3, bias=qkv_bias)
|
| 81 |
self.attn_drop = nn.Dropout(attn_drop)
|
| 82 |
self.proj = nn.Linear(dim, dim)
|
| 83 |
self.proj_drop = nn.Dropout(proj_drop)
|
|
|
|
| 84 |
def forward(self, x):
|
| 85 |
B, N, C = x.shape
|
| 86 |
-
qkv = self.qkv(x).reshape(B,N,3,self.num_heads,C//self.num_heads).permute(2,0,3,1,4)
|
| 87 |
-
q,k,v = qkv[0], qkv[1], qkv[2]
|
| 88 |
-
attn = (q @ k.transpose(-2,-1)) * self.scale
|
| 89 |
attn = attn.softmax(dim=-1)
|
| 90 |
attn = self.attn_drop(attn)
|
| 91 |
-
x = (attn @ v).transpose(1,2).reshape(B,N,C)
|
| 92 |
x = self.proj(x)
|
| 93 |
x = self.proj_drop(x)
|
| 94 |
return x
|
| 95 |
|
| 96 |
-
class _StochasticDepth(nn.Module):
|
| 97 |
-
def __init__(self, p):
|
| 98 |
-
super().__init__()
|
| 99 |
-
self.p = p
|
| 100 |
-
def forward(self, x):
|
| 101 |
-
if not self.training or self.p==0.:
|
| 102 |
-
return x
|
| 103 |
-
keep = torch.rand(x.shape[0],1,1, device=x.device) >= self.p
|
| 104 |
-
return x * keep / (1 - self.p)
|
| 105 |
-
|
| 106 |
class Block(nn.Module):
|
| 107 |
-
def __init__(self, dim, num_heads, mlp_ratio=4., drop=0., drop_path=0.):
|
| 108 |
super().__init__()
|
| 109 |
self.norm1 = nn.LayerNorm(dim)
|
| 110 |
-
self.attn = Attention(dim, num_heads=num_heads, attn_drop=
|
| 111 |
-
self.drop_path = nn.Identity() if drop_path==0. else _StochasticDepth(drop_path)
|
| 112 |
self.norm2 = nn.LayerNorm(dim)
|
| 113 |
self.mlp = MLP(dim, int(dim*mlp_ratio), drop=drop)
|
|
|
|
| 114 |
def forward(self, x):
|
| 115 |
x = x + self.drop_path(self.attn(self.norm1(x)))
|
| 116 |
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
| 117 |
return x
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
class ViT(nn.Module):
|
| 120 |
def __init__(self, cfg):
|
| 121 |
super().__init__()
|
| 122 |
-
|
|
|
|
|
|
|
| 123 |
n_patches = self.patch_embed.n_patches
|
|
|
|
| 124 |
self.cls_token = nn.Parameter(torch.zeros(1,1,cfg["emb_dim"]))
|
| 125 |
-
self.pos_embed = nn.Parameter(torch.zeros(1, 1+n_patches, cfg["emb_dim"]))
|
| 126 |
self.pos_drop = nn.Dropout(p=cfg["drop"])
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
self.norm = nn.LayerNorm(cfg["emb_dim"])
|
| 130 |
self.head = nn.Linear(cfg["emb_dim"], cfg["num_classes"])
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
| 133 |
self.apply(self._init_weights)
|
|
|
|
| 134 |
def _init_weights(self, m):
|
| 135 |
if isinstance(m, nn.Linear):
|
| 136 |
nn.init.xavier_uniform_(m.weight)
|
|
@@ -139,17 +171,24 @@ class ViT(nn.Module):
|
|
| 139 |
elif isinstance(m, nn.LayerNorm):
|
| 140 |
nn.init.zeros_(m.bias)
|
| 141 |
nn.init.ones_(m.weight)
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
B = x.shape[0]
|
| 144 |
-
x = self.patch_embed(x)
|
| 145 |
-
cls_tokens = self.cls_token.expand(B,-1,-1)
|
| 146 |
-
x = torch.cat((cls_tokens,x),dim=1)
|
| 147 |
x = x + self.pos_embed
|
| 148 |
x = self.pos_drop(x)
|
|
|
|
| 149 |
for blk in self.blocks:
|
| 150 |
x = blk(x)
|
|
|
|
| 151 |
x = self.norm(x)
|
| 152 |
-
cls = x[:,0]
|
| 153 |
out = self.head(cls)
|
| 154 |
return out
|
| 155 |
|
|
@@ -180,7 +219,7 @@ iface = gr.Interface(
|
|
| 180 |
fn=predict,
|
| 181 |
inputs=gr.Image(type="pil"),
|
| 182 |
outputs=gr.Label(num_top_classes=1),
|
| 183 |
-
title="ViT CIFAR-100 Classifier",
|
| 184 |
description="Upload a 32x32 image, and the model predicts the CIFAR-100 class."
|
| 185 |
)
|
| 186 |
|
|
|
|
| 14 |
"patch_size": 4,
|
| 15 |
"in_channels": 3,
|
| 16 |
"num_classes": 100,
|
| 17 |
+
"emb_dim": 384,
|
| 18 |
+
"num_heads": 6,
|
| 19 |
+
"depth": 8,
|
| 20 |
"mlp_ratio": 4.0,
|
| 21 |
"drop": 0.1
|
| 22 |
}
|
|
|
|
| 43 |
|
| 44 |
# ------------------------
|
| 45 |
# Model definition
|
| 46 |
+
# ViT model implementation
|
| 47 |
+
# --- Conv stem (replace PatchEmbed) ---
|
| 48 |
+
class ConvPatchEmbed(nn.Module):
|
| 49 |
+
def __init__(self, in_chans=3, embed_dim=384):
|
| 50 |
super().__init__()
|
| 51 |
+
# Input 32x32 -> conv1: 32x32 -> conv2 stride2 -> 16x16 -> conv3 stride2 -> 8x8
|
| 52 |
+
self.conv = nn.Sequential(
|
| 53 |
+
nn.Conv2d(in_chans, 64, kernel_size=3, stride=1, padding=1, bias=False),
|
| 54 |
+
nn.BatchNorm2d(64),
|
| 55 |
+
nn.ReLU(inplace=True),
|
| 56 |
+
|
| 57 |
+
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
| 58 |
+
nn.BatchNorm2d(128),
|
| 59 |
+
nn.ReLU(inplace=True),
|
| 60 |
+
|
| 61 |
+
nn.Conv2d(128, embed_dim, kernel_size=3, stride=2, padding=1, bias=False),
|
| 62 |
+
nn.BatchNorm2d(embed_dim),
|
| 63 |
+
nn.ReLU(inplace=True),
|
| 64 |
+
)
|
| 65 |
+
# n_patches = (32/4)^2 = 8*8 = 64
|
| 66 |
+
self.n_patches = (32 // 4) ** 2
|
| 67 |
|
| 68 |
def forward(self, x):
|
| 69 |
+
# x: (B, C, H, W)
|
| 70 |
+
x = self.conv(x) # (B, E, H/4, W/4) -> H/4=8 for 32x32
|
| 71 |
+
x = x.flatten(2) # (B, E, N)
|
| 72 |
+
x = x.transpose(1, 2) # (B, N, E)
|
| 73 |
return x
|
| 74 |
|
| 75 |
class MLP(nn.Module):
|
|
|
|
| 94 |
self.num_heads = num_heads
|
| 95 |
head_dim = dim // num_heads
|
| 96 |
self.scale = head_dim ** -0.5
|
| 97 |
+
|
| 98 |
self.qkv = nn.Linear(dim, dim*3, bias=qkv_bias)
|
| 99 |
self.attn_drop = nn.Dropout(attn_drop)
|
| 100 |
self.proj = nn.Linear(dim, dim)
|
| 101 |
self.proj_drop = nn.Dropout(proj_drop)
|
| 102 |
+
|
| 103 |
def forward(self, x):
|
| 104 |
B, N, C = x.shape
|
| 105 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2,0,3,1,4)
|
| 106 |
+
q, k, v = qkv[0], qkv[1], qkv[2] # each: (B, heads, N, head_dim)
|
| 107 |
+
attn = (q @ k.transpose(-2, -1)) * self.scale
|
| 108 |
attn = attn.softmax(dim=-1)
|
| 109 |
attn = self.attn_drop(attn)
|
| 110 |
+
x = (attn @ v).transpose(1,2).reshape(B, N, C)
|
| 111 |
x = self.proj(x)
|
| 112 |
x = self.proj_drop(x)
|
| 113 |
return x
|
| 114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
class Block(nn.Module):
|
| 116 |
+
def __init__(self, dim, num_heads, mlp_ratio=4., drop=0., attn_drop=0., drop_path=0.):
|
| 117 |
super().__init__()
|
| 118 |
self.norm1 = nn.LayerNorm(dim)
|
| 119 |
+
self.attn = Attention(dim, num_heads=num_heads, attn_drop=attn_drop, proj_drop=drop)
|
| 120 |
+
self.drop_path = nn.Identity() if drop_path == 0. else _StochasticDepth(drop_path)
|
| 121 |
self.norm2 = nn.LayerNorm(dim)
|
| 122 |
self.mlp = MLP(dim, int(dim*mlp_ratio), drop=drop)
|
| 123 |
+
|
| 124 |
def forward(self, x):
|
| 125 |
x = x + self.drop_path(self.attn(self.norm1(x)))
|
| 126 |
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
| 127 |
return x
|
| 128 |
|
| 129 |
+
# Simple implementation of stochastic depth
|
| 130 |
+
class _StochasticDepth(nn.Module):
|
| 131 |
+
def __init__(self, p):
|
| 132 |
+
super().__init__()
|
| 133 |
+
self.p = p
|
| 134 |
+
def forward(self, x):
|
| 135 |
+
if not self.training or self.p == 0.:
|
| 136 |
+
return x
|
| 137 |
+
keep = torch.rand(x.shape[0], 1, 1, device=x.device) >= self.p
|
| 138 |
+
return x * keep / (1 - self.p)
|
| 139 |
+
|
| 140 |
class ViT(nn.Module):
|
| 141 |
def __init__(self, cfg):
|
| 142 |
super().__init__()
|
| 143 |
+
img_size, patch_size = cfg["image_size"], cfg["patch_size"]
|
| 144 |
+
# Use ConvPatchEmbed (hybrid) instead of linear patch conv with kernel=patch_size
|
| 145 |
+
self.patch_embed = ConvPatchEmbed(cfg["in_channels"], cfg["emb_dim"])
|
| 146 |
n_patches = self.patch_embed.n_patches
|
| 147 |
+
|
| 148 |
self.cls_token = nn.Parameter(torch.zeros(1,1,cfg["emb_dim"]))
|
| 149 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, 1 + n_patches, cfg["emb_dim"]))
|
| 150 |
self.pos_drop = nn.Dropout(p=cfg["drop"])
|
| 151 |
+
|
| 152 |
+
# transformer blocks
|
| 153 |
+
dpr = [x.item() for x in torch.linspace(0, cfg.get("drop_path", 0.2), cfg["depth"])] # stochastic depth decay
|
| 154 |
+
self.blocks = nn.ModuleList([
|
| 155 |
+
Block(cfg["emb_dim"], num_heads=cfg["num_heads"], mlp_ratio=cfg["mlp_ratio"], drop=cfg["drop"], drop_path=dpr[i])
|
| 156 |
+
for i in range(cfg["depth"])
|
| 157 |
+
])
|
| 158 |
self.norm = nn.LayerNorm(cfg["emb_dim"])
|
| 159 |
self.head = nn.Linear(cfg["emb_dim"], cfg["num_classes"])
|
| 160 |
+
|
| 161 |
+
# init
|
| 162 |
+
nn.init.trunc_normal_(self.pos_embed, std=.02)
|
| 163 |
+
nn.init.trunc_normal_(self.cls_token, std=.02)
|
| 164 |
self.apply(self._init_weights)
|
| 165 |
+
|
| 166 |
def _init_weights(self, m):
|
| 167 |
if isinstance(m, nn.Linear):
|
| 168 |
nn.init.xavier_uniform_(m.weight)
|
|
|
|
| 171 |
elif isinstance(m, nn.LayerNorm):
|
| 172 |
nn.init.zeros_(m.bias)
|
| 173 |
nn.init.ones_(m.weight)
|
| 174 |
+
elif isinstance(m, nn.Conv2d):
|
| 175 |
+
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
|
| 176 |
+
if getattr(m, "bias", None) is not None:
|
| 177 |
+
nn.init.zeros_(m.bias)
|
| 178 |
+
|
| 179 |
+
def forward(self, x):
|
| 180 |
B = x.shape[0]
|
| 181 |
+
x = self.patch_embed(x) # (B, N, E)
|
| 182 |
+
cls_tokens = self.cls_token.expand(B, -1, -1)
|
| 183 |
+
x = torch.cat((cls_tokens, x), dim=1) # (B, 1+N, E)
|
| 184 |
x = x + self.pos_embed
|
| 185 |
x = self.pos_drop(x)
|
| 186 |
+
|
| 187 |
for blk in self.blocks:
|
| 188 |
x = blk(x)
|
| 189 |
+
|
| 190 |
x = self.norm(x)
|
| 191 |
+
cls = x[:, 0]
|
| 192 |
out = self.head(cls)
|
| 193 |
return out
|
| 194 |
|
|
|
|
| 219 |
fn=predict,
|
| 220 |
inputs=gr.Image(type="pil"),
|
| 221 |
outputs=gr.Label(num_top_classes=1),
|
| 222 |
+
title="Hybrid ViT+CNN CIFAR-100 Classifier",
|
| 223 |
description="Upload a 32x32 image, and the model predicts the CIFAR-100 class."
|
| 224 |
)
|
| 225 |
|