You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

149 lines
5.8 KiB

import torch
import torch.nn as nn
import torch.nn.functional as F
import math
# --------------------------------------------------------
# Basic Blocks (Quantization Friendly: ReLU used)
# --------------------------------------------------------
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
# Kernel size restricted to 1 and 3 for board compatibility
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
# self.relu = nn.ReLU(inplace=True) # PReLU -> ReLU
self.relu = nn.ReLU(inplace=False) # PReLU -> ReLU
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
# --------------------------------------------------------
# Backbone: Modified ResNet-50
# --------------------------------------------------------
class ResNetFace(nn.Module):
def __init__(self, block, layers, embedding_size=128):
super(ResNetFace, self).__init__()
self.inplanes = 64
# Stem Block: 7x7 replaced by three 3x3 convs
self.stem = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(64),
# nn.ReLU(inplace=True),
nn.ReLU(inplace=False),
nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(64),
# nn.ReLU(inplace=True),
nn.ReLU(inplace=False),
nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(64),
# nn.ReLU(inplace=True),
nn.ReLU(inplace=False),
)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
# Output Head: 128x128 Input -> 4x4 Feature Map
self.avgpool = nn.AvgPool2d(4) # Result: 1x1
# FC layer replaced by 1x1 Conv for 128-d embedding
self.fc_conv = nn.Conv2d(512 * block.expansion, embedding_size, kernel_size=1, bias=False)
self.bn_last = nn.BatchNorm2d(embedding_size)
# Init weights
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for _ in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
x = self.stem(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = self.fc_conv(x)
x = self.bn_last(x) # Output: [N, 128, 1, 1]
return x
# --------------------------------------------------------
# ArcFace Loss Header
# --------------------------------------------------------
class ArcFace(nn.Module):
def __init__(self, in_features, out_features, s=64.0, m=0.50):
super(ArcFace, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.s = s
self.m = m
self.weight = nn.Parameter(torch.FloatTensor(out_features, in_features))
nn.init.xavier_uniform_(self.weight)
def forward(self, input, label):
# Flatten [N, 128, 1, 1] -> [N, 128] for loss calculation
embedding = input.view(input.size(0), -1)
cosine = F.linear(F.normalize(embedding), F.normalize(self.weight))
# Stable implementation of ArcFace
theta = torch.acos(torch.clamp(cosine, -1.0 + 1e-7, 1.0 - 1e-7))
target_logits = torch.cos(theta + self.m)
one_hot = torch.zeros_like(cosine)
one_hot.scatter_(1, label.view(-1, 1).long(), 1)
output = one_hot * target_logits + (1.0 - one_hot) * cosine
output *= self.s
return output
def get_face_model():
return ResNetFace(Bottleneck, [3, 4, 6, 3], embedding_size=128)