-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrain.py
213 lines (170 loc) · 7.89 KB
/
train.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
'''
Source code for training SynthDistill (IJCB 2023):
SynthDistill: Face Recognition with Knowledge Distillation from Synthetic Data
'''
import os,sys
sys.path.append(os.getcwd())
import torch
import random
import numpy as np
from tqdm import tqdm
import math
import argparse
seed=2021
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print("************ NOTE: The torch device is:", device)
parser = argparse.ArgumentParser(description='SynthDistill: Face Recognition with Knowledge Distillation from Synthetic Data')
parser.add_argument('--model', metavar='<model>', type= str, default='TinyFaR_A',
help='TinyFaR_A,TinyFaR_B,TinyFaR_C')
parser.add_argument('--resampling_coef', metavar='<resampling_coef>', type= float, default=1.0,
help='resampling coefficient')
args = parser.parse_args()
resampling_coef = args.resampling_coef
batch_size=2*64
num_epochs=21
iterations_per_epoch_train = int (1e6/batch_size)
iterations_per_epoch_val = int (1e4/batch_size)
# Save the results in the following folder.
results_path = 'results'
os.makedirs(results_path, exist_ok= True)
with open(results_path + '/log_train.txt','w') as f:
pass
with open(results_path + '/log.csv', 'w') as f:
f.write(f"epoch, loss_test_MSE, loss_test_cos, loss_test\n")
#========================================================
#=================== import Network =====================
from src.Network import LightNetwork
if args.model=='TinyFaR_A':
light_model = LightNetwork(model_name='tinynet_a')
elif args.model=='TinyFaR_B':
light_model = LightNetwork(model_name='tinynet_b')
elif args.model=='TinyFaR_C':
light_model = LightNetwork(model_name='tinynet_c')
print('light_model # params', sum(p.numel() for p in light_model.parameters()))
light_model.to(device)
from src.ArcFace import get_FaceRecognition_transformer
large_model= get_FaceRecognition_transformer(device)
#=================== StyleGAN
sys.path.append('./stylegan3') # git clone https://github.com/NVlabs/stylegan3
import pickle
import torch_utils
path_stylegan = './stylegan2-ffhq-256x256.pkl'
with open(path_stylegan, 'rb') as f:
StyleGAN = pickle.load(f)['G_ema']
# StyleGAN.to(device)
# StyleGAN.eval()
StyleGAN_synthesis = StyleGAN.synthesis
StyleGAN_mapping = StyleGAN.mapping
StyleGAN_synthesis.eval()
StyleGAN_mapping.eval()
StyleGAN_synthesis.to(device)
StyleGAN_mapping.to(device)
z_dim_StyleGAN = StyleGAN.z_dim
from src.Crop import Crop_and_resize
#========================================================
#=================== Optimizers =========================
MSELoss = torch.nn.MSELoss(reduction ='mean')
#========================================================
#=================== Optimizers =========================
lr = 0.001
optimizer = torch.optim.Adam(light_model.parameters(), lr=lr)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.5)
#========================================================
######################################################################
print('learning rate = ', str(lr))
for epoch in tqdm(range(num_epochs)):
light_model.train()
# large_model.eval()
for itr in range(iterations_per_epoch_train):
with torch.no_grad():
# Generate batch of latent vectors
noise = torch.randn(batch_size, z_dim_StyleGAN, device=device)
# generate w from noise(z)
w = StyleGAN_mapping(z=noise, c=None, truncation_psi=1.0).detach()
# # syntheise images from w
img = StyleGAN_synthesis(w).detach()
# img = StyleGAN(z=noise, c=None, truncation_psi=1.0).detach()
# clamp values for generated images prior to feature extractor
img = torch.clamp(img, min=-1, max=1)
img = (img + 1) / 2.0 # range: (0,1)
img = Crop_and_resize(img)
# ================== forward =================
emb_light = light_model((img- 0.5) / 0.5)
with torch.no_grad():
emb_large = large_model.transform(img*255.)
MSE = MSELoss(emb_light, emb_large)
cos = torch.nn.CosineSimilarity()(emb_light, emb_large).mean()
loss = MSE
# ================== backward =================
optimizer.zero_grad()
loss.backward()#(retain_graph=True)
optimizer.step()
#==============================================
cos_sim = torch.nn.CosineSimilarity()(emb_light, emb_large)
coef = (cos_sim + 1)/2.0
w_=w[:,0,:]
w_ = w_ + coef.unsqueeze(1) * resampling_coef * torch.randn(batch_size, StyleGAN.w_dim, device=device)
w = w_.unsqueeze(1).repeat([1, StyleGAN.num_ws, 1])
with torch.no_grad():
# Generate batch of latent vectors
# noise = noise[indx_wrost_sim] + 0.1 * torch.randn(batch_size, z_dim_StyleGAN, device=device)
# generate w from noise(z)
# w = StyleGAN_mapping(z=noise, c=None, truncation_psi=1.0).detach()
# # syntheise images from w
img = StyleGAN_synthesis(w).detach()
# img = StyleGAN(z=noise, c=None, truncation_psi=1.0).detach()
# clamp values for generated images prior to feature extractor
img = torch.clamp(img, min=-1, max=1)
img = (img + 1) / 2.0 # range: (0,1)
img = Crop_and_resize(img)
# ================== forward =================
emb_light = light_model((img- 0.5) / 0.5)
with torch.no_grad():
emb_large = large_model.transform(img*255.)
MSE = MSELoss(emb_light, emb_large)
cos = torch.nn.CosineSimilarity()(emb_light, emb_large).mean()
loss = MSE
# ================== backward =================
optimizer.zero_grad()
loss.backward()#(retain_graph=True)
optimizer.step()
#==============================================
if itr%500==0:
print('epoch = '+ str(epoch) + ', iteration = ' + str(itr) + ', loss = ' + str(loss.item()), flush=True)
with open(results_path + '/log_train.txt','a') as f:
f.write('epoch = '+ str(epoch) + ', iteration = ' + str(itr) + ', loss = ' + str(loss.item()) + '\n')
light_model.eval()
# large_model.eval()
torch.save(light_model.state_dict(), results_path + '/light_model_' +str(epoch)+'.pt')
loss_test = loss_test_cos = loss_test_MSE = 0
for itr in range(iterations_per_epoch_val):
with torch.no_grad():
# Generate batch of latent vectors
noise = torch.randn(batch_size, z_dim_StyleGAN, device=device)
# generate w from noise(z)
w = StyleGAN_mapping(z=noise, c=None, truncation_psi=1.0).detach()
# syntheise images from w
img = StyleGAN_synthesis(w).detach()
# img = StyleGAN(z=noise, c=None, truncation_psi=1.0).detach()
# clamp values for generated images prior to feature extractor0
img = torch.clamp(img, min=-1, max=1)
img = (img + 1) / 2.0 # range: (0,1)
img = Crop_and_resize(img)
# ================== forward =================
emb_light = light_model((img- 0.5) / 0.5)
emb_large = large_model.transform(img*255.)
MSE = MSELoss(emb_light, emb_large)
cos = torch.nn.CosineSimilarity()(emb_light, emb_large).mean()
loss = MSE
loss_test_MSE += MSE.item()
loss_test_cos += cos.item()
loss_test += loss.item()
with open(results_path + '/log.csv', 'a') as f:
f.write(f"{epoch}, {loss_test_MSE/iterations_per_epoch_val}, {loss_test_cos/iterations_per_epoch_val}, {loss_test/iterations_per_epoch_val}\n")
# Update schedulers
scheduler.step()