Upload MiewIdNet
Browse files- README.md +199 -0
- config.json +25 -0
- configuration_miewid.py +21 -0
- heads.py +161 -0
- model.safetensors +3 -0
- modeling_miewid.py +159 -0
README.md
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: transformers
|
3 |
+
tags: []
|
4 |
+
---
|
5 |
+
|
6 |
+
# Model Card for Model ID
|
7 |
+
|
8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
9 |
+
|
10 |
+
|
11 |
+
|
12 |
+
## Model Details
|
13 |
+
|
14 |
+
### Model Description
|
15 |
+
|
16 |
+
<!-- Provide a longer summary of what this model is. -->
|
17 |
+
|
18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
19 |
+
|
20 |
+
- **Developed by:** [More Information Needed]
|
21 |
+
- **Funded by [optional]:** [More Information Needed]
|
22 |
+
- **Shared by [optional]:** [More Information Needed]
|
23 |
+
- **Model type:** [More Information Needed]
|
24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
25 |
+
- **License:** [More Information Needed]
|
26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
27 |
+
|
28 |
+
### Model Sources [optional]
|
29 |
+
|
30 |
+
<!-- Provide the basic links for the model. -->
|
31 |
+
|
32 |
+
- **Repository:** [More Information Needed]
|
33 |
+
- **Paper [optional]:** [More Information Needed]
|
34 |
+
- **Demo [optional]:** [More Information Needed]
|
35 |
+
|
36 |
+
## Uses
|
37 |
+
|
38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
39 |
+
|
40 |
+
### Direct Use
|
41 |
+
|
42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
43 |
+
|
44 |
+
[More Information Needed]
|
45 |
+
|
46 |
+
### Downstream Use [optional]
|
47 |
+
|
48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
49 |
+
|
50 |
+
[More Information Needed]
|
51 |
+
|
52 |
+
### Out-of-Scope Use
|
53 |
+
|
54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
55 |
+
|
56 |
+
[More Information Needed]
|
57 |
+
|
58 |
+
## Bias, Risks, and Limitations
|
59 |
+
|
60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
61 |
+
|
62 |
+
[More Information Needed]
|
63 |
+
|
64 |
+
### Recommendations
|
65 |
+
|
66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
67 |
+
|
68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
69 |
+
|
70 |
+
## How to Get Started with the Model
|
71 |
+
|
72 |
+
Use the code below to get started with the model.
|
73 |
+
|
74 |
+
[More Information Needed]
|
75 |
+
|
76 |
+
## Training Details
|
77 |
+
|
78 |
+
### Training Data
|
79 |
+
|
80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
81 |
+
|
82 |
+
[More Information Needed]
|
83 |
+
|
84 |
+
### Training Procedure
|
85 |
+
|
86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
87 |
+
|
88 |
+
#### Preprocessing [optional]
|
89 |
+
|
90 |
+
[More Information Needed]
|
91 |
+
|
92 |
+
|
93 |
+
#### Training Hyperparameters
|
94 |
+
|
95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
96 |
+
|
97 |
+
#### Speeds, Sizes, Times [optional]
|
98 |
+
|
99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
100 |
+
|
101 |
+
[More Information Needed]
|
102 |
+
|
103 |
+
## Evaluation
|
104 |
+
|
105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
106 |
+
|
107 |
+
### Testing Data, Factors & Metrics
|
108 |
+
|
109 |
+
#### Testing Data
|
110 |
+
|
111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
112 |
+
|
113 |
+
[More Information Needed]
|
114 |
+
|
115 |
+
#### Factors
|
116 |
+
|
117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
118 |
+
|
119 |
+
[More Information Needed]
|
120 |
+
|
121 |
+
#### Metrics
|
122 |
+
|
123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
124 |
+
|
125 |
+
[More Information Needed]
|
126 |
+
|
127 |
+
### Results
|
128 |
+
|
129 |
+
[More Information Needed]
|
130 |
+
|
131 |
+
#### Summary
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
## Model Examination [optional]
|
136 |
+
|
137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
138 |
+
|
139 |
+
[More Information Needed]
|
140 |
+
|
141 |
+
## Environmental Impact
|
142 |
+
|
143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
144 |
+
|
145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
146 |
+
|
147 |
+
- **Hardware Type:** [More Information Needed]
|
148 |
+
- **Hours used:** [More Information Needed]
|
149 |
+
- **Cloud Provider:** [More Information Needed]
|
150 |
+
- **Compute Region:** [More Information Needed]
|
151 |
+
- **Carbon Emitted:** [More Information Needed]
|
152 |
+
|
153 |
+
## Technical Specifications [optional]
|
154 |
+
|
155 |
+
### Model Architecture and Objective
|
156 |
+
|
157 |
+
[More Information Needed]
|
158 |
+
|
159 |
+
### Compute Infrastructure
|
160 |
+
|
161 |
+
[More Information Needed]
|
162 |
+
|
163 |
+
#### Hardware
|
164 |
+
|
165 |
+
[More Information Needed]
|
166 |
+
|
167 |
+
#### Software
|
168 |
+
|
169 |
+
[More Information Needed]
|
170 |
+
|
171 |
+
## Citation [optional]
|
172 |
+
|
173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
174 |
+
|
175 |
+
**BibTeX:**
|
176 |
+
|
177 |
+
[More Information Needed]
|
178 |
+
|
179 |
+
**APA:**
|
180 |
+
|
181 |
+
[More Information Needed]
|
182 |
+
|
183 |
+
## Glossary [optional]
|
184 |
+
|
185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
186 |
+
|
187 |
+
[More Information Needed]
|
188 |
+
|
189 |
+
## More Information [optional]
|
190 |
+
|
191 |
+
[More Information Needed]
|
192 |
+
|
193 |
+
## Model Card Authors [optional]
|
194 |
+
|
195 |
+
[More Information Needed]
|
196 |
+
|
197 |
+
## Model Card Contact
|
198 |
+
|
199 |
+
[More Information Needed]
|
config.json
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"MiewIdNet"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_miewid.MiewIdNetConfig",
|
7 |
+
"AutoModel": "modeling_miewid.MiewIdNet"
|
8 |
+
},
|
9 |
+
"dropout": 0.0,
|
10 |
+
"fc_dim": 512,
|
11 |
+
"k": null,
|
12 |
+
"loss_module": "softmax",
|
13 |
+
"ls_eps": 0.0,
|
14 |
+
"margin": 0.5,
|
15 |
+
"margins": null,
|
16 |
+
"model_name": "efficientnetv2_rw_m",
|
17 |
+
"model_type": "miewid",
|
18 |
+
"n_classes": 10,
|
19 |
+
"pretrained": true,
|
20 |
+
"s": 30.0,
|
21 |
+
"theta_zero": 0.785,
|
22 |
+
"torch_dtype": "float32",
|
23 |
+
"transformers_version": "4.41.2",
|
24 |
+
"use_fc": false
|
25 |
+
}
|
configuration_miewid.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig
|
2 |
+
|
3 |
+
|
4 |
+
class MiewIdNetConfig(PretrainedConfig):
|
5 |
+
model_type = "miewid"
|
6 |
+
|
7 |
+
def __init__(self, n_classes=10, model_name='efficientnet_b0', use_fc=False, fc_dim=512, dropout=0.0, loss_module='softmax', s=30.0, margin=0.50, ls_eps=0.0, theta_zero=0.785, pretrained=True, margins=None, k=None, **kwargs):
|
8 |
+
super().__init__(**kwargs)
|
9 |
+
self.n_classes = n_classes
|
10 |
+
self.model_name = model_name
|
11 |
+
self.use_fc = use_fc
|
12 |
+
self.fc_dim = fc_dim
|
13 |
+
self.dropout = dropout
|
14 |
+
self.loss_module = loss_module
|
15 |
+
self.s = s
|
16 |
+
self.margin = margin
|
17 |
+
self.ls_eps = ls_eps
|
18 |
+
self.theta_zero = theta_zero
|
19 |
+
self.pretrained = pretrained
|
20 |
+
self.margins = margins
|
21 |
+
self.k = k
|
heads.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import math
|
4 |
+
import torch.nn.functional as F
|
5 |
+
from torch.nn.parameter import Parameter
|
6 |
+
|
7 |
+
class ArcMarginProduct(nn.Module):
|
8 |
+
r"""Implement of large margin arc distance: :
|
9 |
+
Args:
|
10 |
+
in_features: size of each input sample
|
11 |
+
out_features: size of each output sample
|
12 |
+
s: norm of input feature
|
13 |
+
m: margin
|
14 |
+
cos(theta + m)wandb: ERROR Abnormal program exit
|
15 |
+
|
16 |
+
"""
|
17 |
+
def __init__(self, in_features, out_features, s=30.0, m=0.50, easy_margin=False, ls_eps=0.0):
|
18 |
+
super(ArcMarginProduct, self).__init__()
|
19 |
+
self.in_features = in_features
|
20 |
+
self.out_features = out_features
|
21 |
+
self.s = s
|
22 |
+
self.m = m
|
23 |
+
self.ls_eps = ls_eps # label smoothing
|
24 |
+
self.weight = Parameter(torch.FloatTensor(out_features, in_features))
|
25 |
+
nn.init.xavier_uniform_(self.weight)
|
26 |
+
|
27 |
+
self.easy_margin = easy_margin
|
28 |
+
self.cos_m = math.cos(m)
|
29 |
+
self.sin_m = math.sin(m)
|
30 |
+
self.th = math.cos(math.pi - m)
|
31 |
+
self.mm = math.sin(math.pi - m) * m
|
32 |
+
|
33 |
+
def forward(self, input, label):
|
34 |
+
# --------------------------- cos(theta) & phi(theta) ---------------------------
|
35 |
+
cosine = F.linear(F.normalize(input), F.normalize(self.weight))
|
36 |
+
sine = torch.sqrt(1.0 - torch.pow(cosine, 2))
|
37 |
+
phi = cosine * self.cos_m - sine * self.sin_m
|
38 |
+
if self.easy_margin:
|
39 |
+
phi = torch.where(cosine > 0, phi, cosine)
|
40 |
+
else:
|
41 |
+
phi = torch.where(cosine > self.th, phi, cosine - self.mm)
|
42 |
+
# --------------------------- convert label to one-hot ---------------------------
|
43 |
+
# one_hot = torch.zeros(cosine.size(), requires_grad=True, device='cuda')
|
44 |
+
one_hot = torch.zeros(cosine.size(), device='cuda')
|
45 |
+
one_hot.scatter_(1, label.view(-1, 1).long(), 1)
|
46 |
+
if self.ls_eps > 0:
|
47 |
+
one_hot = (1 - self.ls_eps) * one_hot + self.ls_eps / self.out_features
|
48 |
+
# -------------torch.where(out_i = {x_i if condition_i else y_i) -------------
|
49 |
+
output = (one_hot * phi) + ((1.0 - one_hot) * cosine)
|
50 |
+
output *= self.s
|
51 |
+
|
52 |
+
return output
|
53 |
+
|
54 |
+
|
55 |
+
def l2_norm(input, axis = 1):
|
56 |
+
norm = torch.norm(input, 2, axis, True)
|
57 |
+
output = torch.div(input, norm)
|
58 |
+
|
59 |
+
return output
|
60 |
+
class ElasticArcFace(nn.Module):
|
61 |
+
def __init__(self, in_features, out_features, s=64.0, m=0.50,std=0.0125,plus=False, k=None):
|
62 |
+
super(ElasticArcFace, self).__init__()
|
63 |
+
self.in_features = in_features
|
64 |
+
self.out_features = out_features
|
65 |
+
self.s = s
|
66 |
+
self.m = m
|
67 |
+
self.kernel = nn.Parameter(torch.FloatTensor(in_features, out_features))
|
68 |
+
nn.init.normal_(self.kernel, std=0.01)
|
69 |
+
self.std=std
|
70 |
+
self.plus=plus
|
71 |
+
def forward(self, embbedings, label):
|
72 |
+
embbedings = l2_norm(embbedings, axis=1)
|
73 |
+
kernel_norm = l2_norm(self.kernel, axis=0)
|
74 |
+
cos_theta = torch.mm(embbedings, kernel_norm)
|
75 |
+
cos_theta = cos_theta.clamp(-1, 1) # for numerical stability
|
76 |
+
index = torch.where(label != -1)[0]
|
77 |
+
m_hot = torch.zeros(index.size()[0], cos_theta.size()[1], device=cos_theta.device)
|
78 |
+
margin = torch.normal(mean=self.m, std=self.std, size=label[index, None].size(), device=cos_theta.device) # Fast converge .clamp(self.m-self.std, self.m+self.std)
|
79 |
+
if self.plus:
|
80 |
+
with torch.no_grad():
|
81 |
+
distmat = cos_theta[index, label.view(-1)].detach().clone()
|
82 |
+
_, idicate_cosie = torch.sort(distmat, dim=0, descending=True)
|
83 |
+
margin, _ = torch.sort(margin, dim=0)
|
84 |
+
m_hot.scatter_(1, label[index, None], margin[idicate_cosie])
|
85 |
+
else:
|
86 |
+
m_hot.scatter_(1, label[index, None], margin)
|
87 |
+
cos_theta.acos_()
|
88 |
+
cos_theta[index] += m_hot
|
89 |
+
cos_theta.cos_().mul_(self.s)
|
90 |
+
return cos_theta
|
91 |
+
|
92 |
+
########## Subcenter Arcface with dynamic margin ##########
|
93 |
+
|
94 |
+
class ArcMarginProduct_subcenter(nn.Module):
|
95 |
+
def __init__(self, in_features, out_features, k=3):
|
96 |
+
super().__init__()
|
97 |
+
self.weight = nn.Parameter(torch.FloatTensor(out_features*k, in_features))
|
98 |
+
self.reset_parameters()
|
99 |
+
self.k = k
|
100 |
+
self.out_features = out_features
|
101 |
+
|
102 |
+
def reset_parameters(self):
|
103 |
+
stdv = 1. / math.sqrt(self.weight.size(1))
|
104 |
+
self.weight.data.uniform_(-stdv, stdv)
|
105 |
+
|
106 |
+
def forward(self, features):
|
107 |
+
cosine_all = F.linear(F.normalize(features), F.normalize(self.weight))
|
108 |
+
cosine_all = cosine_all.view(-1, self.out_features, self.k)
|
109 |
+
cosine, _ = torch.max(cosine_all, dim=2)
|
110 |
+
return cosine
|
111 |
+
|
112 |
+
class ArcFaceLossAdaptiveMargin(nn.modules.Module):
|
113 |
+
def __init__(self, margins, out_dim, s):
|
114 |
+
super().__init__()
|
115 |
+
# self.crit = nn.CrossEntropyLoss()
|
116 |
+
self.s = s
|
117 |
+
self.register_buffer('margins', torch.tensor(margins))
|
118 |
+
self.out_dim = out_dim
|
119 |
+
|
120 |
+
def forward(self, logits, labels):
|
121 |
+
#ms = []
|
122 |
+
#ms = self.margins[labels.cpu().numpy()]
|
123 |
+
ms = self.margins[labels]
|
124 |
+
cos_m = torch.cos(ms) #torch.from_numpy(np.cos(ms)).float().cuda()
|
125 |
+
sin_m = torch.sin(ms) #torch.from_numpy(np.sin(ms)).float().cuda()
|
126 |
+
th = torch.cos(math.pi - ms)#torch.from_numpy(np.cos(math.pi - ms)).float().cuda()
|
127 |
+
mm = torch.sin(math.pi - ms) * ms#torch.from_numpy(np.sin(math.pi - ms) * ms).float().cuda()
|
128 |
+
labels = F.one_hot(labels, self.out_dim).float()
|
129 |
+
cosine = logits
|
130 |
+
sine = torch.sqrt(1.0 - cosine * cosine)
|
131 |
+
phi = cosine * cos_m.view(-1,1) - sine * sin_m.view(-1,1)
|
132 |
+
phi = torch.where(cosine > th.view(-1,1), phi, cosine - mm.view(-1,1))
|
133 |
+
output = (labels * phi) + ((1.0 - labels) * cosine)
|
134 |
+
output *= self.s
|
135 |
+
return output
|
136 |
+
|
137 |
+
class ArcFaceSubCenterDynamic(nn.Module):
|
138 |
+
def __init__(
|
139 |
+
self,
|
140 |
+
embedding_dim,
|
141 |
+
output_classes,
|
142 |
+
margins,
|
143 |
+
s,
|
144 |
+
k=2,
|
145 |
+
):
|
146 |
+
super().__init__()
|
147 |
+
|
148 |
+
self.embedding_dim = embedding_dim
|
149 |
+
self.output_classes = output_classes
|
150 |
+
self.margins = margins
|
151 |
+
self.s = s
|
152 |
+
self.wmetric_classify = ArcMarginProduct_subcenter(self.embedding_dim, self.output_classes, k=k)
|
153 |
+
|
154 |
+
self.warcface_margin = ArcFaceLossAdaptiveMargin(margins=self.margins,
|
155 |
+
out_dim=self.output_classes,
|
156 |
+
s=self.s)
|
157 |
+
|
158 |
+
def forward(self, features, labels):
|
159 |
+
logits = self.wmetric_classify(features.float())
|
160 |
+
logits = self.warcface_margin(logits, labels)
|
161 |
+
return logits
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:34dcc7b6c57694ad0ab7cceb09c8a17cfe7eb7cd44650bd5b58005527fb48a51
|
3 |
+
size 205809924
|
modeling_miewid.py
ADDED
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
import timm
|
6 |
+
|
7 |
+
from transformers import PreTrainedModel
|
8 |
+
|
9 |
+
from .heads import ArcMarginProduct, ElasticArcFace, ArcFaceSubCenterDynamic
|
10 |
+
from .configuration_miewid import MiewIdNetConfig
|
11 |
+
|
12 |
+
def weights_init_kaiming(m):
|
13 |
+
classname = m.__class__.__name__
|
14 |
+
if classname.find('Linear') != -1:
|
15 |
+
nn.init.kaiming_normal_(m.weight, a=0, mode='fan_out')
|
16 |
+
nn.init.constant_(m.bias, 0.0)
|
17 |
+
elif classname.find('Conv') != -1:
|
18 |
+
nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in')
|
19 |
+
if m.bias is not None:
|
20 |
+
nn.init.constant_(m.bias, 0.0)
|
21 |
+
elif classname.find('BatchNorm') != -1:
|
22 |
+
if m.affine:
|
23 |
+
nn.init.constant_(m.weight, 1.0)
|
24 |
+
nn.init.constant_(m.bias, 0.0)
|
25 |
+
|
26 |
+
|
27 |
+
def weights_init_classifier(m):
|
28 |
+
classname = m.__class__.__name__
|
29 |
+
if classname.find('Linear') != -1:
|
30 |
+
nn.init.normal_(m.weight, std=0.001)
|
31 |
+
if m.bias:
|
32 |
+
nn.init.constant_(m.bias, 0.0)
|
33 |
+
|
34 |
+
class GeM(nn.Module):
|
35 |
+
def __init__(self, p=3, eps=1e-6):
|
36 |
+
super(GeM, self).__init__()
|
37 |
+
self.p = nn.Parameter(torch.ones(1)*p)
|
38 |
+
self.eps = eps
|
39 |
+
|
40 |
+
def forward(self, x):
|
41 |
+
return self.gem(x, p=self.p, eps=self.eps)
|
42 |
+
|
43 |
+
def gem(self, x, p=3, eps=1e-6):
|
44 |
+
return F.avg_pool2d(x.clamp(min=eps).pow(p), (x.size(-2), x.size(-1))).pow(1./p)
|
45 |
+
|
46 |
+
def __repr__(self):
|
47 |
+
return self.__class__.__name__ + \
|
48 |
+
'(' + 'p=' + '{:.4f}'.format(self.p.data.tolist()[0]) + \
|
49 |
+
', ' + 'eps=' + str(self.eps) + ')'
|
50 |
+
|
51 |
+
class MiewIdNet(PreTrainedModel):
|
52 |
+
config_class = MiewIdNetConfig
|
53 |
+
|
54 |
+
def __init__(self, config):
|
55 |
+
"""
|
56 |
+
"""
|
57 |
+
super(MiewIdNet, self).__init__(config)
|
58 |
+
print('Building Model Backbone for {} model'.format(config.model_name))
|
59 |
+
print('config.model_name', config.model_name)
|
60 |
+
|
61 |
+
n_classes=config.n_classes
|
62 |
+
model_name=config.model_name
|
63 |
+
use_fc=False
|
64 |
+
fc_dim=512
|
65 |
+
dropout=0.0
|
66 |
+
loss_module=config.loss_module
|
67 |
+
s=30.0
|
68 |
+
margin=0.50
|
69 |
+
ls_eps=0.0
|
70 |
+
theta_zero=0.785
|
71 |
+
pretrained=True
|
72 |
+
margins=config.k
|
73 |
+
k=config.k
|
74 |
+
|
75 |
+
print('model_name', model_name)
|
76 |
+
|
77 |
+
self.backbone = timm.create_model(model_name, pretrained=pretrained, num_classes=0)
|
78 |
+
final_in_features = 2152#self.backbone.classifier.in_features
|
79 |
+
|
80 |
+
print('final_in_features', final_in_features)
|
81 |
+
|
82 |
+
# self.backbone.classifier = nn.Identity()
|
83 |
+
self.backbone.global_pool = GeM()#nn.Identity()
|
84 |
+
|
85 |
+
# self.pooling = GeM()
|
86 |
+
self.bn = nn.BatchNorm1d(final_in_features)
|
87 |
+
self.use_fc = use_fc
|
88 |
+
if use_fc:
|
89 |
+
self.dropout = nn.Dropout(p=dropout)
|
90 |
+
self.bn = nn.BatchNorm1d(fc_dim)
|
91 |
+
self.bn.bias.requires_grad_(False)
|
92 |
+
self.fc = nn.Linear(final_in_features, n_classes, bias = False)
|
93 |
+
self.bn.apply(weights_init_kaiming)
|
94 |
+
self.fc.apply(weights_init_classifier)
|
95 |
+
final_in_features = fc_dim
|
96 |
+
|
97 |
+
self.loss_module = loss_module
|
98 |
+
if loss_module == 'arcface':
|
99 |
+
self.final = ElasticArcFace(final_in_features, n_classes,
|
100 |
+
s=s, m=margin)
|
101 |
+
elif loss_module == 'arcface_subcenter_dynamic':
|
102 |
+
if margins is None:
|
103 |
+
margins = [0.3] * n_classes
|
104 |
+
print(final_in_features, n_classes)
|
105 |
+
self.final = ArcFaceSubCenterDynamic(
|
106 |
+
embedding_dim=final_in_features,
|
107 |
+
output_classes=n_classes,
|
108 |
+
margins=margins,
|
109 |
+
s=s,
|
110 |
+
k=k )
|
111 |
+
# elif loss_module == 'cosface':
|
112 |
+
# self.final = AddMarginProduct(final_in_features, n_classes, s=s, m=margin)
|
113 |
+
# elif loss_module == 'adacos':
|
114 |
+
# self.final = AdaCos(final_in_features, n_classes, m=margin, theta_zero=theta_zero)
|
115 |
+
else:
|
116 |
+
self.final = nn.Linear(final_in_features, n_classes)
|
117 |
+
|
118 |
+
def _init_params(self):
|
119 |
+
nn.init.xavier_normal_(self.fc.weight)
|
120 |
+
nn.init.constant_(self.fc.bias, 0)
|
121 |
+
nn.init.constant_(self.bn.weight, 1)
|
122 |
+
nn.init.constant_(self.bn.bias, 0)
|
123 |
+
|
124 |
+
def forward(self, x, label=None):
|
125 |
+
feature = self.extract_feat(x)
|
126 |
+
|
127 |
+
return feature
|
128 |
+
# if not self.training:
|
129 |
+
# return feature
|
130 |
+
# else:
|
131 |
+
# assert label is not None
|
132 |
+
# if self.loss_module in ('arcface', 'arcface_subcenter_dynamic'):
|
133 |
+
# logits = self.final(feature, label)
|
134 |
+
# else:
|
135 |
+
# logits = self.final(feature)
|
136 |
+
|
137 |
+
# return logits
|
138 |
+
|
139 |
+
def extract_feat(self, x):
|
140 |
+
batch_size = x.shape[0]
|
141 |
+
x = self.backbone(x).view(batch_size, -1)
|
142 |
+
# x = self.pooling(x).view(batch_size, -1)
|
143 |
+
x = self.bn(x)
|
144 |
+
if self.use_fc:
|
145 |
+
x1 = self.dropout(x)
|
146 |
+
x1 = self.bn(x1)
|
147 |
+
x1 = self.fc(x1)
|
148 |
+
|
149 |
+
return x
|
150 |
+
|
151 |
+
def extract_logits(self, x, label=None):
|
152 |
+
feature = self.extract_feat(x)
|
153 |
+
assert label is not None
|
154 |
+
if self.loss_module in ('arcface', 'arcface_subcenter_dynamic'):
|
155 |
+
logits = self.final(feature, label)
|
156 |
+
else:
|
157 |
+
logits = self.final(feature)
|
158 |
+
|
159 |
+
return logits
|