-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtrainer_chois.py
3192 lines (2487 loc) · 163 KB
/
trainer_chois.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 argparse
import os
import numpy as np
import yaml
import random
import json
import copy
import trimesh
from matplotlib import pyplot as plt
from pathlib import Path
import wandb
import torch
from torch.optim import Adam
from torch.cuda.amp import autocast, GradScaler
from torch.utils import data
import torch.nn.functional as F
import pytorch3d.transforms as transforms
from ema_pytorch import EMA
from manip.data.cano_traj_dataset import CanoObjectTrajDataset, quat_ik_torch, quat_fk_torch
from manip.data.long_cano_traj_dataset import LongCanoObjectTrajDataset
from manip.data.unseen_obj_long_cano_traj_dataset import UnseenCanoObjectTrajDataset
from manip.model.transformer_object_motion_cond_diffusion import ObjectCondGaussianDiffusion
from manip.vis.blender_vis_mesh_motion import run_blender_rendering_and_save2video, save_verts_faces_to_mesh_file_w_object
from manip.lafan1.utils import quat_inv, quat_mul, quat_between, normalize, quat_normalize
from evaluation_metrics import compute_metrics, determine_floor_height_and_contacts, compute_metrics_long_seq
import clip
import random
torch.manual_seed(1)
random.seed(1)
def export_to_ply(points, filename='output.ply'):
# Open the file in write mode
with open(filename, 'w') as ply_file:
# Write the PLY header
ply_file.write("ply\n")
ply_file.write("format ascii 1.0\n")
ply_file.write("comment Created by YourProgram\n")
ply_file.write(f"element vertex {len(points)}\n")
ply_file.write("property float x\n")
ply_file.write("property float y\n")
ply_file.write("property float z\n")
ply_file.write("end_header\n")
# Write the points data
for point in points:
ply_file.write(f"{point[0]} {point[1]} {point[2]}\n")
def compute_signed_distances(
sdf, sdf_centroid, sdf_extents,
query_points):
# sdf: 1 X 256 X 256 X 256
# sdf_centroid: 1 X 3, center of the bounding box.
# sdf_extents: 1 X 3, width, height, depth of the box.
# query_points: T X Nv X 3
# query_pts_norm = (query_points - sdf_centroid[None, :, :]) * 2 / sdf_extents[None, :, :] # Convert to range [-1, 1]
query_pts_norm = (query_points - sdf_centroid[None, :, :]) * 2 / sdf_extents.cpu().detach().numpy().max() # Convert to range [-1, 1]
query_pts_norm = query_pts_norm[...,[2, 1, 0]] # Switch the order to depth, height, width
num_steps, nv, _ = query_pts_norm.shape # T X Nv X 3
query_pts_norm = query_pts_norm[None, :, None, :, :] # 1 X T X 1 X Nv X 3
signed_dists = F.grid_sample(sdf[:, None, :, :, :], query_pts_norm, \
padding_mode='border', align_corners=True)
# F.grid_sample: N X C X D_in X H_in X W_in, N X D_out X H_out X W_out X 3, output: N X C X D_out X H_out X W_out
# sdf: 1 X 1 X 256 X 256 X 256, query_pts: 1 X T X 1 X Nv X 3 -> 1 X 1 X T X 1 X Nv
signed_dists = signed_dists[0, 0, :, 0, :] * sdf_extents.cpu().detach().numpy().max() / 2. # T X Nv
return signed_dists
def run_smplx_model(root_trans, aa_rot_rep, betas, gender, bm_dict, return_joints24=True):
# root_trans: BS X T X 3
# aa_rot_rep: BS X T X 22 X 3
# betas: BS X 16
# gender: BS
bs, num_steps, num_joints, _ = aa_rot_rep.shape
if num_joints != 52:
padding_zeros_hand = torch.zeros(bs, num_steps, 30, 3).to(aa_rot_rep.device) # BS X T X 30 X 3
aa_rot_rep = torch.cat((aa_rot_rep, padding_zeros_hand), dim=2) # BS X T X 52 X 3
aa_rot_rep = aa_rot_rep.reshape(bs*num_steps, -1, 3) # (BS*T) X n_joints X 3
betas = betas[:, None, :].repeat(1, num_steps, 1).reshape(bs*num_steps, -1) # (BS*T) X 16
gender = np.asarray(gender)[:, np.newaxis].repeat(num_steps, axis=1)
gender = gender.reshape(-1).tolist() # (BS*T)
smpl_trans = root_trans.reshape(-1, 3) # (BS*T) X 3
smpl_betas = betas # (BS*T) X 16
smpl_root_orient = aa_rot_rep[:, 0, :] # (BS*T) X 3
smpl_pose_body = aa_rot_rep[:, 1:22, :].reshape(-1, 63) # (BS*T) X 63
smpl_pose_hand = aa_rot_rep[:, 22:, :].reshape(-1, 90) # (BS*T) X 90
B = smpl_trans.shape[0] # (BS*T)
smpl_vals = [smpl_trans, smpl_root_orient, smpl_betas, smpl_pose_body, smpl_pose_hand]
# batch may be a mix of genders, so need to carefully use the corresponding SMPL body model
gender_names = ['male', 'female', "neutral"]
pred_joints = []
pred_verts = []
prev_nbidx = 0
cat_idx_map = np.ones((B), dtype=np.int64)*-1
for gender_name in gender_names:
gender_idx = np.array(gender) == gender_name
nbidx = np.sum(gender_idx)
cat_idx_map[gender_idx] = np.arange(prev_nbidx, prev_nbidx + nbidx, dtype=np.int64)
prev_nbidx += nbidx
gender_smpl_vals = [val[gender_idx] for val in smpl_vals]
if nbidx == 0:
# skip if no frames for this gender
continue
# reconstruct SMPL
cur_pred_trans, cur_pred_orient, cur_betas, cur_pred_pose, cur_pred_pose_hand = gender_smpl_vals
bm = bm_dict[gender_name]
pred_body = bm(pose_body=cur_pred_pose, pose_hand=cur_pred_pose_hand, \
betas=cur_betas, root_orient=cur_pred_orient, trans=cur_pred_trans)
pred_joints.append(pred_body.Jtr)
pred_verts.append(pred_body.v)
# cat all genders and reorder to original batch ordering
if return_joints24:
x_pred_smpl_joints_all = torch.cat(pred_joints, axis=0) # () X 52 X 3
lmiddle_index= 28
rmiddle_index = 43
x_pred_smpl_joints = torch.cat((x_pred_smpl_joints_all[:, :22, :], \
x_pred_smpl_joints_all[:, lmiddle_index:lmiddle_index+1, :], \
x_pred_smpl_joints_all[:, rmiddle_index:rmiddle_index+1, :]), dim=1)
else:
x_pred_smpl_joints = torch.cat(pred_joints, axis=0)[:, :num_joints, :]
x_pred_smpl_joints = x_pred_smpl_joints[cat_idx_map] # (BS*T) X 22 X 3
x_pred_smpl_verts = torch.cat(pred_verts, axis=0)
x_pred_smpl_verts = x_pred_smpl_verts[cat_idx_map] # (BS*T) X 6890 X 3
x_pred_smpl_joints = x_pred_smpl_joints.reshape(bs, num_steps, -1, 3) # BS X T X 22 X 3/BS X T X 24 X 3
x_pred_smpl_verts = x_pred_smpl_verts.reshape(bs, num_steps, -1, 3) # BS X T X 6890 X 3
mesh_faces = pred_body.f
return x_pred_smpl_joints, x_pred_smpl_verts, mesh_faces
def cycle(dl):
while True:
for data in dl:
yield data
class Trainer(object):
def __init__(
self,
opt,
diffusion_model,
*,
ema_decay=0.995,
train_batch_size=32,
train_lr=1e-4,
train_num_steps=10000000,
gradient_accumulate_every=2,
amp=False,
step_start_ema=2000,
ema_update_every=10,
save_and_sample_every=40000,
results_folder='./results',
use_wandb=True,
):
super().__init__()
self.use_wandb = use_wandb
if self.use_wandb:
# Loggers
wandb.init(config=opt, project=opt.wandb_pj_name, entity=opt.entity, \
name=opt.exp_name, dir=opt.save_dir)
self.model = diffusion_model
self.ema = EMA(diffusion_model, beta=ema_decay, update_every=ema_update_every)
self.step_start_ema = step_start_ema
self.save_and_sample_every = save_and_sample_every
self.batch_size = train_batch_size
self.gradient_accumulate_every = gradient_accumulate_every
self.train_num_steps = train_num_steps
self.optimizer = Adam(diffusion_model.parameters(), lr=train_lr)
self.step = 0
self.amp = amp
self.scaler = GradScaler(enabled=amp)
self.results_folder = results_folder
self.vis_folder = results_folder.replace("weights", "vis_res")
self.opt = opt
self.window = opt.window
self.add_language_condition = self.opt.add_language_condition
self.use_random_frame_bps = self.opt.use_random_frame_bps
self.use_object_keypoints = self.opt.use_object_keypoints
self.add_semantic_contact_labels = self.opt.add_semantic_contact_labels
self.test_unseen_objects = self.opt.test_unseen_objects
self.save_res_folder = self.opt.save_res_folder
self.use_object_split = self.opt.use_object_split
self.data_root_folder = self.opt.data_root_folder
self.prep_dataloader(window_size=opt.window)
self.bm_dict = self.ds.bm_dict
self.test_on_train = self.opt.test_on_train
self.input_first_human_pose = self.opt.input_first_human_pose
self.use_guidance_in_denoising = self.opt.use_guidance_in_denoising
self.compute_metrics = self.opt.compute_metrics
self.loss_w_feet = self.opt.loss_w_feet
self.loss_w_fk = self.opt.loss_w_fk
self.loss_w_obj_pts = self.opt.loss_w_obj_pts
if self.add_language_condition:
clip_version = 'ViT-B/32'
self.clip_model = self.load_and_freeze_clip(clip_version)
self.use_long_planned_path = self.opt.use_long_planned_path
self.test_object_name = self.opt.test_object_name
self.test_scene_name = self.opt.test_scene_name
if self.use_long_planned_path:
self.whole_seq_ds = LongCanoObjectTrajDataset(train=False, data_root_folder=self.data_root_folder, \
window=opt.window, use_object_splits=self.use_object_split, \
input_language_condition=self.add_language_condition, \
use_first_frame_bps=False, use_random_frame_bps=self.use_random_frame_bps, \
test_object_name=self.test_object_name)
self.scene_sdf, self.scene_sdf_centroid, self.scene_sdf_extents = \
self.load_scene_sdf_data(self.test_scene_name)
self.hand_vertex_idxs, self.left_hand_vertex_idxs, self.right_hand_vertex_idxs = self.load_hand_vertex_ids()
if self.test_unseen_objects:
if self.use_long_planned_path:
test_long_seq = True
else:
test_long_seq = False
self.unseen_seq_ds = UnseenCanoObjectTrajDataset(train=False, \
data_root_folder=self.data_root_folder, \
window=opt.window, use_object_splits=self.use_object_split, \
input_language_condition=self.add_language_condition, \
use_first_frame_bps=False, \
use_random_frame_bps=self.use_random_frame_bps, \
test_long_seq=test_long_seq)
def load_hand_vertex_ids(self):
data_folder = "data/part_vert_ids"
left_hand_npy_path = os.path.join(data_folder, "left_hand_vids.npy")
right_hand_npy_path = os.path.join(data_folder, "right_hand_vids.npy")
left_hand_vids = np.load(left_hand_npy_path)
right_hand_vids = np.load(right_hand_npy_path)
hand_vids = np.concatenate((left_hand_vids, right_hand_vids), axis=0)
return hand_vids, left_hand_vids, right_hand_vids
def load_scene_sdf_data(self, scene_name):
data_folder = os.path.join(self.data_root_folder, "replica_processed/replica_fixed_poisson_sdfs_res256")
sdf_npy_path = os.path.join(data_folder, scene_name+"_sdf.npy")
sdf_json_path = os.path.join(data_folder, scene_name+"_sdf_info.json")
sdf = np.load(sdf_npy_path) # 256 X 256 X 256
sdf_json_data = json.load(open(sdf_json_path, 'r'))
sdf_centroid = np.asarray(sdf_json_data['centroid']) # a list with 3 items -> 3
sdf_extents = np.asarray(sdf_json_data['extents']) # a list with 3 items -> 3
sdf = torch.from_numpy(sdf).float()[None].cuda()
sdf_centroid = torch.from_numpy(sdf_centroid).float()[None].cuda()
sdf_extents = torch.from_numpy(sdf_extents).float()[None].cuda()
return sdf, sdf_centroid, sdf_extents
def load_object_sdf_data(self, object_name):
if self.test_unseen_objects:
data_folder = os.path.join(self.data_root_folder, "unseen_objects_data/selected_rotated_zeroed_obj_sdf_256_npy_files")
sdf_npy_path = os.path.join(data_folder, object_name+".npy")
sdf_json_path = os.path.join(data_folder, object_name+".json")
else:
data_folder = os.path.join(self.data_root_folder, "rest_object_sdf_256_npy_files")
sdf_npy_path = os.path.join(data_folder, object_name+".ply.npy")
sdf_json_path = os.path.join(data_folder, object_name+".ply.json")
sdf = np.load(sdf_npy_path) # 256 X 256 X 256
sdf_json_data = json.load(open(sdf_json_path, 'r'))
sdf_centroid = np.asarray(sdf_json_data['centroid']) # a list with 3 items -> 3
sdf_extents = np.asarray(sdf_json_data['extents']) # a list with 3 items -> 3
sdf = torch.from_numpy(sdf).float()[None].cuda()
sdf_centroid = torch.from_numpy(sdf_centroid).float()[None].cuda()
sdf_extents = torch.from_numpy(sdf_extents).float()[None].cuda()
return sdf, sdf_centroid, sdf_extents
def load_and_freeze_clip(self, clip_version):
clip_model, clip_preprocess = clip.load(clip_version, device='cuda',
jit=False)
# Freeze CLIP weights
clip_model.eval()
for p in clip_model.parameters():
p.requires_grad = False
return clip_model
def encode_text(self, raw_text):
# raw_text - list (batch_size length) of strings with input text prompts
device = next(self.clip_model.parameters()).device
max_text_len = 30 # Specific hardcoding for the current dataset
if max_text_len is not None:
default_context_length = 77
context_length = max_text_len + 2 # start_token + 20 + end_token
assert context_length < default_context_length
texts = clip.tokenize(raw_text, context_length=context_length, truncate=True).to(device) # [bs, context_length] # if n_tokens > context_length -> will truncate
# print('texts', texts.shape)
zero_pad = torch.zeros([texts.shape[0], default_context_length-context_length], dtype=texts.dtype, device=texts.device)
texts = torch.cat([texts, zero_pad], dim=1)
# print('texts after pad', texts.shape, texts)
else:
texts = clip.tokenize(raw_text, truncate=True).to(device) # [bs, context_length] # if n_tokens > 77 -> will truncate
return self.clip_model.encode_text(texts).float().detach() # BS X 512
def prep_dataloader(self, window_size):
# Define dataset
train_dataset = CanoObjectTrajDataset(train=True, data_root_folder=self.data_root_folder, \
window=window_size, use_object_splits=self.use_object_split, \
input_language_condition=self.add_language_condition, \
use_random_frame_bps=self.use_random_frame_bps, \
use_object_keypoints=self.use_object_keypoints)
val_dataset = CanoObjectTrajDataset(train=False, data_root_folder=self.data_root_folder, \
window=window_size, use_object_splits=self.use_object_split, \
input_language_condition=self.add_language_condition, \
use_random_frame_bps=self.use_random_frame_bps, \
use_object_keypoints=self.use_object_keypoints)
self.ds = train_dataset
self.val_ds = val_dataset
self.dl = cycle(data.DataLoader(self.ds, batch_size=self.batch_size, \
shuffle=True, pin_memory=True, num_workers=4))
self.val_dl = cycle(data.DataLoader(self.val_ds, batch_size=self.batch_size, \
shuffle=False, pin_memory=True, num_workers=4))
def save(self, milestone):
data = {
'step': self.step,
'model': self.model.state_dict(),
'ema': self.ema.state_dict(),
'scaler': self.scaler.state_dict()
}
torch.save(data, os.path.join(self.results_folder, 'model-'+str(milestone)+'.pt'))
def load(self, milestone, pretrained_path=None):
if pretrained_path is None:
data = torch.load(os.path.join(self.results_folder, 'model-'+str(milestone)+'.pt'))
else:
data = torch.load(pretrained_path)
self.step = data['step']
self.model.load_state_dict(data['model'], strict=False)
self.ema.load_state_dict(data['ema'], strict=False)
self.scaler.load_state_dict(data['scaler'])
def prep_start_end_condition_mask_pos_only(self, data, actual_seq_len):
# data: BS X T X D (3+9)
# actual_seq_len: BS
tmp_mask = torch.arange(self.window).expand(data.shape[0], \
self.window) == (actual_seq_len[:, None].repeat(1, self.window)-1)
# BS X max_timesteps
tmp_mask = tmp_mask.to(data.device)[:, :, None] # BS X T X 1
# Missing regions are ones, the condition regions are zeros.
mask = torch.ones_like(data[:, :, :3]).to(data.device) # BS X T X 3
mask = mask * (~tmp_mask) # Only the actual_seq_len frame is 0
# Add rotation mask, only the first frame's rotation is given.
rotation_mask = torch.ones_like(data[:, :, 3:]).to(data.device)
mask = torch.cat((mask, rotation_mask), dim=-1)
mask[:, 0, :] = torch.zeros(data.shape[0], data.shape[2]).to(data.device) # BS X D
return mask
def prep_mimic_A_star_path_condition_mask_pos_xy_only(self, data, actual_seq_len):
# data: BS X T X D
# actual_seq_len: BS
tmp_mask = torch.arange(self.window).expand(data.shape[0], \
self.window) == (actual_seq_len[:, None].repeat(1, self.window)-1)
# BS X max_timesteps
tmp_mask = tmp_mask.to(data.device)[:, :, None] # BS X T X 1
tmp_mask = (~tmp_mask)
# Use fixed number of waypoints.
random_steps = [30-1, 60-1, 90-1]
for selected_t in random_steps:
if selected_t < self.window - 1:
bs_selected_t = torch.from_numpy(np.asarray([selected_t])) # 1
bs_selected_t = bs_selected_t[None, :].repeat(data.shape[0], self.window) # BS X T
curr_tmp_mask = torch.arange(self.window).expand(data.shape[0], \
self.window) == (bs_selected_t)
# BS X max_timesteps
curr_tmp_mask = curr_tmp_mask.to(data.device)[:, :, None] # BS X T X 1
tmp_mask = (~curr_tmp_mask)*tmp_mask
# Missing regions are ones, the condition regions are zeros.
mask = torch.ones_like(data[:, :, :2]).to(data.device) # BS X T X 2
mask = mask * tmp_mask # Only the actual_seq_len frame is 0
# Add rotation mask, only the first frame's rotation is given.
# Also, add z mask, only the first frane's z is given.
rotation_mask = torch.ones_like(data[:, :, 2:]).to(data.device)
mask = torch.cat((mask, rotation_mask), dim=-1)
mask[:, 0, :] = torch.zeros(data.shape[0], data.shape[2]).to(data.device) # BS X D
return mask
def train(self):
init_step = self.step
for idx in range(init_step, self.train_num_steps):
self.optimizer.zero_grad()
nan_exists = False # If met nan in loss or gradient, need to skip to next data.
for i in range(self.gradient_accumulate_every):
data_dict = next(self.dl)
human_data = data_dict['motion'].cuda() # BS X T X (24*3 + 22*6)
obj_data = data_dict['obj_motion'].cuda() # BS X T X (3+9)
obj_bps_data = data_dict['input_obj_bps'].cuda().reshape(-1, 1, 1024*3) # BS X 1 X 1024 X 3 -> BS X 1 X (1024*3)
rest_human_offsets = data_dict['rest_human_offsets'].cuda() # BS X 24 X 3
ori_data_cond = obj_bps_data # BS X 1 X (1024*3)
# Generate padding mask
actual_seq_len = data_dict['seq_len'] + 1 # BS, + 1 since we need additional timestep for noise level
tmp_mask = torch.arange(self.window+1).expand(obj_data.shape[0], \
self.window+1) < actual_seq_len[:, None].repeat(1, self.window+1)
# BS X max_timesteps
padding_mask = tmp_mask[:, None, :].to(obj_data.device)
# Add start & end object positions and waypoints xy as input conditions
end_pos_cond_mask = self.prep_start_end_condition_mask_pos_only(obj_data, data_dict['seq_len'])
cond_mask = self.prep_mimic_A_star_path_condition_mask_pos_xy_only(obj_data, data_dict['seq_len'])
cond_mask = end_pos_cond_mask * cond_mask
# Add the first human pose as input condition
human_cond_mask = torch.ones_like(human_data).to(human_data.device)
if self.input_first_human_pose:
human_cond_mask[:, 0, :] = 0
cond_mask = torch.cat((cond_mask, human_cond_mask), dim=-1) # BS X T X (3+6+24*3+22*6)
with autocast(enabled = self.amp):
contact_data = data_dict['contact_labels'].cuda() # BS X T X 4
data = torch.cat((obj_data, human_data, contact_data), dim=-1)
cond_mask = torch.cat((cond_mask, \
torch.ones_like(contact_data).to(cond_mask.device)), dim=-1)
if self.add_language_condition:
text_anno_data = data_dict['text']
language_input = self.encode_text(text_anno_data) # BS X 512
language_input = language_input.to(data.device)
loss_diffusion, loss_obj, loss_human, loss_feet, loss_fk, loss_obj_pts = \
self.model(data, ori_data_cond, cond_mask, padding_mask, \
language_input=language_input, \
rest_human_offsets=rest_human_offsets, ds=self.ds, data_dict=data_dict)
else:
loss_diffusion = self.model(data, ori_data_cond, cond_mask, padding_mask, \
rest_human_offsets=rest_human_offsets)
if self.use_object_keypoints:
loss = loss_diffusion + self.loss_w_feet * loss_feet + \
self.loss_w_fk * loss_fk + self.loss_w_obj_pts * loss_obj_pts
else:
loss = loss_diffusion
if torch.isnan(loss).item():
print('WARNING: NaN loss. Skipping to next data...')
nan_exists = True
torch.cuda.empty_cache()
continue
self.scaler.scale(loss / self.gradient_accumulate_every).backward()
# check gradients
parameters = [p for p in self.model.parameters() if p.grad is not None]
total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), 2.0).to(obj_data.device) for p in parameters]), 2.0)
if torch.isnan(total_norm):
print('WARNING: NaN gradients. Skipping to next data...')
nan_exists = True
torch.cuda.empty_cache()
continue
if self.use_wandb:
if self.use_object_keypoints:
log_dict = {
"Train/Loss/Total Loss": loss.item(),
"Train/Loss/Diffusion Loss": loss_diffusion.item(),
"Train/Loss/Object Loss": loss_obj.item(),
"Train/Loss/Human Loss": loss_human.item(),
"Train/Loss/Semantic Contact Loss": loss_feet.item(),
"Train/Loss/FK Loss": loss_fk.item(),
"Train/Loss/Object Pts Loss": loss_obj_pts.item(),
}
else:
log_dict = {
"Train/Loss/Total Loss": loss.item(),
"Train/Loss/Diffusion Loss": loss_diffusion.item(),
"Train/Loss/Object Loss": loss_obj.item(),
"Train/Loss/Human Loss": loss_human.item(),
}
wandb.log(log_dict)
if idx % 20 == 0 and i == 0:
print("Step: {0}".format(idx))
print("Loss: %.4f" % (loss.item()))
print("Object Loss: %.4f" % (loss_obj.item()))
print("Human Loss: %.4f" % (loss_human.item()))
if self.use_object_keypoints:
print("Semantic Contact Loss: %.4f" % (loss_feet.item()))
print("FK Loss: %.4f" % (loss_fk.item()))
print("Object Pts Loss: %.4f" % (loss_obj_pts.item()))
if nan_exists:
continue
self.scaler.step(self.optimizer)
self.scaler.update()
self.ema.update()
if self.step != 0 and self.step % 10 == 0:
self.ema.ema_model.eval()
with torch.no_grad():
val_data_dict = next(self.val_dl)
val_human_data = val_data_dict['motion'].cuda()
val_obj_data = val_data_dict['obj_motion'].cuda()
obj_bps_data = val_data_dict['input_obj_bps'].cuda().reshape(-1, 1, 1024*3)
ori_data_cond = obj_bps_data
rest_human_offsets = val_data_dict['rest_human_offsets'].cuda() # BS X 24 X 3
# Generate padding mask
actual_seq_len = val_data_dict['seq_len'] + 1 # BS, + 1 since we need additional timestep for noise level
tmp_mask = torch.arange(self.window+1).expand(val_obj_data.shape[0], \
self.window+1) < actual_seq_len[:, None].repeat(1, self.window+1)
# BS X max_timesteps
padding_mask = tmp_mask[:, None, :].to(val_obj_data.device)
end_pos_cond_mask = self.prep_start_end_condition_mask_pos_only(val_obj_data, val_data_dict['seq_len'])
cond_mask = self.prep_mimic_A_star_path_condition_mask_pos_xy_only(val_obj_data, val_data_dict['seq_len'])
cond_mask = end_pos_cond_mask * cond_mask
human_cond_mask = torch.ones_like(val_human_data).to(val_human_data.device)
if self.input_first_human_pose:
human_cond_mask[:, 0, :] = 0
cond_mask = torch.cat((cond_mask, human_cond_mask), dim=-1) # BS X T X (3+6+24*3+22*6)
# Get validation loss
contact_data = val_data_dict['contact_labels'].cuda() # BS X T X 4
data = torch.cat((val_obj_data, val_human_data, contact_data), dim=-1)
cond_mask = torch.cat((cond_mask, \
torch.ones_like(contact_data).to(cond_mask.device)), dim=-1)
if self.add_language_condition:
text_anno_data = val_data_dict['text']
language_input = self.encode_text(text_anno_data) # BS X 512
language_input = language_input.to(data.device)
val_loss_diffusion, val_loss_obj, val_loss_human, val_loss_feet, val_loss_fk, val_loss_obj_pts = \
self.model(data, ori_data_cond, cond_mask, padding_mask, \
language_input=language_input, \
rest_human_offsets=rest_human_offsets, \
ds=self.val_ds, data_dict=val_data_dict)
else:
val_loss_diffusion = self.model(data, ori_data_cond, cond_mask, padding_mask, \
rest_human_offsets=rest_human_offsets)
val_loss = val_loss_diffusion + self.loss_w_feet * val_loss_feet + \
self.loss_w_fk * val_loss_fk + self.loss_w_obj_pts * val_loss_obj_pts
if self.use_wandb:
val_log_dict = {
"Validation/Loss/Total Loss": val_loss.item(),
"Validation/Loss/Diffusion Loss": val_loss_diffusion.item(),
"Validation/Loss/Object Loss": val_loss_obj.item(),
"Validation/Loss/Human Loss": val_loss_human.item(),
"Validation/Loss/Semantic Contact Loss": val_loss_feet.item(),
"Validation/Loss/FK Loss": val_loss_fk.item(),
"Validation/Loss/Object Pts Loss": val_loss_obj_pts.item(),
}
wandb.log(val_log_dict)
milestone = self.step // self.save_and_sample_every
if self.step % self.save_and_sample_every == 0:
self.save(milestone)
if self.add_language_condition:
all_res_list = self.ema.ema_model.sample(data, ori_data_cond, cond_mask, padding_mask, \
language_input=language_input, \
rest_human_offsets=rest_human_offsets)
else:
all_res_list = self.ema.ema_model.sample(data, ori_data_cond, cond_mask, padding_mask, \
rest_human_offsets=rest_human_offsets)
for_vis_gt_data = torch.cat((val_obj_data, val_human_data), dim=-1)
all_res_list = all_res_list[:, :, :-4]
cond_mask = cond_mask[:, :, :-4]
self.gen_vis_res(for_vis_gt_data, val_data_dict, self.step, cond_mask, vis_gt=True)
self.gen_vis_res(all_res_list, val_data_dict, self.step, cond_mask)
self.step += 1
print('training complete')
if self.use_wandb:
wandb.run.finish()
def append_new_value_to_metrics_list(self, lhand_jpe, rhand_jpe, hand_jpe, mpvpe, mpjpe, rot_dist, trans_err, \
gt_contact_percent, contact_percent, gt_foot_sliding_jnts, foot_sliding_jnts, \
contact_precision, contact_recall, contact_acc, contact_f1_score, obj_rot_dist, obj_com_pos_err, \
start_obj_com_pos_err, end_obj_com_pos_err, waypoints_xy_pos_err, gt_penetration_score, penetration_score, \
gt_hand_penetration_score, hand_penetration_score, gt_floor_height, pred_floor_height):
# Append new sequence's value to list.
self.lhand_jpe_list.append(lhand_jpe)
self.rhand_jpe_list.append(rhand_jpe)
self.hand_jpe_list.append(hand_jpe)
self.mpvpe_list.append(mpvpe)
self.mpjpe_list.append(mpjpe)
self.rot_dist_list.append(rot_dist)
self.trans_err_list.append(trans_err)
self.gt_floor_height_list.append(gt_floor_height)
self.floor_height_list.append(pred_floor_height)
self.gt_foot_sliding_jnts_list.append(gt_foot_sliding_jnts)
self.foot_sliding_jnts_list.append(foot_sliding_jnts)
self.gt_contact_percent_list.append(gt_contact_percent)
self.contact_percent_list.append(contact_percent)
self.contact_precision_list.append(contact_precision)
self.contact_recall_list.append(contact_recall)
self.contact_acc_list.append(contact_acc)
self.contact_f1_score_list.append(contact_f1_score)
self.obj_rot_dist_list.append(obj_rot_dist)
self.obj_com_pos_err_list.append(obj_com_pos_err)
self.start_obj_com_pos_err_list.append(start_obj_com_pos_err)
self.end_obj_com_pos_err_list.append(end_obj_com_pos_err)
self.waypoints_xy_pos_err_list.append(waypoints_xy_pos_err)
self.gt_penetration_list.append(gt_penetration_score)
self.penetration_list.append(penetration_score)
self.gt_hand_penetration_list.append(gt_hand_penetration_score)
self.hand_penetration_list.append(hand_penetration_score)
def print_evaluation_metrics(self, lhand_jpe_list, rhand_jpe_list, hand_jpe_list, mpvpe_list, mpjpe_list, \
rot_dist_list, trans_err_list, gt_contact_percent_list, contact_percent_list, \
gt_foot_sliding_jnts_list, foot_sliding_jnts_list, contact_precision_list, contact_recall_list, \
contact_acc_list, contact_f1_score_list, obj_rot_dist_list, obj_com_pos_err_list, \
start_obj_com_pos_err_list, end_obj_com_pos_err_list, waypoints_xy_pos_err_list, \
gt_penetration_score_list, penetration_score_list, \
gt_hand_penetration_score_list, hand_penetration_score_list, \
gt_floor_height_list, pred_floor_height_list, \
dest_metric_folder, seq_name=None):
mean_lhand_jpe = np.asarray(lhand_jpe_list).mean()
mean_rhand_jpe = np.asarray(rhand_jpe_list).mean()
mean_hand_jpe = np.asarray(hand_jpe_list).mean()
mean_mpjpe = np.asarray(mpjpe_list).mean()
mean_mpvpe = np.asarray(mpvpe_list).mean()
mean_root_trans_err = np.asarray(trans_err_list).mean()
mean_rot_dist = np.asarray(rot_dist_list).mean()
mean_fsliding_jnts = np.asarray(foot_sliding_jnts_list).mean()
mean_gt_fsliding_jnts = np.asarray(gt_foot_sliding_jnts_list).mean()
mean_contact_percent = np.asarray(contact_percent_list).mean()
mean_gt_contact_percent = np.asarray(gt_contact_percent_list).mean()
mean_contact_precision = np.asarray(contact_precision_list).mean()
mean_contact_recall = np.asarray(contact_recall_list).mean()
mean_contact_acc = np.asarray(contact_acc_list).mean()
mean_contact_f1_score = np.asarray(contact_f1_score_list).mean()
mean_obj_rot_dist = np.asarray(obj_rot_dist_list).mean()
mean_obj_com_pos_err = np.asarray(obj_com_pos_err_list).mean()
mean_start_obj_com_pos_err = np.asarray(start_obj_com_pos_err_list).mean()
mean_end_obj_com_pos_err = np.asarray(end_obj_com_pos_err_list).mean()
mean_waypoints_xy_pos_err = np.asarray(waypoints_xy_pos_err_list).mean()
mean_penetration_score = np.asarray(penetration_score_list).mean()
mean_gt_penetration_score = np.asarray(gt_penetration_score_list).mean()
mean_hand_penetration_score = np.asarray(hand_penetration_score_list).mean()
mean_gt_hand_penetration_score = np.asarray(gt_hand_penetration_score_list).mean()
mean_gt_floor_height = np.asarray(gt_floor_height_list).mean()
mean_pred_floor_height = np.asarray(pred_floor_height_list).mean()
print("The number of sequences: {0}".format(len(mpjpe_list)))
print("*********************************Human Motion Evaluation**************************************")
print("Left Hand JPE: {0}, Right Hand JPE: {1}, Two Hands JPE: {2}".format(mean_lhand_jpe, mean_rhand_jpe, mean_hand_jpe))
print("MPJPE: {0}, MPVPE: {1}, Root Trans: {2}, Global Rot Err: {3}".format(mean_mpjpe, mean_mpvpe, mean_root_trans_err, mean_rot_dist))
print("Foot sliding jnts: {0}, GT Foot sliding jnts: {1}".format(mean_fsliding_jnts, mean_gt_fsliding_jnts))
print("Floor Height: {0}, GT Floor Height: {1}".format(mean_pred_floor_height, mean_gt_floor_height))
print("*********************************Object Motion Evaluation**************************************")
print("Object com pos err: {0}, Object rotation err: {1}".format(mean_obj_com_pos_err, mean_obj_rot_dist))
print("*********************************Interaction Evaluation**************************************")
print("Hand-Object Penetration Score: {0}".format(mean_hand_penetration_score))
print("GT Hand-Object Penetration Score: {0}".format(mean_gt_hand_penetration_score))
print("Human-Object Penetration Score: {0}".format(mean_penetration_score))
print("GT Human-Object Penetration Score: {0}".format(mean_gt_penetration_score))
print("Contact precision: {0}, Contact recall: {1}".format(mean_contact_precision, mean_contact_recall))
print("Contact Acc: {0}, Contact F1 score: {1}".format(mean_contact_acc, mean_contact_f1_score))
print("Contact percentage: {0}, GT Contact percentage: {1}".format(mean_contact_percent, mean_gt_contact_percent))
print("*********************************Condition Following Evaluation**************************************")
print("Start obj_com_pos err: {0}, End obj_com_pos err: {1}".format(mean_start_obj_com_pos_err, mean_end_obj_com_pos_err))
print("waypoints xy err: {0}".format(mean_waypoints_xy_pos_err))
# Save the results to json files.
if not os.path.exists(dest_metric_folder):
os.makedirs(dest_metric_folder)
if seq_name is not None: # number for all the testing data
dest_metric_json_path = os.path.join(dest_metric_folder, seq_name+".json")
else:
dest_metric_json_path = os.path.join(dest_metric_folder, "evaluation_metrics_for_all_test_data.json")
metric_dict = {}
metric_dict['mean_lhand_jpe'] = mean_lhand_jpe
metric_dict['mean_rhand_jpe'] = mean_rhand_jpe
metric_dict['mean_hand_jpe'] = mean_hand_jpe
metric_dict['mean_mpjpe'] = mean_mpjpe
metric_dict['mean_mpvpe'] = mean_mpvpe
metric_dict['mean_root_trans_err'] = mean_root_trans_err
metric_dict['mean_rot_dist'] = mean_rot_dist
metric_dict['mean_floor_height'] = mean_pred_floor_height
metric_dict['mean_gt_floor_height'] = mean_gt_floor_height
metric_dict['mean_fsliding_jnts'] = mean_fsliding_jnts
metric_dict['mean_gt_fsliding_jnts'] = mean_gt_fsliding_jnts
metric_dict['mean_contact_percent'] = mean_contact_percent
metric_dict['mean_gt_contact_percent'] = mean_gt_contact_percent
metric_dict['mean_contact_precision'] = mean_contact_precision
metric_dict['mean_contact_recall'] = mean_contact_recall
metric_dict['mean_contact_acc'] = mean_contact_acc
metric_dict['mean_contact_f1_score'] = mean_contact_f1_score
metric_dict['mean_obj_rot_dist'] = mean_obj_rot_dist
metric_dict['mean_obj_com_pos_err'] = mean_obj_com_pos_err
metric_dict['mean_start_obj_com_pos_err'] = mean_start_obj_com_pos_err
metric_dict['mean_end_obj_com_pos_err'] = mean_end_obj_com_pos_err
metric_dict['mean_waypoints_xy_pos_err'] = mean_waypoints_xy_pos_err
metric_dict['mean_penetration_score'] = mean_penetration_score
metric_dict['mean_gt_penetration_score'] = mean_gt_penetration_score
metric_dict['mean_hand_penetration_score'] = mean_hand_penetration_score
metric_dict['mean_gt_hand_penetration_score'] = mean_gt_hand_penetration_score
# Convert all to float
for k in metric_dict:
metric_dict[k] = float(metric_dict[k])
json.dump(metric_dict, open(dest_metric_json_path, 'w'))
def print_evaluation_metrics_for_long_seq(self, foot_sliding_jnts_list, \
pred_floor_height_list, contact_percent_list, \
start_obj_com_pos_err_list, end_obj_com_pos_err_list, waypoints_xy_pos_err_list, \
penetration_score_list, \
hand_penetration_score_list, \
scene_human_penetration_list, \
scene_object_penetration_list, \
dest_metric_folder, seq_name=None):
mean_fsliding_jnts = np.asarray(foot_sliding_jnts_list).mean()
mean_contact_percent = np.asarray(contact_percent_list).mean()
mean_start_obj_com_pos_err = np.asarray(start_obj_com_pos_err_list).mean()
mean_end_obj_com_pos_err = np.asarray(end_obj_com_pos_err_list).mean()
mean_waypoints_xy_pos_err = np.asarray(waypoints_xy_pos_err_list).mean()
mean_penetration_score = np.asarray(penetration_score_list).mean()
mean_hand_penetration_score = np.asarray(hand_penetration_score_list).mean()
mean_pred_floor_height = np.asarray(pred_floor_height_list).mean()
mean_scene_human_penetration = np.asarray(scene_human_penetration_list).mean()
mean_scene_object_penetration = np.asarray(scene_object_penetration_list).mean()
print("The number of sequences: {0}".format(len(foot_sliding_jnts_list)))
print("*********************************Human Motion Evaluation**************************************")
print("Foot sliding jnts: {0}".format(mean_fsliding_jnts))
print("Floor Height: {0}".format(mean_pred_floor_height))
print("*********************************Interaction Evaluation**************************************")
print("Hand-Object Penetration Score: {0}".format(mean_hand_penetration_score))
print("Human-Object Penetration Score: {0}".format(mean_penetration_score))
print("Contact percentage: {0}".format(mean_contact_percent))
print("Scene-Human Penetration Score: {0}".format(mean_scene_human_penetration))
print("Scene-Object Penetration Score: {0}".format(mean_scene_object_penetration))
print("*********************************Condition Following Evaluation**************************************")
print("Start obj_com_pos err: {0}, End obj_com_pos err: {1}".format(mean_start_obj_com_pos_err, mean_end_obj_com_pos_err))
print("waypoints xy err: {0}".format(mean_waypoints_xy_pos_err))
# Save the results to json files.
if not os.path.exists(dest_metric_folder):
os.makedirs(dest_metric_folder)
if seq_name is not None: # number for all the testing data
dest_metric_json_path = os.path.join(dest_metric_folder, seq_name+".json")
else:
dest_metric_json_path = os.path.join(dest_metric_folder, \
self.test_scene_name+"_evaluation_metrics_for_all_test_data.json")
metric_dict = {}
metric_dict['mean_floor_height'] = mean_pred_floor_height
metric_dict['mean_fsliding_jnts'] = mean_fsliding_jnts
metric_dict['mean_contact_percent'] = mean_contact_percent
metric_dict['mean_start_obj_com_pos_err'] = mean_start_obj_com_pos_err
metric_dict['mean_end_obj_com_pos_err'] = mean_end_obj_com_pos_err
metric_dict['mean_waypoints_xy_pos_err'] = mean_waypoints_xy_pos_err
metric_dict['mean_penetration_score'] = mean_penetration_score
metric_dict['mean_hand_penetration_score'] = mean_hand_penetration_score
metric_dict['mean_scene_human_penetration_score'] = mean_scene_human_penetration
metric_dict['mean_scene_object_penetration_score'] = mean_scene_object_penetration
# Convert all to float
for k in metric_dict:
metric_dict[k] = float(metric_dict[k])
json.dump(metric_dict, open(dest_metric_json_path, 'w'))
def compute_hand_penetration_metric(self, object_name, ori_verts_pred, \
pred_obj_com_pos, pred_obj_rot_mat, eval_fullbody=False):
# ori_verts_pred: T X Nv X 3
# pred_obj_com_pos: T X 3
# pred_obj_rot_mat: T X 3 X 3
ori_verts_pred = ori_verts_pred[None] # 1 X T X Nv X 3
pred_obj_com_pos = pred_obj_com_pos[None] # 1 X T X 3
pred_obj_rot_mat = pred_obj_rot_mat[None] # 1 X T X 3 X 3
if not eval_fullbody:
hand_verts = ori_verts_pred[:, :, self.hand_vertex_idxs, :] # BS X T X N_hand X 3
else:
hand_verts = ori_verts_pred
hand_verts_in_rest_frame = hand_verts - pred_obj_com_pos[:, :, None, :] # BS X T X N_hand X 3
hand_verts_in_rest_frame = torch.matmul(pred_obj_rot_mat[:, :, None, :, :].repeat(1, 1, \
hand_verts_in_rest_frame.shape[2], 1, 1), \
hand_verts_in_rest_frame[:, :, :, :, None]).squeeze(-1) # BS X T X N_hand X 3
curr_object_sdf, curr_object_sdf_centroid, curr_object_sdf_extents = \
self.load_object_sdf_data(object_name)
# Convert hand vertices to align with rest pose object.
signed_dists = compute_signed_distances(curr_object_sdf, curr_object_sdf_centroid, \
curr_object_sdf_extents, hand_verts_in_rest_frame[0]) # we always use bs = 1 now!!!
# signed_dists: T X N_hand (120 X 1535)
penetration_score = torch.minimum(signed_dists, torch.zeros_like(signed_dists)).abs().mean() # The smaller, the better
# penetration_score = torch.minimum(signed_dists, torch.zeros_like(signed_dists)).abs().sum()
return penetration_score.detach().cpu().numpy()
def prep_evaluation_metrics_list(self):
self.lhand_jpe_list = []
self.rhand_jpe_list = []
self.hand_jpe_list = []
self.mpvpe_list = []
self.mpjpe_list = []
self.rot_dist_list = []
self.trans_err_list = []
self.gt_floor_height_list = []
self.floor_height_list = []
self.gt_foot_sliding_jnts_list = []
self.foot_sliding_jnts_list = []
self.gt_contact_percent_list = []
self.contact_percent_list = []
self.contact_precision_list = []
self.contact_recall_list = []
self.contact_acc_list = []
self.contact_f1_score_list = []
self.obj_rot_dist_list = []
self.obj_com_pos_err_list = []
self.start_obj_com_pos_err_list = []
self.end_obj_com_pos_err_list = []
self.waypoints_xy_pos_err_list = []
self.gt_penetration_list = []
self.penetration_list = []
self.gt_hand_penetration_list = []
self.hand_penetration_list = []
def prep_res_folders(self):
res_root_folder = self.save_res_folder
# Prepare folder for saving npz results
dest_res_for_eval_npz_folder = os.path.join(res_root_folder, "res_npz_files")
# Prepare folder for evaluation metrics
dest_metric_root_folder = os.path.join(res_root_folder, "evaluation_metrics_json")
# Prepare folder for visualization
dest_out_vis_root_folder = os.path.join(res_root_folder, "single_window_cmp_settings")
# Prepare folder for saving .obj files
dest_out_obj_root_folder = os.path.join(res_root_folder, "objs_single_window_cmp_settings")
if self.test_unseen_objects:
dest_res_for_eval_npz_folder += "_unseen_obj"
dest_metric_root_folder += "_unseen_obj"
dest_out_vis_root_folder += "_unseen_obj"
dest_out_obj_root_folder += "_unseen_obj"
# Prepare folder for saving text json files
dest_out_text_json_folder = os.path.join(dest_out_vis_root_folder, "text_json_files")
if self.use_guidance_in_denoising:
dest_res_for_eval_npz_folder = os.path.join(dest_res_for_eval_npz_folder, "chois")
dest_metric_folder = os.path.join(dest_metric_root_folder, "chois")
dest_out_vis_folder = os.path.join(dest_out_vis_root_folder, "chois")
dest_out_obj_folder = os.path.join(dest_out_obj_root_folder, "chois")
else: