-
Notifications
You must be signed in to change notification settings - Fork 9
/
processor_v2.py
1567 lines (1373 loc) · 81.8 KB
/
processor_v2.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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import glob
import json
import librosa
import lmdb
import math
import matplotlib.pyplot as plt
import numpy as np
import os
import pickle
import pyarrow
import python_speech_features as ps
import threading
import time
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from os.path import join as jn
from torchlight.torchlight.io import IO
import utils.common as cmn
from net.embedding_space_evaluator import EmbeddingSpaceEvaluator
from net.ser_att_conv_rnn_v1 import AttConvRNN
from net.multimodal_context_net_v2 import PoseGeneratorTriModal as PGT, ConvDiscriminatorTriModal as CDT
from net.multimodal_context_net_v2 import PoseGenerator, AffDiscriminator
from utils import losses
from utils.average_meter import AverageMeter
from utils.data_preprocessor import DataPreprocessor
from utils.gen_utils import create_video_and_save
from utils.mocap_dataset import MoCapDataset
from utils.ted_db_utils import *
torch.manual_seed(1234)
rec_loss = losses.quat_angle_loss
def find_all_substr(a_str, sub):
start = 0
while True:
start = a_str.find(sub, start)
if start == -1:
return
yield start
start += len(sub) # use start += 1 to find overlapping matches
def get_epoch_and_loss(path_to_model_files, epoch='best'):
all_models = os.listdir(path_to_model_files)
if len(all_models) < 2:
return '', None, np.inf
if epoch == 'best':
loss_list = -1. * np.ones(len(all_models))
for i, model in enumerate(all_models):
loss_val = str.split(model, '_')
if len(loss_val) > 1:
loss_list[i] = float(loss_val[3])
if len(loss_list) < 3:
best_model = all_models[np.argwhere(loss_list == min([n for n in loss_list if n > 0]))[0, 0]]
else:
loss_idx = np.argpartition(loss_list, 2)
best_model = all_models[loss_idx[1]]
all_underscores = list(find_all_substr(best_model, '_'))
# return model name, best loss
return best_model, int(best_model[all_underscores[0] + 1:all_underscores[1]]), \
float(best_model[all_underscores[2] + 1:all_underscores[3]])
assert isinstance(epoch, int)
found_model = None
for i, model in enumerate(all_models):
model_epoch = str.split(model, '_')
if len(model_epoch) > 1 and epoch == int(model_epoch[1]):
found_model = model
break
if found_model is None:
return '', None, np.inf
all_underscores = list(find_all_substr(found_model, '_'))
return found_model, int(found_model[all_underscores[0] + 1:all_underscores[1]]), \
float(found_model[all_underscores[2] + 1:all_underscores[3]])
class Processor(object):
"""
Processor for emotive gesture generation
"""
def __init__(self, base_path, args, s2ag_config_args, data_loader, pose_dim, coords,
audio_sr, min_train_epochs=20, zfill=6):
self.base_path = base_path
self.args = args
self.device = torch.device('cpu' if self.args.no_cuda or not torch.cuda.is_available() else 'cuda:{}'.format(torch.cuda.current_device()))
self.s2ag_config_args = s2ag_config_args
self.data_loader = data_loader
self.result = dict()
self.iter_info = dict()
self.epoch_info = dict()
self.meta_info = dict(epoch=0, iter=0)
self.io = IO(
self.args.work_dir_s2ag,
save_log=self.args.save_log,
print_log=self.args.print_log)
# model
self.pose_dim = pose_dim
self.coords = coords
self.audio_sr = audio_sr
if self.args.train_s2ag:
self.time_steps = self.data_loader['train_data_s2ag'].n_poses
self.audio_length = self.data_loader['train_data_s2ag'].expected_audio_length
self.spectrogram_length = self.data_loader['train_data_s2ag'].expected_spectrogram_length
self.num_mfcc = self.data_loader['train_data_s2ag'].num_mfcc_combined
self.lang_model = self.data_loader['train_data_s2ag'].lang_model
else:
self.time_steps = self.data_loader['test_data_s2ag'].n_poses
self.audio_length = self.data_loader['test_data_s2ag'].expected_audio_length
self.spectrogram_length = self.data_loader['test_data_s2ag'].expected_spectrogram_length
self.num_mfcc = self.data_loader['test_data_s2ag'].num_mfcc_combined
self.lang_model = self.data_loader['test_data_s2ag'].lang_model
self.mfcc_length = int(np.ceil(self.audio_length / 512))
self.best_s2ag_loss = np.inf
self.best_s2ag_loss_epoch = None
self.s2ag_loss_updated = False
self.min_train_epochs = min_train_epochs
self.zfill = zfill
self.train_speaker_model = self.data_loader['train_data_s2ag'].speaker_model
self.val_speaker_model = self.data_loader['val_data_s2ag'].speaker_model
self.test_speaker_model = self.data_loader['test_data_s2ag'].speaker_model
self.trimodal_generator = PGT(self.s2ag_config_args,
pose_dim=self.pose_dim,
n_words=self.lang_model.n_words,
word_embed_size=self.s2ag_config_args.wordembed_dim,
word_embeddings=self.lang_model.word_embedding_weights,
z_obj=self.train_speaker_model)
self.trimodal_discriminator = CDT(self.pose_dim)
self.use_mfcc = True
if self.use_mfcc:
self.s2ag_generator = PoseGenerator(self.s2ag_config_args,
pose_dim=self.pose_dim,
n_words=self.lang_model.n_words,
word_embed_size=self.s2ag_config_args.wordembed_dim,
word_embeddings=self.lang_model.word_embedding_weights,
mfcc_length=self.mfcc_length,
num_mfcc=self.num_mfcc,
time_steps=self.time_steps,
z_obj=self.train_speaker_model)
else:
self.s2ag_generator = PGT(self.s2ag_config_args,
pose_dim=self.pose_dim,
n_words=self.lang_model.n_words,
word_embed_size=self.s2ag_config_args.wordembed_dim,
word_embeddings=self.lang_model.word_embedding_weights,
z_obj=self.train_speaker_model)
# self.s2ag_discriminator = CDT(self.pose_dim)
self.s2ag_discriminator = AffDiscriminator(self.pose_dim)
self.evaluator_trimodal = EmbeddingSpaceEvaluator(self.base_path, self.s2ag_config_args, self.pose_dim,
self.lang_model, self.device)
self.evaluator = EmbeddingSpaceEvaluator(self.base_path, self.s2ag_config_args, self.pose_dim,
self.lang_model, self.device)
if self.args.use_multiple_gpus and torch.cuda.device_count() > 1:
self.args.batch_size *= torch.cuda.device_count()
self.trimodal_generator = nn.DataParallel(self.trimodal_generator)
self.trimodal_discriminator = nn.DataParallel(self.trimodal_discriminator)
self.s2ag_generator = nn.DataParallel(self.s2ag_generator)
self.s2ag_discriminator = nn.DataParallel(self.s2ag_discriminator)
else:
self.trimodal_generator.to(self.device)
self.trimodal_discriminator.to(self.device)
self.s2ag_generator.to(self.device)
self.s2ag_discriminator.to(self.device)
npz_path = jn(self.args.data_path, self.args.dataset_s2ag, 'npz')
os.makedirs(npz_path, exist_ok=True)
self.num_test_samples = self.data_loader['test_data_s2ag'].n_samples
if self.args.train_s2ag:
self.num_train_samples = self.data_loader['train_data_s2ag'].n_samples
self.num_val_samples = self.data_loader['val_data_s2ag'].n_samples
self.num_total_samples = self.num_train_samples + self.num_val_samples + self.num_test_samples
print('Total s2ag training data:\t\t{:>6} ({:.2f}%)'.format(
self.num_train_samples, 100. * self.num_train_samples / self.num_total_samples))
print('Training s2ag with batch size:\t{:>6}'.format(self.args.batch_size))
train_dir_name = jn(npz_path, 'train')
if not os.path.exists(train_dir_name):
self.save_cache('train', os.path.dirname(train_dir_name))
self.load_cache('train', train_dir_name)
print('Total s2ag validation data:\t\t{:>6} ({:.2f}%)'.format(
self.num_val_samples, 100. * self.num_val_samples / self.num_total_samples))
val_dir_name = jn(npz_path, 'val')
if not os.path.exists(val_dir_name):
self.save_cache('val', os.path.dirname(val_dir_name))
self.load_cache('val', val_dir_name)
else:
self.train_samples = None
self.val_samples = None
self.num_total_samples = self.num_test_samples
print('Total s2ag testing data:\t\t{:>6} ({:.2f}%)'.format(
self.num_test_samples, 100. * self.num_test_samples / self.num_total_samples))
test_dir_name = jn(npz_path, 'test')
if not os.path.exists(test_dir_name):
self.save_cache('test', os.path.dirname(test_dir_name))
self.lr_s2ag_gen = self.s2ag_config_args.learning_rate
self.lr_s2ag_dis = self.s2ag_config_args.learning_rate * self.s2ag_config_args.discriminator_lr_weight
# s2ag optimizers
self.s2ag_gen_optimizer = optim.Adam(self.s2ag_generator.parameters(),
lr=self.lr_s2ag_gen, betas=(0.5, 0.999))
self.s2ag_dis_optimizer = torch.optim.Adam(
self.s2ag_discriminator.parameters(),
lr=self.lr_s2ag_dis,
betas=(0.5, 0.999))
def load_cache(self, part, dir_name, load_full=True):
print('Loading {} cache'.format(part), end='')
if load_full:
start_time = time.time()
npz = np.load(jn(dir_name, '../full', part + '.npz'), allow_pickle=True)
samples_dict = {'extended_word_seq': npz['extended_word_seq'],
'vec_seq': npz['vec_seq'],
'audio': npz['audio'],
'audio_max': npz['audio_max'],
'mfcc_features': npz['mfcc_features'].astype(np.float16),
'vid_indices': npz['vid_indices']
}
if part == 'train':
self.train_samples = samples_dict
elif part == 'val':
self.val_samples = samples_dict
elif part == 'test':
self.test_samples = samples_dict
print(' took {:>6} seconds.'.format(int(np.ceil(time.time() - start_time))))
else:
num_samples = self.num_train_samples if part == 'train' else (self.num_val_samples if part == 'val' else self.num_test_samples)
samples_dict = {'extended_word_seq': [],
'vec_seq': [],
'audio': [],
'audio_max': [],
'mfcc_features': [],
'vid_indices': []}
for k in range(num_samples):
start_time = time.time()
npz = np.load(jn(dir_name, str(k).zfill(6) + '.npz'), allow_pickle=True)
samples_dict['extended_word_seq'].append(npz['extended_word_seq'])
samples_dict['vec_seq'].append(npz['vec_seq'])
samples_dict['audio'].append(npz['audio'])
samples_dict['audio_max'].append(npz['audio_max'])
samples_dict['mfcc_features'].append(npz['mfcc_features'].astype(np.float16))
samples_dict['vid_indices'].append(npz['vid_indices'])
time_taken = time.time() - start_time
time_remaining = np.ceil((num_samples - k - 1) * time_taken)
print('\rLoading {} cache {:>6}/{}, estimated time remaining {}.'.format(part, k + 1, num_samples,
str(datetime.timedelta(seconds=time_remaining))), end='')
for dict_key in samples_dict.keys():
samples_dict[dict_key] = np.stack(samples_dict[dict_key])
if part == 'train':
self.train_samples = samples_dict
elif part == 'val':
self.val_samples = samples_dict
elif part == 'test':
self.test_samples = samples_dict
print(' Completed.')
def save_cache(self, part, dir_name):
data_s2ag = self.data_loader['{}_data_s2ag'.format(part)]
num_samples = self.num_train_samples if part == 'train' else (self.num_val_samples if part == 'val' else self.num_test_samples)
speaker_model = self.train_speaker_model if part == 'train' else (self.val_speaker_model if part == 'val' else self.test_speaker_model)
extended_word_seq_all = np.zeros((num_samples, self.time_steps), dtype=np.int64)
vec_seq_all = np.zeros((num_samples, self.time_steps, self.pose_dim))
audio_all = np.zeros((num_samples, self.audio_length), dtype=np.int16)
audio_max_all = np.zeros(num_samples)
mfcc_features_all = np.zeros((num_samples, self.num_mfcc, self.mfcc_length))
vid_indices_all = np.zeros(num_samples, dtype=np.int64)
print('Caching {} data {:>6}/{}.'.format(part, 0, num_samples), end='')
for k in range(num_samples):
with data_s2ag.lmdb_env.begin(write=False) as txn:
key = '{:010}'.format(k).encode('ascii')
sample = txn.get(key)
sample = pyarrow.deserialize(sample)
word_seq, pose_seq, vec_seq, audio, spectrogram, mfcc_features, aux_info = sample
# with data_s2ag.lmdb_env.begin(write=False) as txn:
# key = '{:010}'.format(k).encode('ascii')
# sample = txn.get(key)
# sample = pyarrow.deserialize(sample)
# word_seq, pose_seq, vec_seq, audio, spectrogram, mfcc_features, aux_info = sample
duration = aux_info['end_time'] - aux_info['start_time']
audio_max_all[k] = np.max(np.abs(audio))
do_clipping = True
if do_clipping:
sample_end_time = aux_info['start_time'] + duration * data_s2ag.n_poses / vec_seq.shape[0]
audio = make_audio_fixed_length(audio, self.audio_length)
mfcc_features = mfcc_features[:, 0:self.mfcc_length]
vec_seq = vec_seq[0:data_s2ag.n_poses]
else:
sample_end_time = None
# to tensors
word_seq_tensor = Processor.words_to_tensor(data_s2ag.lang_model, word_seq, sample_end_time)
extended_word_seq = Processor.extend_word_seq(data_s2ag.n_poses, data_s2ag.lang_model,
data_s2ag.remove_word_timing, word_seq,
aux_info, sample_end_time).detach().cpu().numpy()
vec_seq = torch.from_numpy(vec_seq).reshape((vec_seq.shape[0], -1)).float().detach().cpu().numpy()
extended_word_seq_all[k] = extended_word_seq
vec_seq_all[k] = vec_seq
audio_all[k] = np.int16(audio / audio_max_all[k] * 32767)
mfcc_features_all[k] = mfcc_features
vid_indices_all[k] = speaker_model.word2index[aux_info['vid']]
part_save_dir = jn(dir_name, part)
os.makedirs(part_save_dir, exist_ok=True)
np.savez_compressed(jn(part_save_dir, str(k).zfill(6) + '.npz'),
extended_word_seq=extended_word_seq,
vec_seq=vec_seq,
audio=np.int16(audio / audio_max_all[k] * 32767),
audio_max=audio_max_all[k],
mfcc_features=mfcc_features,
vid_indices=vid_indices_all[k])
print('\rCaching {} data {:>6}/{}.'.format(part, k + 1, num_samples), end='')
print('\t Storing full cache', end='')
full_cache_path = jn(dir_name, '../full')
os.makedirs(full_cache_path, exist_ok=True)
np.savez_compressed(jn(full_cache_path, part + '.npz'),
extended_word_seq=extended_word_seq_all,
vec_seq=vec_seq_all, audio=audio_all, audio_max=audio_max_all,
mfcc_features=mfcc_features_all,
vid_indices=vid_indices_all)
print(' done.')
def process_data(self, data, poses, quat, trans, affs):
data = data.float().to(self.device)
poses = poses.float().to(self.device)
quat = quat.float().to(self.device)
trans = trans.float().to(self.device)
affs = affs.float().to(self.device)
return data, poses, quat, trans, affs
def load_model_at_epoch(self, epoch='best'):
model_name, self.best_s2ag_loss_epoch, self.best_s2ag_loss = \
get_epoch_and_loss(self.args.work_dir_s2ag, epoch=epoch)
model_found = False
try:
loaded_vars = torch.load(jn(self.args.work_dir_s2ag, model_name))
self.s2ag_generator.load_state_dict(loaded_vars['gen_model_dict'])
self.s2ag_discriminator.load_state_dict(loaded_vars['dis_model_dict'])
model_found = True
except (FileNotFoundError, IsADirectoryError):
if epoch == 'best':
print('Warning! No saved model found.')
else:
print('Warning! No saved model found at epoch {}.'.format(epoch))
return model_found
def adjust_lr_s2ag(self):
self.lr_s2ag_gen = self.lr_s2ag_gen * self.args.lr_s2ag_decay
for param_group in self.s2ag_gen_optimizer.param_groups:
param_group['lr'] = self.lr_s2ag_gen
self.lr_s2ag_dis = self.lr_s2ag_dis * self.args.lr_s2ag_decay
for param_group in self.s2ag_dis_optimizer.param_groups:
param_group['lr'] = self.lr_s2ag_dis
def show_epoch_info(self):
best_metrics = [self.best_s2ag_loss]
print_epochs = [self.best_s2ag_loss_epoch
if self.best_s2ag_loss_epoch is not None else 0] * len(best_metrics)
i = 0
for k, v in self.epoch_info.items():
self.io.print_log('\t{}: {}. Best so far: {:.4f} (epoch: {:d}).'.
format(k, v, best_metrics[i], print_epochs[i]))
i += 1
if self.args.pavi_log:
self.io.log('train', self.meta_info['iter'], self.epoch_info)
def show_iter_info(self):
if self.meta_info['iter'] % self.args.log_interval == 0:
info = '\tIter {} Done.'.format(self.meta_info['iter'])
for k, v in self.iter_info.items():
if isinstance(v, float):
info = info + ' | {}: {:.4f}'.format(k, v)
else:
info = info + ' | {}: {}'.format(k, v)
self.io.print_log(info)
if self.args.pavi_log:
self.io.log('train', self.meta_info['iter'], self.iter_info)
def count_parameters(self):
return sum(p.numel() for p in self.s2ag_generator.parameters() if p.requires_grad)
@staticmethod
def extend_word_seq(n_frames, lang, remove_word_timing, words, aux_info, end_time=None):
if end_time is None:
end_time = aux_info['end_time']
frame_duration = (end_time - aux_info['start_time']) / n_frames
extended_word_indices = np.zeros(n_frames) # zero is the index of padding token
if remove_word_timing:
n_words = 0
for word in words:
idx = max(0, int(np.floor((word[1] - aux_info['start_time']) / frame_duration)))
if idx < n_frames:
n_words += 1
space = int(n_frames / (n_words + 1))
for word_idx in range(n_words):
idx = (word_idx + 1) * space
extended_word_indices[idx] = lang.get_word_index(words[word_idx][0])
else:
prev_idx = 0
for word in words:
idx = max(0, int(np.floor((word[1] - aux_info['start_time']) / frame_duration)))
if idx < n_frames:
extended_word_indices[idx] = lang.get_word_index(word[0])
# extended_word_indices[prev_idx:idx+1] = lang.get_word_index(word[0])
prev_idx = idx
return torch.Tensor(extended_word_indices).long()
@staticmethod
def words_to_tensor(lang, words, end_time=None):
indexes = [lang.SOS_token]
for word in words:
if end_time is not None and word[1] > end_time:
break
indexes.append(lang.get_word_index(word[0]))
indexes.append(lang.EOS_token)
return torch.Tensor(indexes).long()
def yield_batch_old(self, train):
batch_word_seq_tensor = torch.zeros((self.args.batch_size, self.time_steps)).long().to(self.device)
batch_word_seq_lengths = torch.zeros(self.args.batch_size).long().to(self.device)
batch_extended_word_seq = torch.zeros((self.args.batch_size, self.time_steps)).long().to(self.device)
batch_pose_seq = torch.zeros((self.args.batch_size, self.time_steps,
self.pose_dim + self.coords)).float().to(self.device)
batch_vec_seq = torch.zeros((self.args.batch_size, self.time_steps, self.pose_dim)).float().to(self.device)
batch_audio = torch.zeros((self.args.batch_size, self.audio_length)).float().to(self.device)
batch_spectrogram = torch.zeros((self.args.batch_size, 128,
self.spectrogram_length)).float().to(self.device)
batch_mfcc = torch.zeros((self.args.batch_size, self.num_mfcc,
self.mfcc_length)).float().to(self.device)
batch_vid_indices = torch.zeros(self.args.batch_size).long().to(self.device)
if train:
data_s2ag = self.data_loader['train_data_s2ag']
num_data = self.num_train_samples
else:
data_s2ag = self.data_loader['val_data_s2ag']
num_data = self.num_val_samples
pseudo_passes = (num_data + self.args.batch_size - 1) // self.args.batch_size
prob_dist = np.ones(num_data) / float(num_data)
# def load_from_txn(_txn, _i, _k):
# key = '{:010}'.format(_k).encode('ascii')
# sample = _txn.get(key)
# sample = pyarrow.deserialize(sample)
# word_seq, pose_seq, vec_seq, audio, spectrogram, mfcc_features, aux_info = sample
#
# # vid_name = sample[-1]['vid']
# # clip_start = str(sample[-1]['start_time'])
# # clip_end = str(sample[-1]['end_time'])
#
# duration = aux_info['end_time'] - aux_info['start_time']
# do_clipping = True
#
# if do_clipping:
# sample_end_time = aux_info['start_time'] + duration * data_s2ag.n_poses / vec_seq.shape[0]
# audio = make_audio_fixed_length(audio, self.audio_length)
# spectrogram = spectrogram[:, 0:self.spectrogram_length]
# mfcc_features = mfcc_features[:, 0:self.mfcc_length]
# vec_seq = vec_seq[0:data_s2ag.n_poses]
# pose_seq = pose_seq[0:data_s2ag.n_poses]
# else:
# sample_end_time = None
#
# # to tensors
# word_seq_tensor = Processor.words_to_tensor(data_s2ag.lang_model, word_seq, sample_end_time)
# extended_word_seq = Processor.extend_word_seq(data_s2ag.n_poses, data_s2ag.lang_model,
# data_s2ag.remove_word_timing, word_seq,
# aux_info, sample_end_time)
# vec_seq = torch.from_numpy(vec_seq).reshape((vec_seq.shape[0], -1)).float()
# pose_seq = torch.from_numpy(pose_seq).reshape((pose_seq.shape[0], -1)).float()
# # scaled_audio = np.int16(audio / np.max(np.abs(audio)) * self.audio_length)
# mfcc_features = torch.from_numpy(mfcc_features).float()
# audio = torch.from_numpy(audio).float()
# spectrogram = torch.from_numpy(spectrogram)
#
# batch_word_seq_tensor[_i, :len(word_seq_tensor)] = word_seq_tensor
# batch_word_seq_lengths[_i] = len(word_seq_tensor)
# batch_extended_word_seq[_i] = extended_word_seq
# batch_pose_seq[_i] = pose_seq
# batch_vec_seq[_i] = vec_seq
# batch_audio[_i] = audio
# batch_spectrogram[_i] = spectrogram
# batch_mfcc[_i] = mfcc_features
# # speaker input
# if train:
# if self.train_speaker_model and self.train_speaker_model.__class__.__name__ == 'Vocab':
# batch_vid_indices[_i] = \
# torch.LongTensor([self.train_speaker_model.word2index[aux_info['vid']]])
# else:
# if self.val_speaker_model and self.val_speaker_model.__class__.__name__ == 'Vocab':
# batch_vid_indices[_i] = \
# torch.LongTensor([self.val_speaker_model.word2index[aux_info['vid']]])
for p in range(pseudo_passes):
rand_keys = np.random.choice(num_data, size=self.args.batch_size, replace=True, p=prob_dist)
for i, k in enumerate(rand_keys):
if train:
word_seq = self.train_samples['word_seq'].item()[str(k).zfill(6)]
pose_seq = self.train_samples['pose_seq'][k]
vec_seq = self.train_samples['vec_seq'][k]
audio = self.train_samples['audio'][k] / 32767 * self.train_samples['audio_max'][k]
mfcc_features = self.train_samples['mfcc_features'][k]
aux_info = self.train_samples['aux_info'].item()[str(k).zfill(6)]
else:
word_seq = self.val_samples['word_seq'].item()[str(k).zfill(6)]
pose_seq = self.val_samples['pose_seq'][k]
vec_seq = self.val_samples['vec_seq'][k]
audio = self.val_samples['audio'][k] / 32767 * self.val_samples['audio_max'][k]
mfcc_features = self.val_samples['mfcc_features'][k]
aux_info = self.val_samples['aux_info'].item()[str(k).zfill(6)]
duration = aux_info['end_time'] - aux_info['start_time']
do_clipping = True
if do_clipping:
sample_end_time = aux_info['start_time'] + duration * data_s2ag.n_poses / vec_seq.shape[0]
audio = make_audio_fixed_length(audio, self.audio_length)
mfcc_features = mfcc_features[:, 0:self.mfcc_length]
vec_seq = vec_seq[0:data_s2ag.n_poses]
pose_seq = pose_seq[0:data_s2ag.n_poses]
else:
sample_end_time = None
# to tensors
word_seq_tensor = Processor.words_to_tensor(data_s2ag.lang_model, word_seq, sample_end_time)
extended_word_seq = Processor.extend_word_seq(data_s2ag.n_poses, data_s2ag.lang_model,
data_s2ag.remove_word_timing, word_seq,
aux_info, sample_end_time)
vec_seq = torch.from_numpy(vec_seq).reshape((vec_seq.shape[0], -1)).float()
pose_seq = torch.from_numpy(pose_seq).reshape((pose_seq.shape[0], -1)).float()
# scaled_audio = np.int16(audio / np.max(np.abs(audio)) * self.audio_length)
mfcc_features = torch.from_numpy(mfcc_features).float()
audio = torch.from_numpy(audio).float()
batch_word_seq_tensor[i, :len(word_seq_tensor)] = word_seq_tensor
batch_word_seq_lengths[i] = len(word_seq_tensor)
batch_extended_word_seq[i] = extended_word_seq
batch_pose_seq[i] = pose_seq
batch_vec_seq[i] = vec_seq
batch_audio[i] = audio
batch_mfcc[i] = mfcc_features
# speaker input
if train:
if self.train_speaker_model and self.train_speaker_model.__class__.__name__ == 'Vocab':
batch_vid_indices[i] = \
torch.LongTensor([self.train_speaker_model.word2index[aux_info['vid']]])
else:
if self.val_speaker_model and self.val_speaker_model.__class__.__name__ == 'Vocab':
batch_vid_indices[i] = \
torch.LongTensor([self.val_speaker_model.word2index[aux_info['vid']]])
# with data_s2ag.lmdb_env.begin(write=False) as txn:
# threads = []
# for i, k in enumerate(rand_keys):
# threads.append(threading.Thread(target=load_from_txn, args=[i, k]))
# threads[i].start()
# for i in range(len(rand_keys)):
# threads[i].join()
yield batch_word_seq_tensor, batch_word_seq_lengths, batch_extended_word_seq, batch_pose_seq, \
batch_vec_seq, batch_audio, batch_spectrogram, batch_mfcc, batch_vid_indices
def yield_batch(self, train):
if train:
data_s2ag = self.data_loader['train_data_s2ag']
num_data = self.num_train_samples
else:
data_s2ag = self.data_loader['val_data_s2ag']
num_data = self.num_val_samples
pseudo_passes = (num_data + self.args.batch_size - 1) // self.args.batch_size
prob_dist = np.ones(num_data) / float(num_data)
for p in range(pseudo_passes):
rand_keys = np.random.choice(num_data, size=self.args.batch_size, replace=True, p=prob_dist)
if train:
batch_extended_word_seq = torch.from_numpy(
self.train_samples['extended_word_seq'][rand_keys]).to(self.device)
batch_vec_seq = torch.from_numpy(self.train_samples['vec_seq'][rand_keys]).float().to(self.device)
batch_audio = torch.from_numpy(
self.train_samples['audio'][rand_keys] *
self.train_samples['audio_max'][rand_keys, None] / 32767).float().to(self.device)
batch_mfcc_features = torch.from_numpy(
self.train_samples['mfcc_features'][rand_keys]).float().to(self.device)
curr_vid_indices = self.train_samples['vid_indices'][rand_keys]
else:
batch_extended_word_seq = torch.from_numpy(
self.val_samples['extended_word_seq'][rand_keys]).to(self.device)
batch_vec_seq = torch.from_numpy(self.val_samples['vec_seq'][rand_keys]).float().to(self.device)
batch_audio = torch.from_numpy(
self.val_samples['audio'][rand_keys] *
self.val_samples['audio_max'][rand_keys, None] / 32767).float().to(self.device)
batch_mfcc_features = torch.from_numpy(
self.val_samples['mfcc_features'][rand_keys]).float().to(self.device)
curr_vid_indices = self.val_samples['vid_indices'][rand_keys]
# speaker input
batch_vid_indices = None
if train and self.train_speaker_model and\
self.train_speaker_model.__class__.__name__ == 'Vocab':
batch_vid_indices = torch.LongTensor([
np.random.choice(np.setdiff1d(list(self.train_speaker_model.word2index.values()),
curr_vid_indices))
for _ in range(self.args.batch_size)]).to(self.device)
elif self.val_speaker_model and\
self.val_speaker_model.__class__.__name__ == 'Vocab':
batch_vid_indices = torch.LongTensor([
np.random.choice(np.setdiff1d(list(self.val_speaker_model.word2index.values()),
curr_vid_indices))
for _ in range(self.args.batch_size)]).to(self.device)
yield batch_extended_word_seq, batch_vec_seq, batch_audio, batch_mfcc_features, batch_vid_indices
def return_batch(self, batch_size, randomized=True):
data_s2ag = self.data_loader['test_data_s2ag']
if len(batch_size) > 1:
rand_keys = np.copy(batch_size)
batch_size = len(batch_size)
else:
batch_size = batch_size[0]
prob_dist = np.ones(self.num_test_samples) / float(self.num_test_samples)
if randomized:
rand_keys = np.random.choice(self.num_test_samples, size=batch_size, replace=False, p=prob_dist)
else:
rand_keys = np.arange(batch_size)
batch_words = [[] for _ in range(batch_size)]
batch_aux_info = [[] for _ in range(batch_size)]
batch_word_seq_tensor = torch.zeros((batch_size, self.time_steps)).long().to(self.device)
batch_word_seq_lengths = torch.zeros(batch_size).long().to(self.device)
batch_extended_word_seq = torch.zeros((batch_size, self.time_steps)).long().to(self.device)
batch_pose_seq = torch.zeros((batch_size, self.time_steps,
self.pose_dim + self.coords)).float().to(self.device)
batch_vec_seq = torch.zeros((batch_size, self.time_steps, self.pose_dim)).float().to(self.device)
batch_target_seq = torch.zeros((batch_size, self.time_steps, self.pose_dim)).float().to(self.device)
batch_audio = torch.zeros((batch_size, self.audio_length)).float().to(self.device)
batch_spectrogram = torch.zeros((batch_size, 128,
self.spectrogram_length)).float().to(self.device)
batch_mfcc = torch.zeros((batch_size, self.num_mfcc,
self.mfcc_length)).float().to(self.device)
for i, k in enumerate(rand_keys):
with data_s2ag.lmdb_env.begin(write=False) as txn:
key = '{:010}'.format(k).encode('ascii')
sample = txn.get(key)
sample = pyarrow.deserialize(sample)
word_seq, pose_seq, vec_seq, audio, spectrogram, mfcc_features, aux_info = sample
# for selected_vi in range(len(word_seq)): # make start time of input text zero
# word_seq[selected_vi][1] -= aux_info['start_time'] # start time
# word_seq[selected_vi][2] -= aux_info['start_time'] # end time
batch_words[i] = [word_seq[i][0] for i in range(len(word_seq))]
batch_aux_info[i] = aux_info
duration = aux_info['end_time'] - aux_info['start_time']
do_clipping = True
if do_clipping:
sample_end_time = aux_info['start_time'] + duration * data_s2ag.n_poses / vec_seq.shape[0]
audio = make_audio_fixed_length(audio, self.audio_length)
spectrogram = spectrogram[:, 0:self.spectrogram_length]
mfcc_features = mfcc_features[:, 0:self.mfcc_length]
vec_seq = vec_seq[0:data_s2ag.n_poses]
pose_seq = pose_seq[0:data_s2ag.n_poses]
else:
sample_end_time = None
# to tensors
word_seq_tensor = Processor.words_to_tensor(data_s2ag.lang_model, word_seq, sample_end_time)
extended_word_seq = Processor.extend_word_seq(data_s2ag.n_poses, data_s2ag.lang_model,
data_s2ag.remove_word_timing, word_seq,
aux_info, sample_end_time)
vec_seq = torch.from_numpy(vec_seq).reshape((vec_seq.shape[0], -1)).float()
pose_seq = torch.from_numpy(pose_seq).reshape((pose_seq.shape[0], -1)).float()
target_seq = convert_pose_seq_to_dir_vec(pose_seq)
target_seq = target_seq.reshape(target_seq.shape[0], -1)
target_seq -= np.reshape(self.s2ag_config_args.mean_dir_vec, -1)
mfcc_features = torch.from_numpy(mfcc_features)
audio = torch.from_numpy(audio).float()
spectrogram = torch.from_numpy(spectrogram)
batch_word_seq_tensor[i, :len(word_seq_tensor)] = word_seq_tensor
batch_word_seq_lengths[i] = len(word_seq_tensor)
batch_extended_word_seq[i] = extended_word_seq
batch_pose_seq[i] = pose_seq
batch_vec_seq[i] = vec_seq
batch_target_seq[i] = torch.from_numpy(target_seq).float()
batch_audio[i] = audio
batch_spectrogram[i] = spectrogram
batch_mfcc[i] = mfcc_features
# speaker input
# if self.test_speaker_model and self.test_speaker_model.__class__.__name__ == 'Vocab':
# batch_vid_indices[i] = \
# torch.LongTensor([self.test_speaker_model.word2index[aux_info['vid']]])
batch_vid_indices = torch.LongTensor(
[np.random.choice(list(self.test_speaker_model.word2index.values()))
for _ in range(batch_size)]).to(self.device)
return batch_words, batch_aux_info, batch_word_seq_tensor, batch_word_seq_lengths, \
batch_extended_word_seq, batch_pose_seq, batch_vec_seq, batch_target_seq, batch_audio, \
batch_spectrogram, batch_mfcc, batch_vid_indices
@staticmethod
def add_noise(data):
noise = torch.randn_like(data) * 0.1
return data + noise
@staticmethod
def push_samples(evaluator, target, out_dir_vec, in_text_padded, in_audio,
losses_all, joint_mae, accel, mean_dir_vec, n_poses, n_pre_poses):
batch_size = len(target)
# if evaluator:
# evaluator.reset()
loss = F.l1_loss(out_dir_vec, target)
losses_all.update(loss.item(), batch_size)
if evaluator:
evaluator.push_samples(in_text_padded, in_audio, out_dir_vec, target)
# calculate MAE of joint coordinates
out_dir_vec_np = out_dir_vec.detach().cpu().numpy()
out_dir_vec_np += np.array(mean_dir_vec).squeeze()
out_joint_poses = convert_dir_vec_to_pose(out_dir_vec_np)
target_vec = target.detach().cpu().numpy()
target_vec += np.array(mean_dir_vec).squeeze()
target_poses = convert_dir_vec_to_pose(target_vec)
if out_joint_poses.shape[1] == n_poses:
diff = out_joint_poses[:, n_pre_poses:] - \
target_poses[:, n_pre_poses:]
else:
diff = out_joint_poses - target_poses[:, n_pre_poses:]
mae_val = np.mean(np.absolute(diff))
joint_mae.update(mae_val, batch_size)
# accel
target_acc = np.diff(target_poses, n=2, axis=1)
out_acc = np.diff(out_joint_poses, n=2, axis=1)
accel.update(np.mean(np.abs(target_acc - out_acc)), batch_size)
return evaluator, losses_all, joint_mae, accel
def forward_pass_s2ag(self, in_text, in_audio, in_mfcc, target_poses, vid_indices, train,
target_seq=None, words=None, aux_info=None, save_path=None, make_video=False,
calculate_metrics=False, losses_all_trimodal=None, joint_mae_trimodal=None,
accel_trimodal=None, losses_all=None, joint_mae=None, accel=None):
warm_up_epochs = self.s2ag_config_args.loss_warmup
use_noisy_target = False
# make pre seq input
pre_seq = target_poses.new_zeros((target_poses.shape[0], target_poses.shape[1],
target_poses.shape[2] + 1))
pre_seq[:, 0:self.s2ag_config_args.n_pre_poses, :-1] =\
target_poses[:, 0:self.s2ag_config_args.n_pre_poses]
pre_seq[:, 0:self.s2ag_config_args.n_pre_poses, -1] = 1 # indicating bit for constraints
###########################################################################################
# train D
dis_error = None
if self.meta_info['epoch'] > warm_up_epochs and self.s2ag_config_args.loss_gan_weight > 0.0:
self.s2ag_dis_optimizer.zero_grad()
# out shape (batch x seq x dim)
if self.use_mfcc:
out_dir_vec, *_ = self.s2ag_generator(pre_seq, in_text, in_mfcc, vid_indices)
else:
out_dir_vec, *_ = self.s2ag_generator(pre_seq, in_text, in_audio, vid_indices)
if use_noisy_target:
noise_target = Processor.add_noise(target_poses)
noise_out = Processor.add_noise(out_dir_vec.detach())
dis_real = self.s2ag_discriminator(noise_target, in_text)
dis_fake = self.s2ag_discriminator(noise_out, in_text)
else:
dis_real = self.s2ag_discriminator(target_poses, in_text)
dis_fake = self.s2ag_discriminator(out_dir_vec.detach(), in_text)
dis_error = torch.sum(-torch.mean(torch.log(dis_real + 1e-8) + torch.log(1 - dis_fake + 1e-8))) # ns-gan
if train:
dis_error.backward()
self.s2ag_dis_optimizer.step()
###########################################################################################
# train G
self.s2ag_gen_optimizer.zero_grad()
# decoding
out_dir_vec_trimodal, *_ = self.trimodal_generator(pre_seq, in_text, in_audio, vid_indices)
if self.use_mfcc:
out_dir_vec, z, z_mu, z_log_var = self.s2ag_generator(pre_seq, in_text, in_mfcc, vid_indices)
else:
out_dir_vec, z, z_mu, z_log_var = self.s2ag_generator(pre_seq, in_text, in_audio, vid_indices)
# make a video
assert not make_video or (make_video and target_seq is not None), \
'target_seq cannot be None when make_video is True'
assert not make_video or (make_video and words is not None), \
'words cannot be None when make_video is True'
assert not make_video or (make_video and aux_info is not None), \
'aux_info cannot be None when make_video is True'
assert not make_video or (make_video and save_path is not None), \
'save_path cannot be None when make_video is True'
if make_video:
sentence_words = []
for word in words:
sentence_words.append(word)
sentences = [' '.join(sentence_word) for sentence_word in sentence_words]
num_videos = len(aux_info)
for vid_idx in range(num_videos):
start_time = time.time()
filename_prefix = '{}_{}'.format(aux_info[vid_idx]['vid'], vid_idx)
filename_prefix_for_video = filename_prefix
aux_str = '({}, time: {}-{})'.format(aux_info[vid_idx]['vid'],
str(datetime.timedelta(
seconds=aux_info[vid_idx]['start_time'])),
str(datetime.timedelta(
seconds=aux_info[vid_idx]['end_time'])))
create_video_and_save(
save_path, 0, filename_prefix_for_video, 0,
target_seq[vid_idx].cpu().numpy(),
out_dir_vec_trimodal[vid_idx].cpu().numpy(), out_dir_vec[vid_idx].cpu().numpy(),
np.reshape(self.s2ag_config_args.mean_dir_vec, -1), sentences[vid_idx],
audio=in_audio[vid_idx].cpu().numpy(), aux_str=aux_str,
clipping_to_shortest_stream=True, delete_audio_file=False)
print('\rRendered {} of {} videos. Last one took {:.2f} seconds.'.format(vid_idx + 1,
num_videos,
time.time() - start_time),
end='')
print()
# calculate metrics
assert not calculate_metrics or (calculate_metrics and target_seq is not None), \
'target_seq cannot be None when calculate_metrics is True'
assert not calculate_metrics or (calculate_metrics and losses_all_trimodal is not None), \
'losses_all_trimodal cannot be None when calculate_metrics is True'
assert not calculate_metrics or (calculate_metrics and joint_mae_trimodal is not None), \
'joint_mae_trimodal cannot be None when calculate_metrics is True'
assert not calculate_metrics or (calculate_metrics and accel_trimodal is not None), \
'accel_trimodal cannot be None when calculate_metrics is True'
assert not calculate_metrics or (calculate_metrics and losses_all is not None), \
'losses_all cannot be None when calculate_metrics is True'
assert not calculate_metrics or (calculate_metrics and joint_mae is not None), \
'joint_mae cannot be None when calculate_metrics is True'
assert not calculate_metrics or (calculate_metrics and accel is not None), \
'accel cannot be None when calculate_metrics is True'
if calculate_metrics:
self.evaluator_trimodal, losses_all_trimodal, joint_mae_trimodal, accel_trimodal =\
Processor.push_samples(self.evaluator_trimodal, target_seq, out_dir_vec_trimodal,
in_text, in_audio, losses_all_trimodal, joint_mae_trimodal, accel_trimodal,
self.s2ag_config_args.mean_dir_vec, self.s2ag_config_args.n_poses,
self.s2ag_config_args.n_pre_poses)
self.evaluator, losses_all, joint_mae, accel =\
Processor.push_samples(self.evaluator, target_seq, out_dir_vec,
in_text, in_audio, losses_all, joint_mae, accel,
self.s2ag_config_args.mean_dir_vec, self.s2ag_config_args.n_poses,
self.s2ag_config_args.n_pre_poses)
# loss
beta = 0.1
huber_loss = F.smooth_l1_loss(out_dir_vec / beta, target_poses / beta) * beta
dis_output = self.s2ag_discriminator(out_dir_vec, in_text)
gen_error = -torch.mean(torch.log(dis_output + 1e-8))
kld = div_reg = None
if (self.s2ag_config_args.z_type == 'speaker' or self.s2ag_config_args.z_type == 'random') and \
self.s2ag_config_args.loss_reg_weight > 0.0:
if self.s2ag_config_args.z_type == 'speaker':
# enforcing divergent gestures btw original vid and other vid
rand_idx = torch.randperm(vid_indices.shape[0])
rand_vids = vid_indices[rand_idx]
else:
rand_vids = None
if self.use_mfcc:
out_dir_vec_rand_vid, z_rand_vid, _, _ = self.s2ag_generator(pre_seq, in_text, in_mfcc, rand_vids)
else:
out_dir_vec_rand_vid, z_rand_vid, _, _ = self.s2ag_generator(pre_seq, in_text, in_audio, rand_vids)
beta = 0.05
pose_l1 = F.smooth_l1_loss(out_dir_vec / beta, out_dir_vec_rand_vid.detach() / beta,
reduction='none') * beta
pose_l1 = pose_l1.sum(dim=1).sum(dim=1)
pose_l1 = pose_l1.view(pose_l1.shape[0], -1).mean(1)
z_l1 = F.l1_loss(z.detach(), z_rand_vid.detach(), reduction='none')
z_l1 = z_l1.view(z_l1.shape[0], -1).mean(1)
div_reg = -(pose_l1 / (z_l1 + 1.0e-5))
div_reg = torch.clamp(div_reg, min=-1000)
div_reg = div_reg.mean()
if self.s2ag_config_args.z_type == 'speaker':
# speaker embedding KLD
kld = -0.5 * torch.mean(1 + z_log_var - z_mu.pow(2) - z_log_var.exp())
loss = self.s2ag_config_args.loss_regression_weight * huber_loss + \
self.s2ag_config_args.loss_kld_weight * kld + \
self.s2ag_config_args.loss_reg_weight * div_reg
else:
loss = self.s2ag_config_args.loss_regression_weight * huber_loss + \
self.s2ag_config_args.loss_reg_weight * div_reg
else:
loss = self.s2ag_config_args.loss_regression_weight * huber_loss # + var_loss
if self.meta_info['epoch'] > warm_up_epochs:
loss += self.s2ag_config_args.loss_gan_weight * gen_error
if train:
loss.backward()
self.s2ag_gen_optimizer.step()
loss_dict = {'loss': self.s2ag_config_args.loss_regression_weight * huber_loss.item()}
if kld:
loss_dict['KLD'] = self.s2ag_config_args.loss_kld_weight * kld.item()
if div_reg:
loss_dict['DIV_REG'] = self.s2ag_config_args.loss_reg_weight * div_reg.item()
if self.meta_info['epoch'] > warm_up_epochs and self.s2ag_config_args.loss_gan_weight > 0.0:
loss_dict['gen'] = self.s2ag_config_args.loss_gan_weight * gen_error.item()
loss_dict['dis'] = dis_error.item()
# total_loss = 0.
# for loss in loss_dict.keys():
# total_loss += loss_dict[loss]
# return loss_dict, losses_all_trimodal, joint_mae_trimodal, accel_trimodal, losses_all, joint_mae, accel
return F.l1_loss(out_dir_vec, target_poses).item() - F.l1_loss(out_dir_vec_trimodal, target_poses).item(),\
losses_all_trimodal, joint_mae_trimodal, accel_trimodal, losses_all, joint_mae, accel
def per_train_epoch(self):
self.s2ag_generator.train()
self.s2ag_discriminator.train()
batch_s2ag_loss = 0.
num_batches = self.num_train_samples // self.args.batch_size + 1
start_time = time.time()
self.meta_info['iter'] = 0
for extended_word_seq, vec_seq, audio,\
mfcc_features, vid_indices in self.yield_batch(train=True):
loss, *_ = self.forward_pass_s2ag(extended_word_seq, audio, mfcc_features,
vec_seq, vid_indices, train=True)
# Compute statistics
batch_s2ag_loss += loss
self.iter_info['s2ag_loss'] = loss
self.iter_info['lr_gen'] = '{}'.format(self.lr_s2ag_gen)
self.iter_info['lr_dis'] = '{}'.format(self.lr_s2ag_dis)
self.show_iter_info()
self.meta_info['iter'] += 1
print('\riter {:>3}/{} took {:>4} seconds\t'.
format(self.meta_info['iter'], num_batches, int(np.ceil(time.time() - start_time))), end='')
batch_s2ag_loss /= num_batches
self.epoch_info['mean_s2ag_loss'] = batch_s2ag_loss
self.show_epoch_info()
self.io.print_timer()
# self.adjust_lr_s2ag()
def per_val_epoch(self):
self.s2ag_generator.eval()
self.s2ag_discriminator.eval()
batch_s2ag_loss = 0.
num_batches = self.num_val_samples // self.args.batch_size + 1
start_time = time.time()