forked from catalyst-team/catalyst
-
Notifications
You must be signed in to change notification settings - Fork 1
/
arcface.py
229 lines (194 loc) · 6.57 KB
/
arcface.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class ArcFace(nn.Module):
"""Implementation of
`ArcFace: Additive Angular Margin Loss for Deep Face Recognition`_.
.. _ArcFace\: Additive Angular Margin Loss for Deep Face Recognition:
https://arxiv.org/abs/1801.07698v1
Args:
in_features: size of each input sample.
out_features: size of each output sample.
s: norm of input feature.
Default: ``64.0``.
m: margin.
Default: ``0.5``.
eps: operation accuracy.
Default: ``1e-6``.
Shape:
- Input: :math:`(batch, H_{in})` where
:math:`H_{in} = in\_features`.
- Output: :math:`(batch, H_{out})` where
:math:`H_{out} = out\_features`.
Example:
>>> layer = ArcFace(5, 10, s=1.31, m=0.5)
>>> loss_fn = nn.CrosEntropyLoss()
>>> embedding = torch.randn(3, 5, requires_grad=True)
>>> target = torch.empty(3, dtype=torch.long).random_(10)
>>> output = layer(embedding, target)
>>> loss = loss_fn(output, target)
>>> loss.backward()
"""
def __init__( # noqa: D107
self,
in_features: int,
out_features: int,
s: float = 64.0,
m: float = 0.5,
eps: float = 1e-6,
):
super(ArcFace, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.s = s
self.m = m
self.threshold = math.pi - m
self.eps = eps
self.weight = nn.Parameter(
torch.FloatTensor(out_features, in_features)
)
nn.init.xavier_uniform_(self.weight)
def __repr__(self) -> str:
"""Object representation."""
rep = (
"ArcFace("
f"in_features={self.in_features},"
f"out_features={self.out_features},"
f"s={self.s},"
f"m={self.m},"
f"eps={self.eps}"
")"
)
return rep
def forward(
self, input: torch.Tensor, target: torch.LongTensor
) -> torch.Tensor:
"""
Args:
input: input features,
expected shapes ``BxF`` where ``B``
is batch dimension and ``F`` is an
input feature dimension.
target: target classes,
expected shapes ``B`` where
``B`` is batch dimension.
Returns:
tensor (logits) with shapes ``BxC``
where ``C`` is a number of classes
(out_features).
"""
cos_theta = F.linear(F.normalize(input), F.normalize(self.weight))
theta = torch.acos(
torch.clamp(cos_theta, -1.0 + self.eps, 1.0 - self.eps)
)
one_hot = torch.zeros_like(cos_theta)
one_hot.scatter_(1, target.view(-1, 1).long(), 1)
mask = torch.where(
theta > self.threshold, torch.zeros_like(one_hot), one_hot
)
logits = torch.cos(torch.where(mask.bool(), theta + self.m, theta))
logits *= self.s
return logits
class SubCenterArcFace(nn.Module):
"""Implementation of
`Sub-center ArcFace: Boosting Face Recognition
by Large-scale Noisy Web Faces`_.
.. _Sub-center ArcFace\: Boosting Face Recognition \
by Large-scale Noisy Web Faces:
https://ibug.doc.ic.ac.uk/media/uploads/documents/eccv_1445.pdf
Args:
in_features: size of each input sample.
out_features: size of each output sample.
s: norm of input feature,
Default: ``64.0``.
m: margin.
Default: ``0.5``.
k: number of possible class centroids.
Default: ``3``.
eps (float, optional): operation accuracy.
Default: ``1e-6``.
Shape:
- Input: :math:`(batch, H_{in})` where
:math:`H_{in} = in\_features`.
- Output: :math:`(batch, H_{out})` where
:math:`H_{out} = out\_features`.
Example:
>>> layer = SubCenterArcFace(5, 10, s=1.31, m=0.35, k=2)
>>> loss_fn = nn.CrosEntropyLoss()
>>> embedding = torch.randn(3, 5, requires_grad=True)
>>> target = torch.empty(3, dtype=torch.long).random_(10)
>>> output = layer(embedding, target)
>>> loss = loss_fn(output, target)
>>> loss.backward()
"""
def __init__( # noqa: D107
self,
in_features: int,
out_features: int,
s: float = 64.0,
m: float = 0.5,
k: int = 3,
eps: float = 1e-6,
):
super(SubCenterArcFace, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.s = s
self.m = m
self.k = k
self.eps = eps
self.weight = nn.Parameter(
torch.FloatTensor(k, in_features, out_features)
)
nn.init.xavier_uniform_(self.weight)
self.threshold = math.pi - self.m
def __repr__(self) -> str:
"""Object representation."""
rep = (
"SubCenterArcFace("
f"in_features={self.in_features},"
f"out_features={self.out_features},"
f"s={self.s},"
f"m={self.m},"
f"k={self.k},"
f"eps={self.eps}"
")"
)
return rep
def forward(
self, input: torch.Tensor, label: torch.LongTensor
) -> torch.Tensor:
"""
Args:
input: input features,
expected shapes ``BxF`` where ``B``
is batch dimension and ``F`` is an
input feature dimension.
label: target classes,
expected shapes ``B`` where
``B`` is batch dimension.
Returns:
tensor (logits) with shapes ``BxC``
where ``C`` is a number of classes.
"""
cos_theta = torch.bmm(
F.normalize(input)
.unsqueeze(0)
.expand(self.k, *input.shape), # k*b*f
F.normalize(
self.weight, dim=1
), # normalize in_features dim # k*f*c
) # k*b*f
cos_theta = torch.max(cos_theta, dim=0)[0] # b*f
theta = torch.acos(
torch.clamp(cos_theta, -1.0 + self.eps, 1.0 - self.eps)
)
one_hot = torch.zeros_like(cos_theta)
one_hot.scatter_(1, label.view(-1, 1).long(), 1)
selected = torch.where(
theta > self.threshold, torch.zeros_like(one_hot), one_hot
)
logits = torch.cos(torch.where(selected.bool(), theta + self.m, theta))
logits *= self.s
return logits