Spaces:
Sleeping
Sleeping
Update model_loader.py
Browse files- model_loader.py +96 -8
model_loader.py
CHANGED
|
@@ -1,16 +1,104 @@
|
|
| 1 |
import torch
|
| 2 |
import torch.nn as nn
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
self.
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
def forward(self, x):
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def load_model(model_path='InceptionViT_best_model.pth'):
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
return model
|
|
|
|
| 1 |
import torch
|
| 2 |
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import timm
|
| 5 |
|
| 6 |
+
# --- PART 1: The Stem Class ---
|
| 7 |
+
class InceptionStem(nn.Module):
|
| 8 |
+
def __init__(self, in_channels=3, out_channels=64):
|
| 9 |
+
super().__init__()
|
| 10 |
+
self.branch1 = nn.Sequential(
|
| 11 |
+
nn.Conv2d(in_channels, out_channels//2, kernel_size=1, stride=1, padding=0),
|
| 12 |
+
nn.ReLU(inplace=True)
|
| 13 |
+
)
|
| 14 |
+
self.branch3 = nn.Sequential(
|
| 15 |
+
nn.Conv2d(in_channels, out_channels//2, kernel_size=3, stride=1, padding=1),
|
| 16 |
+
nn.ReLU(inplace=True)
|
| 17 |
+
)
|
| 18 |
+
self.pool_branch = nn.Sequential(
|
| 19 |
+
nn.MaxPool2d(3, stride=1, padding=1),
|
| 20 |
+
nn.Conv2d(in_channels, out_channels//2, kernel_size=1),
|
| 21 |
+
nn.ReLU(inplace=True)
|
| 22 |
+
)
|
| 23 |
+
self.project = nn.Conv2d(out_channels + out_channels//2, out_channels, kernel_size=1)
|
| 24 |
+
self.bn = nn.BatchNorm2d(out_channels)
|
| 25 |
|
| 26 |
def forward(self, x):
|
| 27 |
+
b1 = self.branch1(x)
|
| 28 |
+
b3 = self.branch3(x)
|
| 29 |
+
p = self.pool_branch(x)
|
| 30 |
+
cat = torch.cat([b1, b3, p], dim=1)
|
| 31 |
+
out = F.relu(self.bn(self.project(cat)))
|
| 32 |
+
return out
|
| 33 |
|
| 34 |
+
# --- PART 2: The Main Model Class ---
|
| 35 |
+
class InceptionViT(nn.Module):
|
| 36 |
+
def __init__(self, vit_model_name='vit_base_patch16_224', pretrained=False, stem_out_channels=64, num_classes=2, dropout=0.3):
|
| 37 |
+
# NOTE: We set pretrained=False here because we are loading YOUR weights,
|
| 38 |
+
# so we don't need to download the ImageNet weights again.
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.stem = InceptionStem(in_channels=3, out_channels=stem_out_channels)
|
| 41 |
+
|
| 42 |
+
self.vit = timm.create_model(vit_model_name, pretrained=False, num_classes=0, global_pool='')
|
| 43 |
+
self.embed_dim = self.vit.num_features
|
| 44 |
+
self.stem_pool = nn.AdaptiveAvgPool2d(1)
|
| 45 |
+
self.stem_proj = nn.Linear(stem_out_channels, self.embed_dim)
|
| 46 |
+
|
| 47 |
+
self.classifier = nn.Sequential(
|
| 48 |
+
nn.LayerNorm(self.embed_dim),
|
| 49 |
+
nn.Dropout(dropout),
|
| 50 |
+
nn.Linear(self.embed_dim, num_classes)
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
def forward(self, x):
|
| 54 |
+
stem_feat_map = self.stem(x)
|
| 55 |
+
|
| 56 |
+
stem_vec = self.stem_pool(stem_feat_map).view(x.size(0), -1)
|
| 57 |
+
stem_emb = self.stem_proj(stem_vec)
|
| 58 |
+
|
| 59 |
+
B = x.size(0)
|
| 60 |
+
x_vit = self.vit.patch_embed(x)
|
| 61 |
+
cls_tokens = self.vit.cls_token.expand(B, -1, -1)
|
| 62 |
+
x_vit = torch.cat((cls_tokens, x_vit), dim=1)
|
| 63 |
+
x_vit = x_vit + self.vit.pos_embed[:, : x_vit.size(1), :].to(x.device)
|
| 64 |
+
x_vit = self.vit.pos_drop(x_vit)
|
| 65 |
+
|
| 66 |
+
for blk in self.vit.blocks:
|
| 67 |
+
x_vit = blk(x_vit)
|
| 68 |
+
x_vit = self.vit.norm(x_vit)
|
| 69 |
+
|
| 70 |
+
x_vit[:, 0, :] = x_vit[:, 0, :] + stem_emb
|
| 71 |
+
|
| 72 |
+
cls_emb = x_vit[:, 0, :]
|
| 73 |
+
out = self.classifier(cls_emb)
|
| 74 |
+
return out
|
| 75 |
+
|
| 76 |
+
# --- PART 3: The Loader Function ---
|
| 77 |
def load_model(model_path='InceptionViT_best_model.pth'):
|
| 78 |
+
print(f"Loading InceptionViT from {model_path}...")
|
| 79 |
+
|
| 80 |
+
# 1. Initialize the empty model structure
|
| 81 |
+
# CRITICAL: We must match the arguments you used in training!
|
| 82 |
+
# Looking at your code: num_classes=?, dropout=0.4
|
| 83 |
+
# Since I don't know your exact num_classes, I will inspect the weights to find it dynamically.
|
| 84 |
+
|
| 85 |
+
# Load weights first to check dimensions
|
| 86 |
+
state_dict = torch.load(model_path, map_location='cpu')
|
| 87 |
+
|
| 88 |
+
# Auto-detect number of classes from the last layer weight
|
| 89 |
+
# The key is usually "classifier.2.weight" based on your Sequential block
|
| 90 |
+
if "classifier.2.weight" in state_dict:
|
| 91 |
+
num_classes = state_dict["classifier.2.weight"].shape[0]
|
| 92 |
+
print(f"Auto-detected {num_classes} classes.")
|
| 93 |
+
else:
|
| 94 |
+
num_classes = 2 # Default fallback
|
| 95 |
+
print("Could not auto-detect classes, defaulting to 2.")
|
| 96 |
+
|
| 97 |
+
# Create the model
|
| 98 |
+
model = InceptionViT(num_classes=num_classes, dropout=0.4)
|
| 99 |
+
|
| 100 |
+
# Load the weights
|
| 101 |
+
model.load_state_dict(state_dict)
|
| 102 |
+
model.eval()
|
| 103 |
+
|
| 104 |
return model
|