phungthanhtu's picture
seed 5
e7cea59 verified
Raw History Blame Contribute Delete
2 kB
"""Standalone network for the Ada-CM checkpoints (no training code)."""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet18
class AdaCM(nn.Module):
def __init__(self, num_classes=7, dropout=0.5):
super().__init__()
base = resnet18(weights=None)
self.base = nn.Sequential(*list(base.children())[:-2])
self.output = nn.Sequential(nn.Dropout(dropout), nn.Flatten())
self.classifier = nn.Linear(512, num_classes)
def forward(self, x):
feat = self.base(x)
feat = F.avg_pool2d(feat, feat.size()[2:])
feat = F.normalize(self.output(feat), dim=1)
return self.classifier(feat), feat
def load(repo_id, filename="model.pt", device="cpu"):
"""Download a checkpoint and return a ready-to-use network."""
from huggingface_hub import hf_hub_download
path = hf_hub_download(repo_id, filename)
ckpt = torch.load(path, map_location="cpu", weights_only=True)
net = AdaCM(len(ckpt["classes"]), ckpt["config"]["dropout"])
net.load_state_dict(ckpt["state_dict"])
net.eval().to(device)
net.classes = ckpt["classes"]
net.config = ckpt["config"]
net.metrics = ckpt.get("meta", {})
return net
def predict(net, image_path, device="cpu", topk=3):
"""Return [(class name, probability), ...] for one image."""
from PIL import Image
from torchvision import transforms
cfg = net.config
prep = transforms.Compose([
transforms.Resize(cfg["image_size"]),
transforms.ToTensor(),
transforms.Normalize(cfg["mean"], cfg["std"]),
])
img = Image.open(image_path).convert("RGB")
with torch.no_grad():
logits, _ = net(prep(img).unsqueeze(0).to(device))
probs = logits.softmax(dim=1)[0]
top = torch.topk(probs, min(topk, len(net.classes)))
return [(net.classes[i], float(v)) for v, i in zip(top.values, top.indices)]