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

finetuning_training.py 7.5 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
  1. import torch
  2. from torch.utils.data import DataLoader
  3. import torch.optim as optim
  4. import os
  5. from datetime import datetime
  6. from matplotlib import pyplot as plt
  7. import matplotlib
  8. import numpy as np
  9. from dataset.dataset_class import FineTuningImagesDataset, FineTuningVideoDataset
  10. from network.model import *
  11. from loss.loss_discriminator import *
  12. from loss.loss_generator import *
  13. from params.params import K, path_to_chkpt, path_to_backup, path_to_Wi, batch_size, path_to_preprocess, frame_shape
  14. """Hyperparameters and config"""
  15. display_training = True
  16. if not display_training:
  17. matplotlib.use('agg')
  18. device = torch.device("cuda:0")
  19. cpu = torch.device("cpu")
  20. path_to_embedding = 'e_hat_video.tar'
  21. path_to_save = 'finetuned_model.tar'
  22. path_to_video = 'examples/fine_tuning/test_video.mp4'
  23. path_to_images = 'examples/fine_tuning/test_images'
  24. """Create dataset and net"""
  25. choice = ''
  26. while choice != '0' and choice != '1':
  27. choice = input('What source to finetune on?\n0: Video\n1: Images\n\nEnter number\n>>')
  28. if choice == '0': #video
  29. dataset = FineTuningVideoDataset(path_to_video, device)
  30. else: #Images
  31. dataset = FineTuningImagesDataset(path_to_images, device)
  32. dataLoader = DataLoader(dataset, batch_size=2, shuffle=False)
  33. e_hat = torch.load(path_to_embedding, map_location=cpu)
  34. e_hat = e_hat['e_hat']
  35. G = Generator(256, finetuning = True, e_finetuning = e_hat)
  36. D = Discriminator(dataset.__len__(), path_to_Wi, finetuning = True, e_finetuning = e_hat)
  37. G.train()
  38. D.train()
  39. optimizerG = optim.Adam(params = G.parameters(), lr=5e-5)
  40. optimizerD = optim.Adam(params = D.parameters(), lr=2e-4)
  41. """Criterion"""
  42. criterionG = LossGF(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 = 40
  52. #Warning if checkpoint inexistant
  53. if not os.path.isfile(path_to_chkpt):
  54. print('ERROR: cannot find checkpoint')
  55. if os.path.isfile(path_to_save):
  56. path_to_chkpt = path_to_save
  57. """Loading from past checkpoint"""
  58. checkpoint = torch.load(path_to_chkpt, map_location=cpu)
  59. checkpoint['D_state_dict']['W_i'] = torch.rand(512, 32) #change W_i for finetuning
  60. G.load_state_dict(checkpoint['G_state_dict'])
  61. D.load_state_dict(checkpoint['D_state_dict'], strict = False)
  62. """Change to finetuning mode"""
  63. G.finetuning_init()
  64. D.finetuning_init()
  65. G.to(device)
  66. D.to(device)
  67. """Training"""
  68. batch_start = datetime.now()
  69. cont = True
  70. while cont:
  71. for epoch in range(num_epochs):
  72. for i_batch, (x, g_y) in enumerate(dataLoader):
  73. with torch.autograd.enable_grad():
  74. #zero the parameter gradients
  75. optimizerG.zero_grad()
  76. optimizerD.zero_grad()
  77. #forward
  78. #train G and D
  79. x_hat = G(g_y, e_hat)
  80. r_hat, D_hat_res_list = D(x_hat, g_y, i=0)
  81. with torch.no_grad():
  82. r, D_res_list = D(x, g_y, i=0)
  83. lossG = criterionG(x, x_hat, r_hat, D_res_list, D_hat_res_list)
  84. lossG.backward(retain_graph=False)
  85. optimizerG.step()
  86. #train D
  87. optimizerD.zero_grad()
  88. x_hat.detach_().requires_grad_()
  89. r_hat, D_hat_res_list = D(x_hat, g_y, i=0)
  90. r, D_res_list = D(x, g_y, i=0)
  91. lossDfake = criterionDfake(r_hat)
  92. lossDreal = criterionDreal(r)
  93. lossD = lossDreal + lossDfake
  94. lossD.backward(retain_graph=False)
  95. optimizerD.step()
  96. #train D again
  97. optimizerG.zero_grad()
  98. optimizerD.zero_grad()
  99. r_hat, D_hat_res_list = D(x_hat, g_y, i=0)
  100. r, D_res_list = D(x, g_y, i=0)
  101. lossDfake = criterionDfake(r_hat)
  102. lossDreal = criterionDreal(r)
  103. lossD = lossDreal + lossDfake
  104. lossD.backward(retain_graph=False)
  105. optimizerD.step()
  106. # Output training stats
  107. if epoch % 10 == 0:
  108. batch_end = datetime.now()
  109. avg_time = (batch_end - batch_start) / 10
  110. print('\n\navg batch time for batch size of', x.shape[0],':',avg_time)
  111. batch_start = datetime.now()
  112. print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(y)): %.4f'
  113. % (epoch, num_epochs, i_batch, len(dataLoader),
  114. lossD.item(), lossG.item(), r.mean(), r_hat.mean()))
  115. """
  116. plt.clf()
  117. out = x_hat.transpose(1,3)[0]
  118. for img_no in range(1,x_hat.shape[0]):
  119. out = torch.cat((out, x_hat.transpose(1,3)[img_no]), dim = 1)
  120. out = out.type(torch.int32).to(cpu).numpy()*255
  121. plt.imshow(out)
  122. plt.show()
  123. plt.clf()
  124. out = x.transpose(1,3)[0]
  125. for img_no in range(1,x.shape[0]):
  126. out = torch.cat((out, x.transpose(1,3)[img_no]), dim = 1)
  127. out = out.type(torch.int32).to(cpu).numpy()*255
  128. plt.imshow(out)
  129. plt.show()
  130. plt.clf()
  131. out = g_y.transpose(1,3)[0]
  132. for img_no in range(1,g_y.shape[0]):
  133. out = torch.cat((out, g_y.transpose(1,3)[img_no]), dim = 1)
  134. out = out.type(torch.int32).to(cpu).numpy()*255
  135. plt.imshow(out)
  136. plt.show()
  137. lossesD.append(lossD.item())
  138. lossesG.append(lossG.item())"""
  139. if display_training:
  140. plt.clf()
  141. out = (x_hat[0]*255).transpose(0,2)
  142. for img_no in range(1,x_hat.shape[0]):
  143. out = torch.cat((out, (x_hat[img_no]*255).transpose(0,2)), dim = 1)
  144. out = out.type(torch.int32).to(cpu).numpy()
  145. fig = out
  146. plt.clf()
  147. out = (x[0]*255).transpose(0,2)
  148. for img_no in range(1,x.shape[0]):
  149. out = torch.cat((out, (x[img_no]*255).transpose(0,2)), dim = 1)
  150. out = out.type(torch.int32).to(cpu).numpy()
  151. fig = np.concatenate((fig, out), 0)
  152. plt.clf()
  153. out = (g_y[0]*255).transpose(0,2)
  154. for img_no in range(1,g_y.shape[0]):
  155. out = torch.cat((out, (g_y[img_no]*255).transpose(0,2)), dim = 1)
  156. out = out.type(torch.int32).to(cpu).numpy()
  157. fig = np.concatenate((fig, out), 0)
  158. plt.imshow(fig)
  159. plt.xticks([])
  160. plt.yticks([])
  161. plt.draw()
  162. plt.pause(0.001)
  163. num_epochs = int(input('Num epoch further?\n'))
  164. cont = num_epochs != 0
  165. print('Saving finetuned model...')
  166. torch.save({
  167. 'epoch': epoch,
  168. 'lossesG': lossesG,
  169. 'lossesD': lossesD,
  170. 'G_state_dict': G.state_dict(),
  171. 'D_state_dict': D.state_dict(),
  172. 'optimizerG_state_dict': optimizerG.state_dict(),
  173. 'optimizerD_state_dict': optimizerD.state_dict(),
  174. }, path_to_save)
  175. print('...Done saving latest')
Tip!

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

Comments

Loading...