Download ssl_retrieval/models.py from duyle2408/milk10k_new_code: direct link, hf CLI and curl.
- Browser
- Download file 2.31 kB
-
https://huggingface.co/datasets/duyle2408/milk10k_new_code/resolve/main/ssl_retrieval/models.py
- Command line
-
hf download hf://datasets/duyle2408/milk10k_new_code/ssl_retrieval/models.py
-
curl -L -o models.py https://huggingface.co/datasets/duyle2408/milk10k_new_code/resolve/main/ssl_retrieval/models.py
2.31 kB
| from __future__ import annotations | |
| import timm | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| from torchvision.models import ResNet18_Weights, resnet18 | |
| class Encoder(nn.Module): | |
| output_dim = 512 | |
| def __init__(self, pretrained: bool = True): | |
| super().__init__() | |
| model = resnet18(weights=ResNet18_Weights.DEFAULT if pretrained else None) | |
| model.conv1 = nn.Conv2d(3, 64, 3, 1, 1, bias=False) | |
| model.maxpool = nn.Identity() | |
| model.fc = nn.Identity() | |
| self.model = model | |
| def forward(self, images): | |
| return F.normalize(self.model(images), dim=1) | |
| class SSLModel(nn.Module): | |
| def __init__(self, method: str, pretrained: bool = True, projection_dim: int = 128): | |
| super().__init__() | |
| self.method = method | |
| self.encoder = Encoder(pretrained) | |
| dim = self.encoder.output_dim | |
| self.projector = nn.Sequential(nn.Linear(dim, dim), nn.ReLU(), nn.Linear(dim, projection_dim)) if method in {"simclr", "joint"} else None | |
| self.rotation_head = nn.Linear(dim, 4) if method in {"rotation", "joint"} else None | |
| self.decoder = nn.Sequential( | |
| nn.Linear(dim, 512 * 4 * 4), nn.Unflatten(1, (512, 4, 4)), | |
| nn.ConvTranspose2d(512, 256, 4, 2, 1), nn.ReLU(), | |
| nn.ConvTranspose2d(256, 128, 4, 2, 1), nn.ReLU(), | |
| nn.ConvTranspose2d(128, 64, 4, 2, 1), nn.ReLU(), | |
| nn.ConvTranspose2d(64, 3, 4, 2, 1), nn.Sigmoid(), | |
| ) if method in {"autoencoder", "joint"} else None | |
| def embedding(self, images): | |
| return self.encoder(images) | |
| def project(self, images): | |
| return F.normalize(self.projector(self.encoder(images)), dim=1) | |
| def reconstruct(self, images): | |
| return self.decoder(self.encoder(images)) | |
| def predict_rotation(self, images): | |
| return self.rotation_head(self.encoder(images)) | |
| class DINOEncoder(nn.Module): | |
| def __init__(self, model_name="convnext_tiny.dinov3_lvd1689m"): | |
| super().__init__() | |
| self.model = timm.create_model(model_name, pretrained=True, num_classes=0) | |
| def forward(self, images): | |
| features = self.model(images) | |
| if features.ndim > 2: | |
| features = features.flatten(2).mean(-1) | |
| return F.normalize(features.float(), dim=1) | |