Upload folder using huggingface_hub
Browse files- README.md +73 -3
- config.json +5 -0
- model.safetensors +3 -0
- models/ndlinear_util.py +140 -0
- models/resnet.py +227 -0
- models/utils_resnet.py +382 -0
- ndlinear.py +82 -0
README.md
CHANGED
|
@@ -1,3 +1,73 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# FaceNet Triplet ResNet Model (Grayscale, 112x112, Mobile-friendly)
|
| 2 |
+
|
| 3 |
+
This repository provides a FaceNet-style triplet embedding model using ResNet backbones, optimized for mobile and edge devices:
|
| 4 |
+
- Input: **Grayscale images** (`3` channel)
|
| 5 |
+
- Resolution: **112x112 pixels**
|
| 6 |
+
- Output: **Embeddings** suitable for face recognition and verification
|
| 7 |
+
|
| 8 |
+
## Model Details
|
| 9 |
+
|
| 10 |
+
- **Architecture:** ResNet50 with NdLinear
|
| 11 |
+
- **Embedding Dimension:** 512
|
| 12 |
+
- **Input:** 3x112x112 grayscale images (NCHW format)
|
| 13 |
+
- **Exported weights:** `model.safetensors`
|
| 14 |
+
- **Config:** `config.json`
|
| 15 |
+
|
| 16 |
+
## Usage
|
| 17 |
+
|
| 18 |
+
### 1. Clone or Download Files
|
| 19 |
+
|
| 20 |
+
Download/copy the `models/` directory and dependencies (`ndlinear.py`, etc.) to your project.
|
| 21 |
+
|
| 22 |
+
### 2. Install requirements
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
pip install torch safetensors
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
### 3. Load the model
|
| 29 |
+
|
| 30 |
+
```python
|
| 31 |
+
from models.resnet import Resnet50Triplet # or your chosen variant
|
| 32 |
+
|
| 33 |
+
model = Resnet50Triplet.from_pretrained(".", safe_serialization=True)
|
| 34 |
+
model.eval()
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
### 4. Use for Face Recognition
|
| 38 |
+
|
| 39 |
+
Obtain a face embedding from an input image, and compare embeddings (e.g., with cosine similarity) to recognize or verify identities.
|
| 40 |
+
|
| 41 |
+
```python
|
| 42 |
+
import torch
|
| 43 |
+
|
| 44 |
+
# Example: batch of 1 grayscale image of 112x112
|
| 45 |
+
images = torch.randn(1, 1, 112, 112) # (batch_size, channels, height, width)
|
| 46 |
+
|
| 47 |
+
with torch.no_grad():
|
| 48 |
+
embedding = model(images) # embedding output suitable for face recognition
|
| 49 |
+
print(embedding.shape) # (batch_size, embedding_dim)
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
To perform recognition or verification, compare the embedding against a database of known face embeddings using distance/similarity metrics.
|
| 53 |
+
|
| 54 |
+
## Files
|
| 55 |
+
|
| 56 |
+
- `model.safetensors` - Model weights
|
| 57 |
+
- `config.json` - Loader configuration
|
| 58 |
+
- `models/` - Model definition files
|
| 59 |
+
- `README.md` - This file
|
| 60 |
+
|
| 61 |
+
## Notes
|
| 62 |
+
|
| 63 |
+
- Model is optimized for runtime on edge/mobile devices (reduced input size, grayscale input for lower computational load)
|
| 64 |
+
- Make sure your image preprocess pipeline produces three identical grayscaled channels, 112x112 images.
|
| 65 |
+
|
| 66 |
+
## Credits
|
| 67 |
+
|
| 68 |
+
- Backbone based on [PyTorch torchvision ResNet](https://pytorch.org/vision/stable/models/generated/torchvision.models.resnet50.html)
|
| 69 |
+
- Architecture inspired by [Facenet PyTorch](https://github.com/timesler/facenet-pytorch)
|
| 70 |
+
|
| 71 |
+
---
|
| 72 |
+
|
| 73 |
+
*For contributions or issues, open a discussion or pull request.*
|
config.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_class": "Resnet50NdTriplet",
|
| 3 |
+
"embedding_dimension": 512,
|
| 4 |
+
"pretrained": false
|
| 5 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2bae12f646679e6b0b80acd9cd4cac9e2071d4c5e83053b04012b82787e14186
|
| 3 |
+
size 94537792
|
models/ndlinear_util.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import time
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import wandb
|
| 8 |
+
from fvcore.nn import FlopCountAnalysis
|
| 9 |
+
from sklearn.metrics import roc_curve
|
| 10 |
+
from torchvision import models, transforms
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
from ndlinear import NdLinear
|
| 14 |
+
|
| 15 |
+
transform = transforms.Compose([
|
| 16 |
+
transforms.Resize((224, 224)),
|
| 17 |
+
transforms.RandomHorizontalFlip(),
|
| 18 |
+
transforms.ColorJitter(brightness=0.2, contrast=0.2),
|
| 19 |
+
transforms.RandomRotation(10),
|
| 20 |
+
transforms.RandomResizedCrop((224, 224), scale=(0.8, 1.0)),
|
| 21 |
+
transforms.ToTensor(),
|
| 22 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
| 23 |
+
std=[0.229, 0.224, 0.225])
|
| 24 |
+
])
|
| 25 |
+
|
| 26 |
+
class ReshapedNdLinear(torch.nn.Module):
|
| 27 |
+
def __init__(self, nd_linear_layer):
|
| 28 |
+
super(ReshapedNdLinear, self).__init__()
|
| 29 |
+
self.nd_linear = nd_linear_layer
|
| 30 |
+
|
| 31 |
+
def forward(self, x):
|
| 32 |
+
x = x.reshape(*x.shape, 1)
|
| 33 |
+
x = self.nd_linear(x)
|
| 34 |
+
return x.view(x.size(0), -1)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def print_cpu_layers(model):
|
| 38 |
+
found_cpu_layer = False
|
| 39 |
+
for name, module in model.named_modules():
|
| 40 |
+
if any(p.device.type == 'cpu' for p in module.parameters(recurse=False)):
|
| 41 |
+
print(f"Layer: {name}, Device: CPU")
|
| 42 |
+
found_cpu_layer = True
|
| 43 |
+
if not found_cpu_layer:
|
| 44 |
+
print("No layers are on the CPU.")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def calculate_flops(model, input_tensor):
|
| 48 |
+
model.eval()
|
| 49 |
+
device = next(model.parameters()).device
|
| 50 |
+
input_tensor = input_tensor.to(device)
|
| 51 |
+
flops_analysis = FlopCountAnalysis(model, input_tensor)
|
| 52 |
+
flops = flops_analysis.total()
|
| 53 |
+
return flops
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def print_model_parameters(model):
|
| 57 |
+
return sum(p.numel() for p in model.parameters())
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def measure_latency_and_flops_cuda(model, input_tensor, warmup=10, runs=100):
|
| 61 |
+
assert torch.cuda.is_available(), "CUDA is not available."
|
| 62 |
+
device = torch.device('cuda')
|
| 63 |
+
model.to(device)
|
| 64 |
+
input_tensor = input_tensor.to(device)
|
| 65 |
+
model.eval()
|
| 66 |
+
torch.backends.cudnn.benchmark = True
|
| 67 |
+
|
| 68 |
+
with torch.no_grad():
|
| 69 |
+
for _ in range(warmup):
|
| 70 |
+
_ = model(input_tensor)
|
| 71 |
+
torch.cuda.synchronize()
|
| 72 |
+
|
| 73 |
+
timings = []
|
| 74 |
+
with torch.no_grad():
|
| 75 |
+
for _ in range(runs):
|
| 76 |
+
start = time.time()
|
| 77 |
+
_ = model(input_tensor)
|
| 78 |
+
torch.cuda.synchronize()
|
| 79 |
+
end = time.time()
|
| 80 |
+
timings.append(end - start)
|
| 81 |
+
|
| 82 |
+
avg_latency = sum(timings) / len(timings)
|
| 83 |
+
flops = calculate_flops(model, input_tensor[:1, ...])
|
| 84 |
+
|
| 85 |
+
print(f"Average CUDA Latency over {runs} runs: {avg_latency * 1000:.3f} ms")
|
| 86 |
+
print(f"Approx. FPS: {1.0 / avg_latency:.2f}")
|
| 87 |
+
print(f"Approx. Flops: {flops / 10 ** 9:.2f} GFlops")
|
| 88 |
+
|
| 89 |
+
return avg_latency, flops
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def modify_and_evaluate_backbone(model, cfg):
|
| 93 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 94 |
+
model.train()
|
| 95 |
+
|
| 96 |
+
in_features = model.fc.in_features
|
| 97 |
+
fc_nd = NdLinear((in_features, 1), (cfg.embedding_size // 32, 32))
|
| 98 |
+
reshaped_fc = ReshapedNdLinear(fc_nd).to(device)
|
| 99 |
+
|
| 100 |
+
# Add dropout to the student model's fully connected layer
|
| 101 |
+
model.fc = nn.Sequential(
|
| 102 |
+
nn.Dropout(p=0.2),
|
| 103 |
+
reshaped_fc
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
for param in model.fc.parameters():
|
| 107 |
+
param.requires_grad = True
|
| 108 |
+
|
| 109 |
+
total_params = print_model_parameters(model)
|
| 110 |
+
wandb.log({"total_parameters": total_params})
|
| 111 |
+
|
| 112 |
+
model.to(device)
|
| 113 |
+
print_cpu_layers(model)
|
| 114 |
+
print(model)
|
| 115 |
+
return model
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def load_config(config_path='config.json'):
|
| 119 |
+
try:
|
| 120 |
+
with open(config_path, 'r') as f:
|
| 121 |
+
return json.load(f)
|
| 122 |
+
except FileNotFoundError as fe:
|
| 123 |
+
config = {
|
| 124 |
+
"learning_rate": 0.001, # Adjusted learning rate
|
| 125 |
+
"epochs": 1000,
|
| 126 |
+
"batch_size": 32,
|
| 127 |
+
"eval_batch_size": 512,
|
| 128 |
+
"eval_every": 1000
|
| 129 |
+
}
|
| 130 |
+
return config
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def find_optimal_threshold(embeddings1, embeddings2, labels):
|
| 134 |
+
cosine_sim = np.sum(embeddings1 * embeddings2, axis=1)
|
| 135 |
+
fpr, tpr, thresholds = roc_curve(labels, cosine_sim)
|
| 136 |
+
# Youden's J statistic
|
| 137 |
+
j_scores = tpr - fpr
|
| 138 |
+
optimal_idx = np.argmax(j_scores)
|
| 139 |
+
optimal_threshold = thresholds[optimal_idx]
|
| 140 |
+
return optimal_threshold
|
models/resnet.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
from torch.nn import functional as F
|
| 3 |
+
from ndlinear import NdLinear
|
| 4 |
+
from .utils_resnet import resnet18, resnet34, resnet50, resnet101, resnet152, resnet34nd
|
| 5 |
+
from .ndlinear_util import ReshapedNdLinear
|
| 6 |
+
import torch
|
| 7 |
+
from safetensors.torch import save_file as safe_save, load_file as safe_load
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
class PretrainedTripletModel(nn.Module):
|
| 12 |
+
def save_pretrained(self, save_directory, safe_serialization=True):
|
| 13 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 14 |
+
# Save config
|
| 15 |
+
config = {
|
| 16 |
+
"model_class": self.__class__.__name__,
|
| 17 |
+
"embedding_dimension": self.embedding_dimension,
|
| 18 |
+
"pretrained": self.pretrained,
|
| 19 |
+
}
|
| 20 |
+
with open(os.path.join(save_directory, "config.json"), "w") as f:
|
| 21 |
+
json.dump(config, f, indent=2)
|
| 22 |
+
|
| 23 |
+
# Save weights
|
| 24 |
+
state_dict = self.state_dict()
|
| 25 |
+
if safe_serialization:
|
| 26 |
+
safe_save(state_dict, os.path.join(save_directory, "model.safetensors"))
|
| 27 |
+
else:
|
| 28 |
+
torch.save(state_dict, os.path.join(save_directory, "pytorch_model.bin"))
|
| 29 |
+
|
| 30 |
+
@classmethod
|
| 31 |
+
def from_pretrained(cls, load_directory, safe_serialization=True):
|
| 32 |
+
# Load config
|
| 33 |
+
with open(os.path.join(load_directory, "config.json"), "r") as f:
|
| 34 |
+
config = json.load(f)
|
| 35 |
+
model = cls(**{k:config[k] for k in config if k in cls.__init__.__code__.co_varnames})
|
| 36 |
+
# Load weights
|
| 37 |
+
if safe_serialization:
|
| 38 |
+
state_dict = safe_load(os.path.join(load_directory, "model.safetensors"))
|
| 39 |
+
else:
|
| 40 |
+
state_dict = torch.load(os.path.join(load_directory, "pytorch_model.bin"), map_location="cpu")
|
| 41 |
+
model.load_state_dict(state_dict)
|
| 42 |
+
return model
|
| 43 |
+
|
| 44 |
+
class Resnet18Triplet(nn.Module):
|
| 45 |
+
"""Constructs a ResNet-18 model for FaceNet training using triplet loss.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
embedding_dimension (int): Required dimension of the resulting embedding layer that is outputted by the model.
|
| 49 |
+
using triplet loss. Defaults to 512.
|
| 50 |
+
pretrained (bool): If True, returns a model pre-trained on the ImageNet dataset from a PyTorch repository.
|
| 51 |
+
Defaults to False.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(self, embedding_dimension=512, pretrained=False):
|
| 55 |
+
super(Resnet18Triplet, self).__init__()
|
| 56 |
+
self.model = resnet18(pretrained=pretrained)
|
| 57 |
+
|
| 58 |
+
# Output embedding
|
| 59 |
+
input_features_fc_layer = self.model.fc.in_features
|
| 60 |
+
self.model.fc = nn.Linear(input_features_fc_layer, embedding_dimension, bias=False)
|
| 61 |
+
|
| 62 |
+
def forward(self, images):
|
| 63 |
+
"""Forward pass to output the embedding vector (feature vector) after l2-normalization."""
|
| 64 |
+
embedding = self.model(images)
|
| 65 |
+
# From: https://github.com/timesler/facenet-pytorch/blob/master/models/inception_resnet_v1.py#L301
|
| 66 |
+
embedding = F.normalize(embedding, p=2, dim=1)
|
| 67 |
+
|
| 68 |
+
return embedding
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class Resnet34Triplet(nn.Module):
|
| 72 |
+
"""Constructs a ResNet-34 model for FaceNet training using triplet loss.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
embedding_dimension (int): Required dimension of the resulting embedding layer that is outputted by the model.
|
| 76 |
+
using triplet loss. Defaults to 512.
|
| 77 |
+
pretrained (bool): If True, returns a model pre-trained on the ImageNet dataset from a PyTorch repository.
|
| 78 |
+
Defaults to False.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
def __init__(self, embedding_dimension=512, pretrained=False):
|
| 82 |
+
super(Resnet34Triplet, self).__init__()
|
| 83 |
+
self.model = resnet34(pretrained=pretrained)
|
| 84 |
+
|
| 85 |
+
# Output embedding
|
| 86 |
+
input_features_fc_layer = self.model.fc.in_features
|
| 87 |
+
self.model.fc = nn.Linear(input_features_fc_layer, embedding_dimension, bias=False)
|
| 88 |
+
|
| 89 |
+
def forward(self, images):
|
| 90 |
+
"""Forward pass to output the embedding vector (feature vector) after l2-normalization."""
|
| 91 |
+
embedding = self.model(images)
|
| 92 |
+
# From: https://github.com/timesler/facenet-pytorch/blob/master/models/inception_resnet_v1.py#L301
|
| 93 |
+
embedding = F.normalize(embedding, p=2, dim=1)
|
| 94 |
+
|
| 95 |
+
return embedding
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class Resnet50Triplet(nn.Module):
|
| 99 |
+
"""Constructs a ResNet-50 model for FaceNet training using triplet loss.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
embedding_dimension (int): Required dimension of the resulting embedding layer that is outputted by the model.
|
| 103 |
+
using triplet loss. Defaults to 512.
|
| 104 |
+
pretrained (bool): If True, returns a model pre-trained on the ImageNet dataset from a PyTorch repository.
|
| 105 |
+
Defaults to False.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
def __init__(self, embedding_dimension=512, pretrained=False):
|
| 109 |
+
super(Resnet50Triplet, self).__init__()
|
| 110 |
+
self.model = resnet50(pretrained=pretrained)
|
| 111 |
+
|
| 112 |
+
# Output embedding
|
| 113 |
+
input_features_fc_layer = self.model.fc.in_features
|
| 114 |
+
self.model.fc = nn.Linear(input_features_fc_layer, embedding_dimension, bias=False)
|
| 115 |
+
|
| 116 |
+
def forward(self, images):
|
| 117 |
+
"""Forward pass to output the embedding vector (feature vector) after l2-normalization."""
|
| 118 |
+
embedding = self.model(images)
|
| 119 |
+
# From: https://github.com/timesler/facenet-pytorch/blob/master/models/inception_resnet_v1.py#L301
|
| 120 |
+
embedding = F.normalize(embedding, p=2, dim=1)
|
| 121 |
+
|
| 122 |
+
return embedding
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class Resnet101Triplet(nn.Module):
|
| 126 |
+
"""Constructs a ResNet-101 model for FaceNet training using triplet loss.
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
embedding_dimension (int): Required dimension of the resulting embedding layer that is outputted by the model.
|
| 130 |
+
using triplet loss. Defaults to 512.
|
| 131 |
+
pretrained (bool): If True, returns a model pre-trained on the ImageNet dataset from a PyTorch repository.
|
| 132 |
+
Defaults to False.
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
def __init__(self, embedding_dimension=512, pretrained=False):
|
| 136 |
+
super(Resnet101Triplet, self).__init__()
|
| 137 |
+
self.model = resnet101(pretrained=pretrained)
|
| 138 |
+
|
| 139 |
+
# Output embedding
|
| 140 |
+
input_features_fc_layer = self.model.fc.in_features
|
| 141 |
+
self.model.fc = nn.Linear(input_features_fc_layer, embedding_dimension, bias=False)
|
| 142 |
+
|
| 143 |
+
def forward(self, images):
|
| 144 |
+
"""Forward pass to output the embedding vector (feature vector) after l2-normalization."""
|
| 145 |
+
embedding = self.model(images)
|
| 146 |
+
# From: https://github.com/timesler/facenet-pytorch/blob/master/models/inception_resnet_v1.py#L301
|
| 147 |
+
embedding = F.normalize(embedding, p=2, dim=1)
|
| 148 |
+
|
| 149 |
+
return embedding
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class Resnet152Triplet(nn.Module):
|
| 153 |
+
"""Constructs a ResNet-152 model for FaceNet training using triplet loss.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
embedding_dimension (int): Required dimension of the resulting embedding layer that is outputted by the model.
|
| 157 |
+
using triplet loss. Defaults to 512.
|
| 158 |
+
pretrained (bool): If True, returns a model pre-trained on the ImageNet dataset from a PyTorch repository.
|
| 159 |
+
Defaults to False.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
def __init__(self, embedding_dimension=512, pretrained=False):
|
| 163 |
+
super(Resnet152Triplet, self).__init__()
|
| 164 |
+
self.model = resnet152(pretrained=pretrained)
|
| 165 |
+
|
| 166 |
+
# Output embedding
|
| 167 |
+
input_features_fc_layer = self.model.fc.in_features
|
| 168 |
+
self.model.fc = nn.Linear(input_features_fc_layer, embedding_dimension, bias=False)
|
| 169 |
+
|
| 170 |
+
def forward(self, images):
|
| 171 |
+
"""Forward pass to output the embedding vector (feature vector) after l2-normalization."""
|
| 172 |
+
embedding = self.model(images)
|
| 173 |
+
# From: https://github.com/timesler/facenet-pytorch/blob/master/models/inception_resnet_v1.py#L301
|
| 174 |
+
embedding = F.normalize(embedding, p=2, dim=1)
|
| 175 |
+
|
| 176 |
+
return embedding
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class Resnet34NdTriplet(nn.Module):
|
| 180 |
+
"""Constructs a ResNet-34 model for FaceNet training using triplet loss.
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
embedding_dimension (int): Required dimension of the resulting embedding layer that is outputted by the model.
|
| 184 |
+
using triplet loss. Defaults to 512.
|
| 185 |
+
pretrained (bool): If True, returns a model pre-trained on the ImageNet dataset from a PyTorch repository.
|
| 186 |
+
Defaults to False.
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
def __init__(self, embedding_dimension=512, pretrained=False):
|
| 190 |
+
super(Resnet34NdTriplet, self).__init__()
|
| 191 |
+
# self.model = resnet34nd(pretrained=False)
|
| 192 |
+
self.model = resnet34(pretrained=pretrained)
|
| 193 |
+
|
| 194 |
+
# Output embedding
|
| 195 |
+
input_features_fc_layer = self.model.fc.in_features
|
| 196 |
+
self.model.fc = ReshapedNdLinear(
|
| 197 |
+
NdLinear((input_features_fc_layer, 1),
|
| 198 |
+
(embedding_dimension, 1),
|
| 199 |
+
bias=False)
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
def forward(self, images):
|
| 203 |
+
"""Forward pass to output the embedding vector (feature vector) after l2-normalization."""
|
| 204 |
+
embedding = self.model(images)
|
| 205 |
+
# From: https://github.com/timesler/facenet-pytorch/blob/master/models/inception_resnet_v1.py#L301
|
| 206 |
+
embedding = F.normalize(embedding, p=2, dim=1)
|
| 207 |
+
|
| 208 |
+
return embedding
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class Resnet50NdTriplet(PretrainedTripletModel):
|
| 212 |
+
def __init__(self, embedding_dimension=512, pretrained=False):
|
| 213 |
+
super().__init__()
|
| 214 |
+
self.embedding_dimension = embedding_dimension
|
| 215 |
+
self.pretrained = pretrained
|
| 216 |
+
self.model = resnet50(pretrained=pretrained)
|
| 217 |
+
input_features_fc_layer = self.model.fc.in_features
|
| 218 |
+
self.model.fc = ReshapedNdLinear(
|
| 219 |
+
NdLinear((input_features_fc_layer, 1), (embedding_dimension // 16, 16), bias=False)
|
| 220 |
+
)
|
| 221 |
+
def forward(self, images):
|
| 222 |
+
"""Forward pass to output the embedding vector (feature vector) after l2-normalization."""
|
| 223 |
+
embedding = self.model(images)
|
| 224 |
+
# From: https://github.com/timesler/facenet-pytorch/blob/master/models/inception_resnet_v1.py#L301
|
| 225 |
+
embedding = F.normalize(embedding, p=2, dim=1)
|
| 226 |
+
|
| 227 |
+
return embedding
|
models/utils_resnet.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This code was imported from the official PyTorch Torchvision GitHub repository for the purposes doing experiments
|
| 2 |
+
with fine-tuned resnet architectures:
|
| 3 |
+
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
from ndlinear import NdLinear
|
| 9 |
+
from .ndlinear_util import ReshapedNdLinear
|
| 10 |
+
|
| 11 |
+
# Replaced 'from .utils import load_state_dict_from_url' with the following:
|
| 12 |
+
try:
|
| 13 |
+
from torch.hub import load_state_dict_from_url
|
| 14 |
+
except ImportError:
|
| 15 |
+
from torch.utils.model_zoo import load_url as load_state_dict_from_url
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet34nd', 'resnet50', 'resnet50nd',
|
| 19 |
+
'resnet101', 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
|
| 20 |
+
'wide_resnet50_2', 'wide_resnet101_2']
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
model_urls = {
|
| 24 |
+
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
|
| 25 |
+
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
|
| 26 |
+
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
|
| 27 |
+
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
|
| 28 |
+
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
|
| 29 |
+
'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
|
| 30 |
+
'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
|
| 31 |
+
'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
|
| 32 |
+
'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
|
| 37 |
+
"""3x3 convolution with padding"""
|
| 38 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
|
| 39 |
+
padding=dilation, groups=groups, bias=False, dilation=dilation)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def conv1x1(in_planes, out_planes, stride=1):
|
| 43 |
+
"""1x1 convolution"""
|
| 44 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class BasicBlock(nn.Module):
|
| 48 |
+
expansion = 1
|
| 49 |
+
|
| 50 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
|
| 51 |
+
base_width=64, dilation=1, norm_layer=None):
|
| 52 |
+
super(BasicBlock, self).__init__()
|
| 53 |
+
if norm_layer is None:
|
| 54 |
+
norm_layer = nn.BatchNorm2d
|
| 55 |
+
if groups != 1 or base_width != 64:
|
| 56 |
+
raise ValueError('BasicBlock only supports groups=1 and base_width=64')
|
| 57 |
+
if dilation > 1:
|
| 58 |
+
raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
|
| 59 |
+
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
|
| 60 |
+
self.conv1 = conv3x3(inplanes, planes, stride)
|
| 61 |
+
self.bn1 = norm_layer(planes)
|
| 62 |
+
self.relu = nn.ReLU(inplace=True)
|
| 63 |
+
self.conv2 = conv3x3(planes, planes)
|
| 64 |
+
self.bn2 = norm_layer(planes)
|
| 65 |
+
self.downsample = downsample
|
| 66 |
+
self.stride = stride
|
| 67 |
+
|
| 68 |
+
def forward(self, x):
|
| 69 |
+
identity = x
|
| 70 |
+
|
| 71 |
+
out = self.conv1(x)
|
| 72 |
+
out = self.bn1(out)
|
| 73 |
+
out = self.relu(out)
|
| 74 |
+
|
| 75 |
+
out = self.conv2(out)
|
| 76 |
+
out = self.bn2(out)
|
| 77 |
+
|
| 78 |
+
if self.downsample is not None:
|
| 79 |
+
identity = self.downsample(x)
|
| 80 |
+
|
| 81 |
+
out += identity
|
| 82 |
+
out = self.relu(out)
|
| 83 |
+
|
| 84 |
+
return out
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class Bottleneck(nn.Module):
|
| 88 |
+
# Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
|
| 89 |
+
# while original implementation places the stride at the first 1x1 convolution(self.conv1)
|
| 90 |
+
# according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
|
| 91 |
+
# This variant is also known as ResNet V1.5 and improves accuracy according to
|
| 92 |
+
# https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.
|
| 93 |
+
|
| 94 |
+
expansion = 4
|
| 95 |
+
|
| 96 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
|
| 97 |
+
base_width=64, dilation=1, norm_layer=None):
|
| 98 |
+
super(Bottleneck, self).__init__()
|
| 99 |
+
if norm_layer is None:
|
| 100 |
+
norm_layer = nn.BatchNorm2d
|
| 101 |
+
width = int(planes * (base_width / 64.)) * groups
|
| 102 |
+
# Both self.conv2 and self.downsample layers downsample the input when stride != 1
|
| 103 |
+
self.conv1 = conv1x1(inplanes, width)
|
| 104 |
+
self.bn1 = norm_layer(width)
|
| 105 |
+
self.conv2 = conv3x3(width, width, stride, groups, dilation)
|
| 106 |
+
self.bn2 = norm_layer(width)
|
| 107 |
+
self.conv3 = conv1x1(width, planes * self.expansion)
|
| 108 |
+
self.bn3 = norm_layer(planes * self.expansion)
|
| 109 |
+
self.relu = nn.ReLU(inplace=True)
|
| 110 |
+
self.downsample = downsample
|
| 111 |
+
self.stride = stride
|
| 112 |
+
|
| 113 |
+
def forward(self, x):
|
| 114 |
+
identity = x
|
| 115 |
+
|
| 116 |
+
out = self.conv1(x)
|
| 117 |
+
out = self.bn1(out)
|
| 118 |
+
out = self.relu(out)
|
| 119 |
+
|
| 120 |
+
out = self.conv2(out)
|
| 121 |
+
out = self.bn2(out)
|
| 122 |
+
out = self.relu(out)
|
| 123 |
+
|
| 124 |
+
out = self.conv3(out)
|
| 125 |
+
out = self.bn3(out)
|
| 126 |
+
|
| 127 |
+
if self.downsample is not None:
|
| 128 |
+
identity = self.downsample(x)
|
| 129 |
+
|
| 130 |
+
out += identity
|
| 131 |
+
out = self.relu(out)
|
| 132 |
+
|
| 133 |
+
return out
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class ResNet(nn.Module):
|
| 137 |
+
|
| 138 |
+
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
|
| 139 |
+
groups=1, width_per_group=64, replace_stride_with_dilation=None,
|
| 140 |
+
norm_layer=None):
|
| 141 |
+
super(ResNet, self).__init__()
|
| 142 |
+
if norm_layer is None:
|
| 143 |
+
norm_layer = nn.BatchNorm2d
|
| 144 |
+
self._norm_layer = norm_layer
|
| 145 |
+
|
| 146 |
+
self.inplanes = 64
|
| 147 |
+
self.dilation = 1
|
| 148 |
+
if replace_stride_with_dilation is None:
|
| 149 |
+
# each element in the tuple indicates if we should replace
|
| 150 |
+
# the 2x2 stride with a dilated convolution instead
|
| 151 |
+
replace_stride_with_dilation = [False, False, False]
|
| 152 |
+
if len(replace_stride_with_dilation) != 3:
|
| 153 |
+
raise ValueError("replace_stride_with_dilation should be None "
|
| 154 |
+
"or a 3-element tuple, got {}".format(replace_stride_with_dilation))
|
| 155 |
+
self.groups = groups
|
| 156 |
+
self.base_width = width_per_group
|
| 157 |
+
self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
|
| 158 |
+
bias=False)
|
| 159 |
+
self.bn1 = norm_layer(self.inplanes)
|
| 160 |
+
self.relu = nn.ReLU(inplace=True)
|
| 161 |
+
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
|
| 162 |
+
self.layer1 = self._make_layer(block, 64, layers[0])
|
| 163 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
|
| 164 |
+
dilate=replace_stride_with_dilation[0])
|
| 165 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
|
| 166 |
+
dilate=replace_stride_with_dilation[1])
|
| 167 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
|
| 168 |
+
dilate=replace_stride_with_dilation[2])
|
| 169 |
+
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
|
| 170 |
+
self.fc = nn.Linear(512 * block.expansion, num_classes)
|
| 171 |
+
|
| 172 |
+
for m in self.modules():
|
| 173 |
+
if isinstance(m, nn.Conv2d):
|
| 174 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 175 |
+
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
|
| 176 |
+
nn.init.constant_(m.weight, 1)
|
| 177 |
+
nn.init.constant_(m.bias, 0)
|
| 178 |
+
|
| 179 |
+
# Zero-initialize the last BN in each residual branch,
|
| 180 |
+
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
|
| 181 |
+
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
|
| 182 |
+
if zero_init_residual:
|
| 183 |
+
for m in self.modules():
|
| 184 |
+
if isinstance(m, Bottleneck):
|
| 185 |
+
nn.init.constant_(m.bn3.weight, 0)
|
| 186 |
+
elif isinstance(m, BasicBlock):
|
| 187 |
+
nn.init.constant_(m.bn2.weight, 0)
|
| 188 |
+
|
| 189 |
+
def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
|
| 190 |
+
norm_layer = self._norm_layer
|
| 191 |
+
downsample = None
|
| 192 |
+
previous_dilation = self.dilation
|
| 193 |
+
if dilate:
|
| 194 |
+
self.dilation *= stride
|
| 195 |
+
stride = 1
|
| 196 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
| 197 |
+
downsample = nn.Sequential(
|
| 198 |
+
conv1x1(self.inplanes, planes * block.expansion, stride),
|
| 199 |
+
norm_layer(planes * block.expansion),
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
layers = []
|
| 203 |
+
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
|
| 204 |
+
self.base_width, previous_dilation, norm_layer))
|
| 205 |
+
self.inplanes = planes * block.expansion
|
| 206 |
+
for _ in range(1, blocks):
|
| 207 |
+
layers.append(block(self.inplanes, planes, groups=self.groups,
|
| 208 |
+
base_width=self.base_width, dilation=self.dilation,
|
| 209 |
+
norm_layer=norm_layer))
|
| 210 |
+
|
| 211 |
+
return nn.Sequential(*layers)
|
| 212 |
+
|
| 213 |
+
def _forward_impl(self, x):
|
| 214 |
+
# See note [TorchScript super()]
|
| 215 |
+
x = self.conv1(x)
|
| 216 |
+
x = self.bn1(x)
|
| 217 |
+
x = self.relu(x)
|
| 218 |
+
x = self.maxpool(x)
|
| 219 |
+
|
| 220 |
+
x = self.layer1(x)
|
| 221 |
+
x = self.layer2(x)
|
| 222 |
+
x = self.layer3(x)
|
| 223 |
+
x = self.layer4(x)
|
| 224 |
+
|
| 225 |
+
x = self.avgpool(x)
|
| 226 |
+
x = torch.flatten(x, 1)
|
| 227 |
+
x = self.fc(x)
|
| 228 |
+
|
| 229 |
+
return x
|
| 230 |
+
|
| 231 |
+
def forward(self, x):
|
| 232 |
+
return self._forward_impl(x)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _resnet(arch, block, layers, pretrained, progress, **kwargs):
|
| 236 |
+
model = ResNet(block, layers, **kwargs)
|
| 237 |
+
if pretrained:
|
| 238 |
+
state_dict = load_state_dict_from_url(model_urls[arch],
|
| 239 |
+
progress=progress)
|
| 240 |
+
model.load_state_dict(state_dict)
|
| 241 |
+
return model
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def resnet18(pretrained=False, progress=True, **kwargs):
|
| 245 |
+
r"""ResNet-18 model from
|
| 246 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 247 |
+
Args:
|
| 248 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 249 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 250 |
+
"""
|
| 251 |
+
return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
|
| 252 |
+
**kwargs)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def resnet34(pretrained=False, progress=True, **kwargs):
|
| 256 |
+
r"""ResNet-34 model from
|
| 257 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 258 |
+
Args:
|
| 259 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 260 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 261 |
+
"""
|
| 262 |
+
return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
|
| 263 |
+
**kwargs)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def resnet50(pretrained=False, progress=True, **kwargs):
|
| 267 |
+
r"""ResNet-50 model from
|
| 268 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 269 |
+
Args:
|
| 270 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 271 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 272 |
+
"""
|
| 273 |
+
return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
|
| 274 |
+
**kwargs)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def resnet101(pretrained=False, progress=True, **kwargs):
|
| 278 |
+
r"""ResNet-101 model from
|
| 279 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 280 |
+
Args:
|
| 281 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 282 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 283 |
+
"""
|
| 284 |
+
return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,
|
| 285 |
+
**kwargs)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def resnet152(pretrained=False, progress=True, **kwargs):
|
| 289 |
+
r"""ResNet-152 model from
|
| 290 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 291 |
+
Args:
|
| 292 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 293 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 294 |
+
"""
|
| 295 |
+
return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,
|
| 296 |
+
**kwargs)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
|
| 300 |
+
r"""ResNeXt-50 32x4d model from
|
| 301 |
+
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
|
| 302 |
+
Args:
|
| 303 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 304 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 305 |
+
"""
|
| 306 |
+
kwargs['groups'] = 32
|
| 307 |
+
kwargs['width_per_group'] = 4
|
| 308 |
+
return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],
|
| 309 |
+
pretrained, progress, **kwargs)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
|
| 313 |
+
r"""ResNeXt-101 32x8d model from
|
| 314 |
+
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
|
| 315 |
+
Args:
|
| 316 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 317 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 318 |
+
"""
|
| 319 |
+
kwargs['groups'] = 32
|
| 320 |
+
kwargs['width_per_group'] = 8
|
| 321 |
+
return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],
|
| 322 |
+
pretrained, progress, **kwargs)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def wide_resnet50_2(pretrained=False, progress=True, **kwargs):
|
| 326 |
+
r"""Wide ResNet-50-2 model from
|
| 327 |
+
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
|
| 328 |
+
The model is the same as ResNet except for the bottleneck number of channels
|
| 329 |
+
which is twice larger in every block. The number of channels in outer 1x1
|
| 330 |
+
convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
|
| 331 |
+
channels, and in Wide ResNet-50-2 has 2048-1024-2048.
|
| 332 |
+
Args:
|
| 333 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 334 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 335 |
+
"""
|
| 336 |
+
kwargs['width_per_group'] = 64 * 2
|
| 337 |
+
return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],
|
| 338 |
+
pretrained, progress, **kwargs)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def wide_resnet101_2(pretrained=False, progress=True, **kwargs):
|
| 342 |
+
r"""Wide ResNet-101-2 model from
|
| 343 |
+
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
|
| 344 |
+
The model is the same as ResNet except for the bottleneck number of channels
|
| 345 |
+
which is twice larger in every block. The number of channels in outer 1x1
|
| 346 |
+
convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
|
| 347 |
+
channels, and in Wide ResNet-50-2 has 2048-1024-2048.
|
| 348 |
+
Args:
|
| 349 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 350 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 351 |
+
"""
|
| 352 |
+
kwargs['width_per_group'] = 64 * 2
|
| 353 |
+
return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3],
|
| 354 |
+
pretrained, progress, **kwargs)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def resnet34nd(pretrained=False, progress=True, **kwargs):
|
| 358 |
+
r"""ResNet-34 model from
|
| 359 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 360 |
+
Args:
|
| 361 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 362 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 363 |
+
"""
|
| 364 |
+
_resnet34 = _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, **kwargs)
|
| 365 |
+
input_dim = _resnet34.fc.in_features
|
| 366 |
+
output_dim = _resnet34.fc.out_features
|
| 367 |
+
_resnet34.fc = ReshapedNdLinear(NdLinear((input_dim, 1), (output_dim // 16, 16)))
|
| 368 |
+
return _resnet34
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def resnet50nd(pretrained=False, progress=True, **kwargs):
|
| 372 |
+
r"""ResNet-50 model from
|
| 373 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 374 |
+
Args:
|
| 375 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 376 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 377 |
+
"""
|
| 378 |
+
_resnet50 = _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs)
|
| 379 |
+
input_dim = _resnet50.fc.in_features
|
| 380 |
+
output_dim = _resnet50.fc.out_features
|
| 381 |
+
_resnet50.fc = ReshapedNdLinear(NdLinear((input_dim, 1), (output_dim // 16, 16)))
|
| 382 |
+
return _resnet50
|
ndlinear.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.optim as optim
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class NdLinear(nn.Module):
|
| 8 |
+
def __init__(self, input_dims: tuple, hidden_size: tuple, transform_outer=True, bias=True):
|
| 9 |
+
"""
|
| 10 |
+
NdLinear: A PyTorch layer for projecting tensors into multi-space representations.
|
| 11 |
+
|
| 12 |
+
Unlike conventional embedding layers that map into a single vector space, NdLinear
|
| 13 |
+
transforms tensors across a collection of vector spaces, capturing multivariate structure
|
| 14 |
+
and topical information that standard deep learning architectures typically lose.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
input_dims (tuple): Shape of input tensor (excluding batch dimension).
|
| 18 |
+
hidden_size (tuple): Target hidden dimensions after transformation.
|
| 19 |
+
"""
|
| 20 |
+
super(NdLinear, self).__init__()
|
| 21 |
+
|
| 22 |
+
if len(input_dims) != len(hidden_size):
|
| 23 |
+
raise Exception("Input shape and hidden shape do not match.")
|
| 24 |
+
|
| 25 |
+
self.input_dims = input_dims
|
| 26 |
+
self.hidden_size = hidden_size
|
| 27 |
+
self.num_layers = len(input_dims) # Must match since dims are equal
|
| 28 |
+
# self.relu = nn.ReLU()
|
| 29 |
+
self.transform_outer = transform_outer
|
| 30 |
+
|
| 31 |
+
# Define transformation layers per dimension
|
| 32 |
+
self.align_layers = nn.ModuleList([
|
| 33 |
+
nn.Linear(input_dims[i], hidden_size[i], bias=bias) for i in range(self.num_layers)
|
| 34 |
+
])
|
| 35 |
+
|
| 36 |
+
def forward(self, X):
|
| 37 |
+
"""
|
| 38 |
+
Forward pass to project input tensor into a new multi-space representation.
|
| 39 |
+
- Incrementally transposes, flattens, applies linear layers, and restores shape.
|
| 40 |
+
|
| 41 |
+
Expected Input Shape: [batch_size, *input_dims]
|
| 42 |
+
Output Shape: [batch_size, *hidden_size]
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
X (torch.Tensor): Input tensor with shape [batch_size, *input_dims]
|
| 46 |
+
|
| 47 |
+
Returns:
|
| 48 |
+
torch.Tensor: Output tensor with shape [batch_size, *hidden_size]
|
| 49 |
+
"""
|
| 50 |
+
num_transforms = self.num_layers # Number of transformations
|
| 51 |
+
|
| 52 |
+
# Define iteration order
|
| 53 |
+
# transform_indices = range(num_transforms) if transform_outer else reversed(range(num_transforms))
|
| 54 |
+
|
| 55 |
+
for i in range(num_transforms):
|
| 56 |
+
if self.transform_outer:
|
| 57 |
+
layer = self.align_layers[i]
|
| 58 |
+
transpose_dim = i + 1
|
| 59 |
+
else:
|
| 60 |
+
layer = self.align_layers[num_transforms - (i+1)]
|
| 61 |
+
transpose_dim = num_transforms - i
|
| 62 |
+
|
| 63 |
+
# Transpose the selected dimension to the last position
|
| 64 |
+
X = torch.transpose(X, transpose_dim, num_transforms).contiguous()
|
| 65 |
+
|
| 66 |
+
# Store original shape before transformation
|
| 67 |
+
X_size = X.shape[:-1]
|
| 68 |
+
|
| 69 |
+
# Flatten everything except the last dimension
|
| 70 |
+
X = X.view(-1, X.shape[-1])
|
| 71 |
+
|
| 72 |
+
# Apply transformation
|
| 73 |
+
X = layer(X)
|
| 74 |
+
|
| 75 |
+
# Reshape back to the original spatial structure (with new embedding dim)
|
| 76 |
+
X = X.view(*X_size, X.shape[-1])
|
| 77 |
+
|
| 78 |
+
# Transpose the dimension back to its original position
|
| 79 |
+
X = torch.transpose(X, transpose_dim, num_transforms).contiguous()
|
| 80 |
+
|
| 81 |
+
return X
|
| 82 |
+
|