Spaces:
Runtime error
Runtime error
Download src/model_utils.py from mahinkumar/RAINN: direct link, hf CLI and curl.
- Browser
- Download file 5.52 kB
-
https://huggingface.co/spaces/mahinkumar/RAINN/resolve/main/src/model_utils.py
- Command line
-
hf download hf://spaces/mahinkumar/RAINN/src/model_utils.py
-
curl -L -o model_utils.py https://huggingface.co/spaces/mahinkumar/RAINN/resolve/main/src/model_utils.py
5.52 kB
| # 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) |