Instructions to use ntuhophai/ERM-AI with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- timm
How to use ntuhophai/ERM-AI with timm:
import timm model = timm.create_model("hf-hub:ntuhophai/ERM-AI", pretrained=True) - Notebooks
- Google Colab
- Kaggle
Download modeling_multistream.py from ntuhophai/ERM-AI: direct link, hf CLI and curl.
- Browser
- Download file 7.43 kB
-
https://huggingface.co/ntuhophai/ERM-AI/resolve/main/modeling_multistream.py
- Command line
-
hf download hf://ntuhophai/ERM-AI/modeling_multistream.py
-
curl -L -o modeling_multistream.py https://huggingface.co/ntuhophai/ERM-AI/resolve/main/modeling_multistream.py
7.43 kB
| """Load public multistream weights without private training metadata.""" | |
| from pathlib import Path | |
| import json | |
| import timm | |
| import torch | |
| from torch import nn | |
| from safetensors.torch import load_file | |
| def _strict_load(model, state): | |
| expected = model.state_dict() | |
| if set(expected) != set(state): | |
| missing, extra = set(expected) - set(state), set(state) - set(expected) | |
| raise ValueError("Weight keys differ: missing=%s, extra=%s" % | |
| (sorted(missing), sorted(extra))) | |
| for key, value in state.items(): | |
| if tuple(value.shape) != tuple(expected[key].shape): | |
| raise ValueError("Weight shape differs for " + key) | |
| model.load_state_dict(state, strict=True) | |
| class SingleStreamClassifier(nn.Module): | |
| def __init__(self, name, streams, num_classes, freeze_backbones=False): | |
| super().__init__() | |
| self.streams = tuple(streams) | |
| self.network = timm.create_model(name, pretrained=False, num_classes=num_classes) | |
| self.freeze_backbones = freeze_backbones | |
| if freeze_backbones: | |
| for parameter in self.network.parameters(): | |
| parameter.requires_grad_(False) | |
| for parameter in self.network.get_classifier().parameters(): | |
| parameter.requires_grad_(True) | |
| self.train(self.training) | |
| def forward(self, images): | |
| _check_images(images, len(self.streams)) | |
| return self.network(images[:, 0]) | |
| def train(self, mode=True): | |
| super().train(mode) | |
| if getattr(self, "freeze_backbones", False): | |
| self.network.eval() | |
| self.network.get_classifier().train(mode) | |
| return self | |
| def state_dict(self, *args, **kwargs): | |
| return self.network.state_dict(*args, **kwargs) | |
| def load_state_dict(self, state, strict=True, **kwargs): | |
| if not strict: | |
| raise ValueError("Partial weight loading is disabled") | |
| return self.network.load_state_dict(state, strict=True, **kwargs) | |
| class MultiStreamClassifier(nn.Module): | |
| def __init__(self, name, streams, num_classes, hidden_dim=2048, | |
| freeze_backbones=False): | |
| super().__init__() | |
| self.streams = tuple(streams) | |
| self.backbones = nn.ModuleList([ | |
| timm.create_model(name, pretrained=False, num_classes=0, global_pool="avg") | |
| for _ in streams | |
| ]) | |
| features = sum(int(backbone.num_features) for backbone in self.backbones) | |
| self.fusion = nn.Sequential( | |
| nn.Linear(features, hidden_dim), nn.ReLU(), | |
| nn.Linear(hidden_dim, hidden_dim), | |
| ) | |
| self.classifier = nn.Linear(hidden_dim, num_classes) | |
| self.freeze_backbones = freeze_backbones | |
| if freeze_backbones: | |
| for parameter in self.backbones.parameters(): | |
| parameter.requires_grad_(False) | |
| self.train(self.training) | |
| def forward(self, images): | |
| _check_images(images, len(self.streams)) | |
| features = [backbone(images[:, index]) | |
| for index, backbone in enumerate(self.backbones)] | |
| return self.classifier(self.fusion(torch.cat(features, dim=1))) | |
| def train(self, mode=True): | |
| super().train(mode) | |
| if getattr(self, "freeze_backbones", False): | |
| self.backbones.eval() | |
| return self | |
| def _check_images(images, streams): | |
| if not isinstance(images, torch.Tensor) or images.ndim != 5: | |
| raise ValueError("Expected images shaped [B, S, 3, H, W]") | |
| if images.shape[0] < 1 or images.shape[1] != streams or images.shape[2] != 3: | |
| raise ValueError("Batch, stream count or RGB channels do not match") | |
| def build_model(model_config, streams, num_classes, initialize=False): | |
| if initialize: | |
| raise ValueError("Public loading does not perform pretrained initialization") | |
| if not isinstance(streams, (list, tuple)) or not 1 <= len(streams) <= 8: | |
| raise ValueError("Expected 1 to 8 explicitly ordered streams") | |
| if any(not isinstance(stream, str) or not stream for stream in streams): | |
| raise ValueError("Stream names must be nonempty strings") | |
| if len(set(streams)) != len(streams): | |
| raise ValueError("Stream names must be unique") | |
| if type(num_classes) is not int or num_classes < 2: | |
| raise ValueError("Expected at least two classes") | |
| name = model_config["name"] | |
| if not isinstance(name, str) or not timm.is_model(name): | |
| raise ValueError("Architecture must be registered locally in timm") | |
| hidden = model_config.get("hidden_dim", 2048) | |
| if type(hidden) is not int or hidden < 1: | |
| raise ValueError("hidden_dim must be a positive integer") | |
| frozen = model_config.get("freeze_backbones", False) | |
| if type(frozen) is not bool: | |
| raise ValueError("freeze_backbones must be a boolean") | |
| if len(streams) == 1: | |
| return SingleStreamClassifier(name, streams, num_classes, frozen) | |
| return MultiStreamClassifier(name, streams, num_classes, hidden, frozen) | |
| def load_public_model(directory, device="cpu"): | |
| directory = Path(directory) | |
| config = json.loads((directory / "config.json").read_text(encoding="utf-8")) | |
| if config.get("public_format_version") != 1: | |
| raise ValueError("Unsupported public export version") | |
| classes = config["class_to_idx"] | |
| if (not isinstance(classes, dict) or len(classes) < 2 | |
| or any(not isinstance(name, str) or type(index) is not int | |
| for name, index in classes.items()) | |
| or sorted(classes.values()) != list(range(len(classes)))): | |
| raise ValueError("Invalid public class mapping") | |
| model = build_model(config["model_config"], config["streams"], len(classes)) | |
| _strict_load(model, load_file(str(directory / "model.safetensors"), device="cpu")) | |
| model.public_config = config | |
| model.class_to_idx = classes | |
| model.preprocessing = config["preprocessing"] | |
| return model.to(device).eval() | |
| def preprocess_streams(paths, preprocessing): | |
| """Return [1, S, 3, H, W] in the supplied path order.""" | |
| from PIL import Image | |
| from torchvision.transforms import functional as F | |
| from torchvision.transforms import InterpolationMode | |
| tensors = [] | |
| backend = preprocessing.get("resize_backend", "pil") | |
| for path in paths: | |
| with Image.open(path) as opened: | |
| image = opened.convert("RGB") | |
| if backend == "tensor": | |
| tensor = F.resize( | |
| F.to_tensor(image), preprocessing["resize_size"], | |
| interpolation=InterpolationMode.BILINEAR, | |
| antialias=preprocessing["antialias"], | |
| ) | |
| elif backend == "pil": | |
| image = F.resize(image, preprocessing["resize_size"], | |
| interpolation=InterpolationMode.BILINEAR) | |
| tensor = F.to_tensor(image) | |
| else: | |
| raise ValueError("Unsupported resize backend") | |
| tensor = F.center_crop(tensor, [preprocessing["image_size"]] * 2) | |
| tensors.append(F.normalize(tensor, preprocessing["mean"], preprocessing["std"])) | |
| if not tensors: | |
| raise ValueError("Supply one image path per declared stream") | |
| return torch.stack(tensors).unsqueeze(0) | |