Spaces:
Runtime error
Runtime error
File size: 5,522 Bytes
3be6475 de87097 3be6475 56995a0 3be6475 56995a0 3be6475 56995a0 3be6475 56995a0 3be6475 56995a0 3be6475 56995a0 3be6475 56995a0 ad164f6 3be6475 56995a0 3be6475 ca05aa5 3be6475 56995a0 3be6475 56995a0 3be6475 56995a0 3be6475 56995a0 3be6475 | 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 | # model_utils.py
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import mobilenet_v2
import torchvision.transforms as transforms
from PIL import Image
import numpy as np
class SimpleEarlyExitMobileNetV2(nn.Module):
def __init__(self, base_model, num_classes=100):
super(SimpleEarlyExitMobileNetV2, self).__init__()
self.features = base_model.features
self.num_classes = num_classes
self.exit_points = [6, 13, 17]
self.exit_classifiers = nn.ModuleList([
self._make_exit_classifier(32),
self._make_exit_classifier(96),
self._make_exit_classifier(320),
])
self.avgpool = nn.AdaptiveAvgPool2d(1)
self.final_classifier = base_model.classifier
def _make_exit_classifier(self, in_channels):
return nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Flatten(),
nn.Linear(in_channels, self.num_classes)
)
def forward(self, x):
x = self.features(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.final_classifier(x)
return x
def forward_with_exits(self, x, threshold=0.9, confidence_metric='max', k_value=5):
exit_taken = -1
confidence_score = 0.0
for i, block in enumerate(self.features):
x = block(x)
if i in self.exit_points:
exit_idx = self.exit_points.index(i)
exit_output = self.exit_classifiers[exit_idx](x)
probs = F.softmax(exit_output, dim=1)
confidence = self._calculate_confidence(probs, confidence_metric, k_value)
if confidence > threshold:
exit_taken = exit_idx
confidence_score = confidence.item()
return exit_output, exit_taken, i+1, confidence_score
x = self.avgpool(x)
x = torch.flatten(x, 1)
final_output = self.final_classifier(x)
probs = F.softmax(final_output, dim=1)
confidence_score = self._calculate_confidence(probs, confidence_metric, k_value).item()
return final_output, exit_taken, len(self.features), confidence_score
def _calculate_confidence(self, probs, metric='max', k_value=5):
if metric == 'max':
return torch.max(probs, dim=1)[0]
elif metric == 'entropy':
entropy = -torch.sum(probs * torch.log(probs + 1e-10), dim=1)
return 1 - (entropy / torch.log(torch.tensor(self.num_classes, dtype=torch.float)))
elif metric == 'margin':
top2 = torch.topk(probs, 2, dim=1)[0]
return top2[:, 0] - top2[:, 1]
elif metric == 'slopev2':
sorted_probs = torch.sort(probs, dim=1, descending=True)[0]
k = min(k_value, self.num_classes)
return sorted_probs[:, 0] - sorted_probs[:, k - 1]
elif metric == 'ensemble':
max_conf = torch.max(probs, dim=1)[0]
top2 = torch.topk(probs, 2, dim=1)[0]
margin_conf = top2[:, 0] - top2[:, 1]
entropy = -torch.sum(probs * torch.log(probs + 1e-10), dim=1)
entropy_conf = 1 - (entropy / torch.log(torch.tensor(self.num_classes, dtype=torch.float)))
return 0.4 * max_conf + 0.4 * margin_conf + 0.2 * entropy_conf
def load_model(model_path, device):
if not os.path.isabs(model_path):
model_path = os.path.abspath(model_path)
base_model = mobilenet_v2(pretrained=False)
base_model.classifier[1] = nn.Linear(base_model.last_channel, 100)
model = SimpleEarlyExitMobileNetV2(base_model, num_classes=100)
model.load_state_dict(torch.load(model_path, map_location=device))
model.to(device)
model.eval()
return model
def get_transform():
return transforms.Compose([
transforms.Resize(32),
transforms.CenterCrop(32),
transforms.ToTensor(),
transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761))
])
def get_class_names():
return [
'apple', 'aquarium_fish', 'baby', 'bear', 'beaver', 'bed', 'bee', 'beetle',
'bicycle', 'bottle', 'bowl', 'boy', 'bridge', 'bus', 'butterfly', 'camel',
'can', 'castle', 'caterpillar', 'cattle', 'chair', 'chimpanzee', 'clock',
'cloud', 'cockroach', 'couch', 'crab', 'crocodile', 'cup', 'dinosaur',
'dolphin', 'elephant', 'flatfish', 'forest', 'fox', 'girl', 'hamster',
'house', 'kangaroo', 'keyboard', 'lamp', 'lawn_mower', 'leopard', 'lion',
'lizard', 'lobster', 'man', 'maple_tree', 'motorcycle', 'mountain', 'mouse',
'mushroom', 'oak_tree', 'orange', 'orchid', 'otter', 'palm_tree', 'pear',
'pickup_truck', 'pine_tree', 'plain', 'plate', 'poppy', 'porcupine',
'possum', 'rabbit', 'raccoon', 'ray', 'road', 'rocket', 'rose',
'sea', 'seal', 'shark', 'shrew', 'skunk', 'skyscraper', 'snail', 'snake',
'spider', 'squirrel', 'streetcar', 'sunflower', 'sweet_pepper', 'table',
'tank', 'telephone', 'television', 'tiger', 'tractor', 'train', 'trout',
'tulip', 'turtle', 'wardrobe', 'whale', 'willow_tree', 'wolf', 'woman',
'worm'
]
def preprocess_image(image):
"""Preprocess PIL image for model"""
transform = get_transform()
return transform(image).unsqueeze(0) |