CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ai-forever

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: ai-forever/sber-swap
Path: blob/main/models/models.py
Views: 792
1
import math
2
import torch
3
import torch.nn.functional as F
4
from torch import nn
5
from torch.nn import Parameter
6
from .config import device, num_classes
7
8
9
def create_model(opt):
10
if opt.model == 'pix2pixHD':
11
#from .pix2pixHD_model import Pix2PixHDModel, InferenceModel
12
from .fs_model import fsModel
13
model = fsModel()
14
else:
15
from .ui_model import UIModel
16
model = UIModel()
17
18
model.initialize(opt)
19
if opt.verbose:
20
print("model [%s] was created" % (model.name()))
21
22
if opt.isTrain and len(opt.gpu_ids) and not opt.fp16:
23
model = torch.nn.DataParallel(model, device_ids=opt.gpu_ids)
24
25
return model
26
27
28
29
class SEBlock(nn.Module):
30
def __init__(self, channel, reduction=16):
31
super(SEBlock, self).__init__()
32
self.avg_pool = nn.AdaptiveAvgPool2d(1)
33
self.fc = nn.Sequential(
34
nn.Linear(channel, channel // reduction),
35
nn.PReLU(),
36
nn.Linear(channel // reduction, channel),
37
nn.Sigmoid()
38
)
39
40
def forward(self, x):
41
b, c, _, _ = x.size()
42
y = self.avg_pool(x).view(b, c)
43
y = self.fc(y).view(b, c, 1, 1)
44
return x * y
45
46
47
class IRBlock(nn.Module):
48
expansion = 1
49
50
def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True):
51
super(IRBlock, self).__init__()
52
self.bn0 = nn.BatchNorm2d(inplanes)
53
self.conv1 = conv3x3(inplanes, inplanes)
54
self.bn1 = nn.BatchNorm2d(inplanes)
55
self.prelu = nn.PReLU()
56
self.conv2 = conv3x3(inplanes, planes, stride)
57
self.bn2 = nn.BatchNorm2d(planes)
58
self.downsample = downsample
59
self.stride = stride
60
self.use_se = use_se
61
if self.use_se:
62
self.se = SEBlock(planes)
63
64
def forward(self, x):
65
residual = x
66
out = self.bn0(x)
67
out = self.conv1(out)
68
out = self.bn1(out)
69
out = self.prelu(out)
70
71
out = self.conv2(out)
72
out = self.bn2(out)
73
if self.use_se:
74
out = self.se(out)
75
76
if self.downsample is not None:
77
residual = self.downsample(x)
78
79
out += residual
80
out = self.prelu(out)
81
82
return out
83
84
85
class ResNet(nn.Module):
86
87
def __init__(self, block, layers, use_se=True):
88
self.inplanes = 64
89
self.use_se = use_se
90
super(ResNet, self).__init__()
91
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, bias=False)
92
self.bn1 = nn.BatchNorm2d(64)
93
self.prelu = nn.PReLU()
94
self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
95
self.layer1 = self._make_layer(block, 64, layers[0])
96
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
97
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
98
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
99
self.bn2 = nn.BatchNorm2d(512)
100
self.dropout = nn.Dropout()
101
self.fc = nn.Linear(512 * 7 * 7, 512)
102
self.bn3 = nn.BatchNorm1d(512)
103
104
for m in self.modules():
105
if isinstance(m, nn.Conv2d):
106
nn.init.xavier_normal_(m.weight)
107
elif isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d):
108
nn.init.constant_(m.weight, 1)
109
nn.init.constant_(m.bias, 0)
110
elif isinstance(m, nn.Linear):
111
nn.init.xavier_normal_(m.weight)
112
nn.init.constant_(m.bias, 0)
113
114
def _make_layer(self, block, planes, blocks, stride=1):
115
downsample = None
116
if stride != 1 or self.inplanes != planes * block.expansion:
117
downsample = nn.Sequential(
118
nn.Conv2d(self.inplanes, planes * block.expansion,
119
kernel_size=1, stride=stride, bias=False),
120
nn.BatchNorm2d(planes * block.expansion),
121
)
122
123
layers = []
124
layers.append(block(self.inplanes, planes, stride, downsample, use_se=self.use_se))
125
self.inplanes = planes
126
for i in range(1, blocks):
127
layers.append(block(self.inplanes, planes, use_se=self.use_se))
128
129
return nn.Sequential(*layers)
130
131
def forward(self, x):
132
x = self.conv1(x)
133
x = self.bn1(x)
134
x = self.prelu(x)
135
x = self.maxpool(x)
136
137
x = self.layer1(x)
138
x = self.layer2(x)
139
x = self.layer3(x)
140
x = self.layer4(x)
141
142
x = self.bn2(x)
143
x = self.dropout(x)
144
x = x.view(x.size(0), -1)
145
x = self.fc(x)
146
x = self.bn3(x)
147
148
return x
149
150
151
class ArcMarginModel(nn.Module):
152
def __init__(self, args):
153
super(ArcMarginModel, self).__init__()
154
155
self.weight = Parameter(torch.FloatTensor(num_classes, args.emb_size))
156
nn.init.xavier_uniform_(self.weight)
157
158
self.easy_margin = args.easy_margin
159
self.m = args.margin_m
160
self.s = args.margin_s
161
162
self.cos_m = math.cos(self.m)
163
self.sin_m = math.sin(self.m)
164
self.th = math.cos(math.pi - self.m)
165
self.mm = math.sin(math.pi - self.m) * self.m
166
167
def forward(self, input, label):
168
x = F.normalize(input)
169
W = F.normalize(self.weight)
170
cosine = F.linear(x, W)
171
sine = torch.sqrt(1.0 - torch.pow(cosine, 2))
172
phi = cosine * self.cos_m - sine * self.sin_m # cos(theta + m)
173
if self.easy_margin:
174
phi = torch.where(cosine > 0, phi, cosine)
175
else:
176
phi = torch.where(cosine > self.th, phi, cosine - self.mm)
177
one_hot = torch.zeros(cosine.size(), device=device)
178
one_hot.scatter_(1, label.view(-1, 1).long(), 1)
179
output = (one_hot * phi) + ((1.0 - one_hot) * cosine)
180
output *= self.s
181
return output
182
183