Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

train.py 11 KB

You have to be logged in to leave a comment. Sign In
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
  1. """Main"""
  2. import torch
  3. import torch.nn as nn
  4. import torch.optim as optim
  5. from torch.utils.data import DataLoader
  6. from datetime import datetime
  7. import matplotlib
  8. #matplotlib.use('agg')
  9. from matplotlib import pyplot as plt
  10. plt.ion()
  11. import os
  12. from dataset.dataset_class import PreprocessDataset
  13. from dataset.video_extraction_conversion import *
  14. from loss.loss_discriminator import *
  15. from loss.loss_generator import *
  16. from network.blocks import *
  17. from network.model import *
  18. from tqdm import tqdm
  19. from params.params import K, path_to_chkpt, path_to_backup, path_to_Wi, batch_size, path_to_preprocess, frame_shape
  20. """Create dataset and net"""
  21. display_training = False
  22. device = torch.device("cuda:0")
  23. cpu = torch.device("cpu")
  24. dataset = PreprocessDataset(K=K, path_to_preprocess=path_to_preprocess, path_to_Wi=path_to_Wi)
  25. dataLoader = DataLoader(dataset, batch_size=batch_size, shuffle=True,
  26. num_workers=16,
  27. pin_memory=True,
  28. drop_last = True)
  29. G = nn.DataParallel(Generator(frame_shape).to(device))
  30. E = nn.DataParallel(Embedder(frame_shape).to(device))
  31. D = nn.DataParallel(Discriminator(dataset.__len__(), path_to_Wi).to(device))
  32. G.train()
  33. E.train()
  34. D.train()
  35. optimizerG = optim.Adam(params = list(E.parameters()) + list(G.parameters()),
  36. lr=5e-5,
  37. amsgrad=False)
  38. optimizerD = optim.Adam(params = D.parameters(),
  39. lr=2e-4,
  40. amsgrad=False)
  41. """Criterion"""
  42. criterionG = LossG(VGGFace_body_path='Pytorch_VGGFACE_IR.py',
  43. VGGFace_weight_path='Pytorch_VGGFACE.pth', device=device)
  44. criterionDreal = LossDSCreal()
  45. criterionDfake = LossDSCfake()
  46. """Training init"""
  47. epochCurrent = epoch = i_batch = 0
  48. lossesG = []
  49. lossesD = []
  50. i_batch_current = 0
  51. num_epochs = 75*5
  52. #initiate checkpoint if inexistant
  53. if not os.path.isfile(path_to_chkpt):
  54. def init_weights(m):
  55. if type(m) == nn.Conv2d:
  56. torch.nn.init.xavier_uniform(m.weight)
  57. G.apply(init_weights)
  58. D.apply(init_weights)
  59. E.apply(init_weights)
  60. print('Initiating new checkpoint...')
  61. torch.save({
  62. 'epoch': epoch,
  63. 'lossesG': lossesG,
  64. 'lossesD': lossesD,
  65. 'E_state_dict': E.module.state_dict(),
  66. 'G_state_dict': G.module.state_dict(),
  67. 'D_state_dict': D.module.state_dict(),
  68. 'num_vid': dataset.__len__(),
  69. 'i_batch': i_batch,
  70. 'optimizerG': optimizerG.state_dict(),
  71. 'optimizerD': optimizerD.state_dict()
  72. }, path_to_chkpt)
  73. print('...Done')
  74. """Loading from past checkpoint"""
  75. checkpoint = torch.load(path_to_chkpt, map_location=cpu)
  76. E.module.load_state_dict(checkpoint['E_state_dict'])
  77. G.module.load_state_dict(checkpoint['G_state_dict'], strict=False)
  78. D.module.load_state_dict(checkpoint['D_state_dict'])
  79. epochCurrent = checkpoint['epoch']
  80. lossesG = checkpoint['lossesG']
  81. lossesD = checkpoint['lossesD']
  82. num_vid = checkpoint['num_vid']
  83. i_batch_current = checkpoint['i_batch'] +1
  84. optimizerG.load_state_dict(checkpoint['optimizerG'])
  85. optimizerD.load_state_dict(checkpoint['optimizerD'])
  86. G.train()
  87. E.train()
  88. D.train()
  89. """Training"""
  90. batch_start = datetime.now()
  91. pbar = tqdm(dataLoader, leave=True, initial=0)
  92. if not display_training:
  93. matplotlib.use('agg')
  94. for epoch in range(epochCurrent, num_epochs):
  95. if epoch > epochCurrent:
  96. i_batch_current = 0
  97. pbar = tqdm(dataLoader, leave=True, initial=0)
  98. pbar.set_postfix(epoch=epoch)
  99. for i_batch, (f_lm, x, g_y, i, W_i) in enumerate(pbar, start=0):
  100. f_lm = f_lm.to(device)
  101. x = x.to(device)
  102. g_y = g_y.to(device)
  103. W_i = W_i.squeeze(-1).transpose(0,1).to(device).requires_grad_()
  104. D.module.load_W_i(W_i)
  105. if i_batch % 1 == 0:
  106. with torch.autograd.enable_grad():
  107. #zero the parameter gradients
  108. optimizerG.zero_grad()
  109. optimizerD.zero_grad()
  110. #forward
  111. # Calculate average encoding vector for video
  112. f_lm_compact = f_lm.view(-1, f_lm.shape[-4], f_lm.shape[-3], f_lm.shape[-2], f_lm.shape[-1]) #BxK,2,3,224,224
  113. e_vectors = E(f_lm_compact[:,0,:,:,:], f_lm_compact[:,1,:,:,:]) #BxK,512,1
  114. e_vectors = e_vectors.view(-1, f_lm.shape[1], 512, 1) #B,K,512,1
  115. e_hat = e_vectors.mean(dim=1)
  116. #train G and D
  117. x_hat = G(g_y, e_hat)
  118. r_hat, D_hat_res_list = D(x_hat, g_y, i)
  119. with torch.no_grad():
  120. r, D_res_list = D(x, g_y, i)
  121. """####################################################################################################################################################
  122. r, D_res_list = D(x, g_y, i)"""
  123. lossG = criterionG(x, x_hat, r_hat, D_res_list, D_hat_res_list, e_vectors, D.module.W_i, i)
  124. """####################################################################################################################################################
  125. lossD = criterionDfake(r_hat) + criterionDreal(r)
  126. loss = lossG + lossD
  127. loss.backward(retain_graph=False)
  128. optimizerG.step()
  129. optimizerD.step()"""
  130. lossG.backward(retain_graph=False)
  131. optimizerG.step()
  132. #optimizerD.step()
  133. with torch.autograd.enable_grad():
  134. optimizerG.zero_grad()
  135. optimizerD.zero_grad()
  136. x_hat.detach_().requires_grad_()
  137. r_hat, D_hat_res_list = D(x_hat, g_y, i)
  138. lossDfake = criterionDfake(r_hat)
  139. r, D_res_list = D(x, g_y, i)
  140. lossDreal = criterionDreal(r)
  141. lossD = lossDfake + lossDreal
  142. lossD.backward(retain_graph=False)
  143. optimizerD.step()
  144. #for p in D.module.parameters():
  145. # p.data.clamp_(-1.0, 1.0)
  146. optimizerD.zero_grad()
  147. r_hat, D_hat_res_list = D(x_hat, g_y, i)
  148. lossDfake = criterionDfake(r_hat)
  149. r, D_res_list = D(x, g_y, i)
  150. lossDreal = criterionDreal(r)
  151. lossD = lossDfake + lossDreal
  152. lossD.backward(retain_graph=False)
  153. optimizerD.step()
  154. #for p in D.module.parameters():
  155. # p.data.clamp_(-1.0, 1.0)
  156. for enum, idx in enumerate(i):
  157. torch.save({'W_i': D.module.W_i[:,enum].unsqueeze(-1)}, path_to_Wi+'/W_'+str(idx.item())+'/W_'+str(idx.item())+'.tar')
  158. # Output training stats
  159. if i_batch % 1 == 0 and i_batch > 0:
  160. #batch_end = datetime.now()
  161. #avg_time = (batch_end - batch_start) / 100
  162. # print('\n\navg batch time for batch size of', x.shape[0],':',avg_time)
  163. #batch_start = datetime.now()
  164. # print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(y)): %.4f'
  165. # % (epoch, num_epochs, i_batch, len(dataLoader),
  166. # lossD.item(), lossG.item(), r.mean(), r_hat.mean()))
  167. pbar.set_postfix(epoch=epoch, r=r.mean().item(), rhat=r_hat.mean().item(), lossG=lossG.item())
  168. if display_training:
  169. plt.figure(figsize=(10,10))
  170. plt.clf()
  171. out = (x_hat[0]*255).transpose(0,2)
  172. for img_no in range(1,x_hat.shape[0]//16):
  173. out = torch.cat((out, (x_hat[img_no]*255).transpose(0,2)), dim = 1)
  174. out = out.type(torch.int32).to(cpu).numpy()
  175. fig = out
  176. plt.clf()
  177. out = (x[0]*255).transpose(0,2)
  178. for img_no in range(1,x.shape[0]//16):
  179. out = torch.cat((out, (x[img_no]*255).transpose(0,2)), dim = 1)
  180. out = out.type(torch.int32).to(cpu).numpy()
  181. fig = np.concatenate((fig, out), 0)
  182. plt.clf()
  183. out = (g_y[0]*255).transpose(0,2)
  184. for img_no in range(1,g_y.shape[0]//16):
  185. out = torch.cat((out, (g_y[img_no]*255).transpose(0,2)), dim = 1)
  186. out = out.type(torch.int32).to(cpu).numpy()
  187. fig = np.concatenate((fig, out), 0)
  188. plt.imshow(fig)
  189. plt.xticks([])
  190. plt.yticks([])
  191. plt.draw()
  192. plt.pause(0.001)
  193. if i_batch % 1000 == 999:
  194. lossesD.append(lossD.item())
  195. lossesG.append(lossG.item())
  196. if display_training:
  197. plt.clf()
  198. plt.plot(lossesG) #blue
  199. plt.plot(lossesD) #orange
  200. plt.show()
  201. print('Saving latest...')
  202. torch.save({
  203. 'epoch': epoch,
  204. 'lossesG': lossesG,
  205. 'lossesD': lossesD,
  206. 'E_state_dict': E.module.state_dict(),
  207. 'G_state_dict': G.module.state_dict(),
  208. 'D_state_dict': D.module.state_dict(),
  209. 'num_vid': dataset.__len__(),
  210. 'i_batch': i_batch,
  211. 'optimizerG': optimizerG.state_dict(),
  212. 'optimizerD': optimizerD.state_dict()
  213. }, path_to_chkpt)
  214. out = (x_hat[0]*255).transpose(0,2)
  215. for img_no in range(1,2):
  216. out = torch.cat((out, (x_hat[img_no]*255).transpose(0,2)), dim = 1)
  217. out = out.type(torch.uint8).to(cpu).numpy()
  218. plt.imsave("recent.png", out)
  219. print('...Done saving latest')
  220. if epoch%1 == 0:
  221. print('Saving latest...')
  222. torch.save({
  223. 'epoch': epoch+1,
  224. 'lossesG': lossesG,
  225. 'lossesD': lossesD,
  226. 'E_state_dict': E.module.state_dict(),
  227. 'G_state_dict': G.module.state_dict(),
  228. 'D_state_dict': D.module.state_dict(),
  229. 'num_vid': dataset.__len__(),
  230. 'i_batch': i_batch,
  231. 'optimizerG': optimizerG.state_dict(),
  232. 'optimizerD': optimizerD.state_dict()
  233. }, path_to_backup)
  234. out = (x_hat[0]*255).transpose(0,2)
  235. for img_no in range(1,2):
  236. out = torch.cat((out, (x_hat[img_no]*255).transpose(0,2)), dim = 1)
  237. out = out.type(torch.uint8).to(cpu).numpy()
  238. plt.imsave("recent_backup.png", out)
  239. print('...Done saving latest')
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...