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

Model.py 17 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
  1. import multiprocessing
  2. from functools import partial
  3. import numpy as np
  4. from core import mathlib
  5. from core.interact import interact as io
  6. from core.leras import nn
  7. from facelib import FaceType
  8. from models import ModelBase
  9. from samplelib import *
  10. class QModel(ModelBase):
  11. #override
  12. def on_initialize(self):
  13. device_config = nn.getCurrentDeviceConfig()
  14. devices = device_config.devices
  15. self.model_data_format = "NCHW" if len(devices) != 0 and not self.is_debug() else "NHWC"
  16. nn.initialize(data_format=self.model_data_format)
  17. tf = nn.tf
  18. resolution = self.resolution = 96
  19. self.face_type = FaceType.FULL
  20. ae_dims = 128
  21. e_dims = 64
  22. d_dims = 64
  23. d_mask_dims = 16
  24. self.pretrain = False
  25. self.pretrain_just_disabled = False
  26. masked_training = True
  27. models_opt_on_gpu = len(devices) >= 1 and all([dev.total_mem_gb >= 4 for dev in devices])
  28. models_opt_device = nn.tf_default_device_name if models_opt_on_gpu and self.is_training else '/CPU:0'
  29. optimizer_vars_on_cpu = models_opt_device=='/CPU:0'
  30. input_ch = 3
  31. bgr_shape = nn.get4Dshape(resolution,resolution,input_ch)
  32. mask_shape = nn.get4Dshape(resolution,resolution,1)
  33. self.model_filename_list = []
  34. model_archi = nn.DeepFakeArchi(resolution, opts='ud')
  35. with tf.device ('/CPU:0'):
  36. #Place holders on CPU
  37. self.warped_src = tf.placeholder (nn.floatx, bgr_shape)
  38. self.warped_dst = tf.placeholder (nn.floatx, bgr_shape)
  39. self.target_src = tf.placeholder (nn.floatx, bgr_shape)
  40. self.target_dst = tf.placeholder (nn.floatx, bgr_shape)
  41. self.target_srcm = tf.placeholder (nn.floatx, mask_shape)
  42. self.target_dstm = tf.placeholder (nn.floatx, mask_shape)
  43. # Initializing model classes
  44. with tf.device (models_opt_device):
  45. self.encoder = model_archi.Encoder(in_ch=input_ch, e_ch=e_dims, name='encoder')
  46. encoder_out_ch = self.encoder.get_out_ch()*self.encoder.get_out_res(resolution)**2
  47. self.inter = model_archi.Inter (in_ch=encoder_out_ch, ae_ch=ae_dims, ae_out_ch=ae_dims, name='inter')
  48. inter_out_ch = self.inter.get_out_ch()
  49. self.decoder_src = model_archi.Decoder(in_ch=inter_out_ch, d_ch=d_dims, d_mask_ch=d_mask_dims, name='decoder_src')
  50. self.decoder_dst = model_archi.Decoder(in_ch=inter_out_ch, d_ch=d_dims, d_mask_ch=d_mask_dims, name='decoder_dst')
  51. self.model_filename_list += [ [self.encoder, 'encoder.npy' ],
  52. [self.inter, 'inter.npy' ],
  53. [self.decoder_src, 'decoder_src.npy'],
  54. [self.decoder_dst, 'decoder_dst.npy'] ]
  55. if self.is_training:
  56. self.src_dst_trainable_weights = self.encoder.get_weights() + self.inter.get_weights() + self.decoder_src.get_weights() + self.decoder_dst.get_weights()
  57. # Initialize optimizers
  58. self.src_dst_opt = nn.RMSprop(lr=2e-4, lr_dropout=0.3, name='src_dst_opt')
  59. self.src_dst_opt.initialize_variables(self.src_dst_trainable_weights, vars_on_cpu=optimizer_vars_on_cpu )
  60. self.model_filename_list += [ (self.src_dst_opt, 'src_dst_opt.npy') ]
  61. if self.is_training:
  62. # Adjust batch size for multiple GPU
  63. gpu_count = max(1, len(devices) )
  64. bs_per_gpu = max(1, 4 // gpu_count)
  65. self.set_batch_size( gpu_count*bs_per_gpu)
  66. # Compute losses per GPU
  67. gpu_pred_src_src_list = []
  68. gpu_pred_dst_dst_list = []
  69. gpu_pred_src_dst_list = []
  70. gpu_pred_src_srcm_list = []
  71. gpu_pred_dst_dstm_list = []
  72. gpu_pred_src_dstm_list = []
  73. gpu_src_losses = []
  74. gpu_dst_losses = []
  75. gpu_src_dst_loss_gvs = []
  76. for gpu_id in range(gpu_count):
  77. with tf.device( f'/{devices[gpu_id].tf_dev_type}:{gpu_id}' if len(devices) != 0 else f'/CPU:0' ):
  78. batch_slice = slice( gpu_id*bs_per_gpu, (gpu_id+1)*bs_per_gpu )
  79. with tf.device(f'/CPU:0'):
  80. # slice on CPU, otherwise all batch data will be transfered to GPU first
  81. gpu_warped_src = self.warped_src [batch_slice,:,:,:]
  82. gpu_warped_dst = self.warped_dst [batch_slice,:,:,:]
  83. gpu_target_src = self.target_src [batch_slice,:,:,:]
  84. gpu_target_dst = self.target_dst [batch_slice,:,:,:]
  85. gpu_target_srcm = self.target_srcm[batch_slice,:,:,:]
  86. gpu_target_dstm = self.target_dstm[batch_slice,:,:,:]
  87. # process model tensors
  88. gpu_src_code = self.inter(self.encoder(gpu_warped_src))
  89. gpu_dst_code = self.inter(self.encoder(gpu_warped_dst))
  90. gpu_pred_src_src, gpu_pred_src_srcm = self.decoder_src(gpu_src_code)
  91. gpu_pred_dst_dst, gpu_pred_dst_dstm = self.decoder_dst(gpu_dst_code)
  92. gpu_pred_src_dst, gpu_pred_src_dstm = self.decoder_src(gpu_dst_code)
  93. gpu_pred_src_src_list.append(gpu_pred_src_src)
  94. gpu_pred_dst_dst_list.append(gpu_pred_dst_dst)
  95. gpu_pred_src_dst_list.append(gpu_pred_src_dst)
  96. gpu_pred_src_srcm_list.append(gpu_pred_src_srcm)
  97. gpu_pred_dst_dstm_list.append(gpu_pred_dst_dstm)
  98. gpu_pred_src_dstm_list.append(gpu_pred_src_dstm)
  99. gpu_target_srcm_blur = nn.gaussian_blur(gpu_target_srcm, max(1, resolution // 32) )
  100. gpu_target_dstm_blur = nn.gaussian_blur(gpu_target_dstm, max(1, resolution // 32) )
  101. gpu_target_dst_masked = gpu_target_dst*gpu_target_dstm_blur
  102. gpu_target_dst_anti_masked = gpu_target_dst*(1.0 - gpu_target_dstm_blur)
  103. gpu_target_src_masked_opt = gpu_target_src*gpu_target_srcm_blur if masked_training else gpu_target_src
  104. gpu_target_dst_masked_opt = gpu_target_dst_masked if masked_training else gpu_target_dst
  105. gpu_pred_src_src_masked_opt = gpu_pred_src_src*gpu_target_srcm_blur if masked_training else gpu_pred_src_src
  106. gpu_pred_dst_dst_masked_opt = gpu_pred_dst_dst*gpu_target_dstm_blur if masked_training else gpu_pred_dst_dst
  107. gpu_psd_target_dst_masked = gpu_pred_src_dst*gpu_target_dstm_blur
  108. gpu_psd_target_dst_anti_masked = gpu_pred_src_dst*(1.0 - gpu_target_dstm_blur)
  109. gpu_src_loss = tf.reduce_mean ( 10*nn.dssim(gpu_target_src_masked_opt, gpu_pred_src_src_masked_opt, max_val=1.0, filter_size=int(resolution/11.6)), axis=[1])
  110. gpu_src_loss += tf.reduce_mean ( 10*tf.square ( gpu_target_src_masked_opt - gpu_pred_src_src_masked_opt ), axis=[1,2,3])
  111. gpu_src_loss += tf.reduce_mean ( 10*tf.square( gpu_target_srcm - gpu_pred_src_srcm ),axis=[1,2,3] )
  112. gpu_dst_loss = tf.reduce_mean ( 10*nn.dssim(gpu_target_dst_masked_opt, gpu_pred_dst_dst_masked_opt, max_val=1.0, filter_size=int(resolution/11.6) ), axis=[1])
  113. gpu_dst_loss += tf.reduce_mean ( 10*tf.square( gpu_target_dst_masked_opt- gpu_pred_dst_dst_masked_opt ), axis=[1,2,3])
  114. gpu_dst_loss += tf.reduce_mean ( 10*tf.square( gpu_target_dstm - gpu_pred_dst_dstm ),axis=[1,2,3] )
  115. gpu_src_losses += [gpu_src_loss]
  116. gpu_dst_losses += [gpu_dst_loss]
  117. gpu_G_loss = gpu_src_loss + gpu_dst_loss
  118. gpu_src_dst_loss_gvs += [ nn.gradients ( gpu_G_loss, self.src_dst_trainable_weights ) ]
  119. # Average losses and gradients, and create optimizer update ops
  120. with tf.device (models_opt_device):
  121. pred_src_src = nn.concat(gpu_pred_src_src_list, 0)
  122. pred_dst_dst = nn.concat(gpu_pred_dst_dst_list, 0)
  123. pred_src_dst = nn.concat(gpu_pred_src_dst_list, 0)
  124. pred_src_srcm = nn.concat(gpu_pred_src_srcm_list, 0)
  125. pred_dst_dstm = nn.concat(gpu_pred_dst_dstm_list, 0)
  126. pred_src_dstm = nn.concat(gpu_pred_src_dstm_list, 0)
  127. src_loss = nn.average_tensor_list(gpu_src_losses)
  128. dst_loss = nn.average_tensor_list(gpu_dst_losses)
  129. src_dst_loss_gv = nn.average_gv_list (gpu_src_dst_loss_gvs)
  130. src_dst_loss_gv_op = self.src_dst_opt.get_update_op (src_dst_loss_gv)
  131. # Initializing training and view functions
  132. def src_dst_train(warped_src, target_src, target_srcm, \
  133. warped_dst, target_dst, target_dstm):
  134. s, d, _ = nn.tf_sess.run ( [ src_loss, dst_loss, src_dst_loss_gv_op],
  135. feed_dict={self.warped_src :warped_src,
  136. self.target_src :target_src,
  137. self.target_srcm:target_srcm,
  138. self.warped_dst :warped_dst,
  139. self.target_dst :target_dst,
  140. self.target_dstm:target_dstm,
  141. })
  142. s = np.mean(s)
  143. d = np.mean(d)
  144. return s, d
  145. self.src_dst_train = src_dst_train
  146. def AE_view(warped_src, warped_dst):
  147. return nn.tf_sess.run ( [pred_src_src, pred_dst_dst, pred_dst_dstm, pred_src_dst, pred_src_dstm],
  148. feed_dict={self.warped_src:warped_src,
  149. self.warped_dst:warped_dst})
  150. self.AE_view = AE_view
  151. else:
  152. # Initializing merge function
  153. with tf.device( nn.tf_default_device_name if len(devices) != 0 else f'/CPU:0'):
  154. gpu_dst_code = self.inter(self.encoder(self.warped_dst))
  155. gpu_pred_src_dst, gpu_pred_src_dstm = self.decoder_src(gpu_dst_code)
  156. _, gpu_pred_dst_dstm = self.decoder_dst(gpu_dst_code)
  157. def AE_merge( warped_dst):
  158. return nn.tf_sess.run ( [gpu_pred_src_dst, gpu_pred_dst_dstm, gpu_pred_src_dstm], feed_dict={self.warped_dst:warped_dst})
  159. self.AE_merge = AE_merge
  160. # Loading/initializing all models/optimizers weights
  161. for model, filename in io.progress_bar_generator(self.model_filename_list, "Initializing models"):
  162. if self.pretrain_just_disabled:
  163. do_init = False
  164. if model == self.inter:
  165. do_init = True
  166. else:
  167. do_init = self.is_first_run()
  168. if not do_init:
  169. do_init = not model.load_weights( self.get_strpath_storage_for_file(filename) )
  170. if do_init and self.pretrained_model_path is not None:
  171. pretrained_filepath = self.pretrained_model_path / filename
  172. if pretrained_filepath.exists():
  173. do_init = not model.load_weights(pretrained_filepath)
  174. if do_init:
  175. model.init_weights()
  176. # initializing sample generators
  177. if self.is_training:
  178. training_data_src_path = self.training_data_src_path if not self.pretrain else self.get_pretraining_data_path()
  179. training_data_dst_path = self.training_data_dst_path if not self.pretrain else self.get_pretraining_data_path()
  180. cpu_count = min(multiprocessing.cpu_count(), 8)
  181. src_generators_count = cpu_count // 2
  182. dst_generators_count = cpu_count // 2
  183. self.set_training_data_generators ([
  184. SampleGeneratorFace(training_data_src_path, debug=self.is_debug(), batch_size=self.get_batch_size(),
  185. sample_process_options=SampleProcessor.Options(random_flip=True if self.pretrain else False),
  186. output_sample_types = [ {'sample_type': SampleProcessor.SampleType.FACE_IMAGE,'warp':True, 'transform':True, 'channel_type' : SampleProcessor.ChannelType.BGR, 'face_type':self.face_type, 'data_format':nn.data_format, 'resolution': resolution},
  187. {'sample_type': SampleProcessor.SampleType.FACE_IMAGE,'warp':False, 'transform':True, 'channel_type' : SampleProcessor.ChannelType.BGR, 'face_type':self.face_type, 'data_format':nn.data_format, 'resolution': resolution},
  188. {'sample_type': SampleProcessor.SampleType.FACE_MASK, 'warp':False, 'transform':True, 'channel_type' : SampleProcessor.ChannelType.G, 'face_mask_type' : SampleProcessor.FaceMaskType.FULL_FACE, 'face_type':self.face_type, 'data_format':nn.data_format, 'resolution': resolution}
  189. ],
  190. generators_count=src_generators_count ),
  191. SampleGeneratorFace(training_data_dst_path, debug=self.is_debug(), batch_size=self.get_batch_size(),
  192. sample_process_options=SampleProcessor.Options(random_flip=True if self.pretrain else False),
  193. output_sample_types = [ {'sample_type': SampleProcessor.SampleType.FACE_IMAGE,'warp':True, 'transform':True, 'channel_type' : SampleProcessor.ChannelType.BGR, 'face_type':self.face_type, 'data_format':nn.data_format, 'resolution': resolution},
  194. {'sample_type': SampleProcessor.SampleType.FACE_IMAGE,'warp':False, 'transform':True, 'channel_type' : SampleProcessor.ChannelType.BGR, 'face_type':self.face_type, 'data_format':nn.data_format, 'resolution': resolution},
  195. {'sample_type': SampleProcessor.SampleType.FACE_MASK, 'warp':False, 'transform':True, 'channel_type' : SampleProcessor.ChannelType.G, 'face_mask_type' : SampleProcessor.FaceMaskType.FULL_FACE, 'face_type':self.face_type, 'data_format':nn.data_format, 'resolution': resolution}
  196. ],
  197. generators_count=dst_generators_count )
  198. ])
  199. self.last_samples = None
  200. #override
  201. def get_model_filename_list(self):
  202. return self.model_filename_list
  203. #override
  204. def onSave(self):
  205. for model, filename in io.progress_bar_generator(self.get_model_filename_list(), "Saving", leave=False):
  206. model.save_weights ( self.get_strpath_storage_for_file(filename) )
  207. #override
  208. def onTrainOneIter(self):
  209. if self.get_iter() % 3 == 0 and self.last_samples is not None:
  210. ( (warped_src, target_src, target_srcm), \
  211. (warped_dst, target_dst, target_dstm) ) = self.last_samples
  212. warped_src = target_src
  213. warped_dst = target_dst
  214. else:
  215. samples = self.last_samples = self.generate_next_samples()
  216. ( (warped_src, target_src, target_srcm), \
  217. (warped_dst, target_dst, target_dstm) ) = samples
  218. src_loss, dst_loss = self.src_dst_train (warped_src, target_src, target_srcm,
  219. warped_dst, target_dst, target_dstm)
  220. return ( ('src_loss', src_loss), ('dst_loss', dst_loss), )
  221. #override
  222. def onGetPreview(self, samples, for_history=False):
  223. ( (warped_src, target_src, target_srcm),
  224. (warped_dst, target_dst, target_dstm) ) = samples
  225. S, D, SS, DD, DDM, SD, SDM = [ np.clip( nn.to_data_format(x,"NHWC", self.model_data_format), 0.0, 1.0) for x in ([target_src,target_dst] + self.AE_view (target_src, target_dst) ) ]
  226. DDM, SDM, = [ np.repeat (x, (3,), -1) for x in [DDM, SDM] ]
  227. target_srcm, target_dstm = [ nn.to_data_format(x,"NHWC", self.model_data_format) for x in ([target_srcm, target_dstm] )]
  228. n_samples = min(4, self.get_batch_size() )
  229. result = []
  230. st = []
  231. for i in range(n_samples):
  232. ar = S[i], SS[i], D[i], DD[i], SD[i]
  233. st.append ( np.concatenate ( ar, axis=1) )
  234. result += [ ('Quick96', np.concatenate (st, axis=0 )), ]
  235. st_m = []
  236. for i in range(n_samples):
  237. ar = S[i]*target_srcm[i], SS[i], D[i]*target_dstm[i], DD[i]*DDM[i], SD[i]*(DDM[i]*SDM[i])
  238. st_m.append ( np.concatenate ( ar, axis=1) )
  239. result += [ ('Quick96 masked', np.concatenate (st_m, axis=0 )), ]
  240. return result
  241. def predictor_func (self, face=None):
  242. face = nn.to_data_format(face[None,...], self.model_data_format, "NHWC")
  243. bgr, mask_dst_dstm, mask_src_dstm = [ nn.to_data_format(x, "NHWC", self.model_data_format).astype(np.float32) for x in self.AE_merge (face) ]
  244. return bgr[0], mask_src_dstm[0][...,0], mask_dst_dstm[0][...,0]
  245. #override
  246. def get_MergerConfig(self):
  247. import merger
  248. return self.predictor_func, (self.resolution, self.resolution, 3), merger.MergerConfigMasked(face_type=self.face_type,
  249. default_mode = 'overlay',
  250. )
  251. Model = QModel
Tip!

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

Comments

Loading...