chencws commited on
Commit
b7ecc94
1 Parent(s): 3d91bf8

Upload 13 files

Browse files
Files changed (13) hide show
  1. GPT_eval_multi.py +144 -0
  2. LICENSE +201 -0
  3. README.md +227 -13
  4. VQ_eval.py +95 -0
  5. attack.py +182 -0
  6. environment.yml +121 -0
  7. eval_trans_per.py +653 -0
  8. losses.py +102 -0
  9. metrics.py +192 -0
  10. quickstart.ipynb +0 -0
  11. render_final.py +198 -0
  12. requirements.txt +57 -0
  13. train_vq.py +175 -0
GPT_eval_multi.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import numpy as np
4
+ from torch.utils.tensorboard import SummaryWriter
5
+ import json
6
+ # import clip
7
+ from CLIP import clip
8
+
9
+ import options.option_transformer as option_trans
10
+ import models.vqvae as vqvae
11
+ import utils.utils_model as utils_model
12
+ import eval_trans_per as eval_trans
13
+ from dataset import dataset_TM_eval
14
+ import models.t2m_trans as trans
15
+ from options.get_eval_option import get_opt
16
+ from models.evaluator_wrapper import EvaluatorModelWrapper
17
+ import warnings
18
+ from tqdm import trange
19
+ warnings.filterwarnings('ignore')
20
+
21
+ ##### ---- Exp dirs ---- #####
22
+ os.chdir('/root/autodl-tmp/SATO')
23
+ args = option_trans.get_args_parser()
24
+ torch.manual_seed(args.seed)
25
+
26
+ args.out_dir = os.path.join(args.out_dir, f'{args.exp_name}')
27
+ os.makedirs(args.out_dir, exist_ok = True)
28
+
29
+ ##### ---- Logger ---- #####
30
+ logger = utils_model.get_logger(args.out_dir)
31
+ writer = SummaryWriter(args.out_dir)
32
+ logger.info(json.dumps(vars(args), indent=4, sort_keys=True))
33
+
34
+ from utils.word_vectorizer import WordVectorizer
35
+ w_vectorizer = WordVectorizer('./glove', 'our_vab')
36
+ val_loader = dataset_TM_eval.DATALoader(args.dataname, True, 32, w_vectorizer)
37
+
38
+ dataset_opt_path = 'checkpoints/kit/Comp_v6_KLD005/opt.txt' if args.dataname == 'kit' else 'checkpoints/t2m/Comp_v6_KLD005/opt.txt'
39
+
40
+ wrapper_opt = get_opt(dataset_opt_path, torch.device('cuda'))
41
+ eval_wrapper = EvaluatorModelWrapper(wrapper_opt)
42
+
43
+ ##### ---- Network ---- #####
44
+
45
+ ## load clip model and datasets
46
+
47
+ clip_model, clip_preprocess = clip.load(args.clip_path, device=torch.device('cuda'), jit=False) # Must set jit=False for training
48
+ clip.model.convert_weights(clip_model) # Actually this line is unnecessary since clip by default already on float16
49
+ clip_model.eval()
50
+ for p in clip_model.parameters():
51
+ p.requires_grad = False
52
+
53
+ net = vqvae.HumanVQVAE(args, ## use args to define different parameters in different quantizers
54
+ args.nb_code,
55
+ args.code_dim,
56
+ args.output_emb_width,
57
+ args.down_t,
58
+ args.stride_t,
59
+ args.width,
60
+ args.depth,
61
+ args.dilation_growth_rate)
62
+
63
+
64
+ trans_encoder = trans.Text2Motion_Transformer(num_vq=args.nb_code,
65
+ embed_dim=args.embed_dim_gpt,
66
+ clip_dim=args.clip_dim,
67
+ block_size=args.block_size,
68
+ num_layers=args.num_layers,
69
+ n_head=args.n_head_gpt,
70
+ drop_out_rate=args.drop_out_rate,
71
+ fc_rate=args.ff_rate)
72
+
73
+
74
+ print ('loading checkpoint from {}'.format(args.resume_pth))
75
+ ckpt = torch.load(args.resume_pth, map_location='cpu')
76
+ net.load_state_dict(ckpt['net'], strict=True)
77
+ net.eval()
78
+ net.cuda()
79
+
80
+ if args.resume_trans is not None:
81
+ print ('loading transformer checkpoint from {}'.format(args.resume_trans))
82
+ ckpt = torch.load(args.resume_trans, map_location='cpu')
83
+ trans_encoder.load_state_dict(ckpt['trans'], strict=True)
84
+ trans_encoder.train()
85
+ trans_encoder.cuda()
86
+ print('checkpoints loading successfully')
87
+
88
+ fid = []
89
+ fid_per=[]
90
+ div = []
91
+ top1 = []
92
+ top2 = []
93
+ top3 = []
94
+ matching = []
95
+ multi = []
96
+ repeat_time = 20
97
+ fid_word_perb=[]
98
+
99
+ for i in range(repeat_time):
100
+ print('repeat_time: ',i)
101
+ best_fid,best_fid_word_perb,best_fid_per, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, best_multi, writer, logger = eval_trans.evaluation_transformer_test(args.out_dir, val_loader, net, trans_encoder, logger, writer, 0, best_fid=1000,best_fid_word_perb=1000,best_fid_perturbation=1000, best_iter=0, best_div=100, best_top1=0, best_top2=0, best_top3=0, best_matching=100, best_multi=0, clip_model=clip_model, eval_wrapper=eval_wrapper, draw=False, savegif=False, save=False, savenpy=(i==0))
102
+ fid.append(best_fid)
103
+ fid_word_perb.append(best_fid_word_perb)
104
+ fid_per.append(best_fid_per)
105
+ div.append(best_div)
106
+ top1.append(best_top1)
107
+ top2.append(best_top2)
108
+ top3.append(best_top3)
109
+ matching.append(best_matching)
110
+ multi.append(best_multi)
111
+
112
+ # print('fid: ', sum(fid)/(i+1))
113
+ # print('fid_per',sum(fid_per)/(i+1))
114
+ # print('div: ', sum(div)/(i+1))
115
+ # print('top1: ', sum(top1)/(i+1))
116
+ # print('top2: ', sum(top2)/(i+1))
117
+ # print('top3: ', sum(top3)/(i+1))
118
+ # print('matching: ', sum(matching)/(i+1))
119
+ # print('multi: ', sum(multi)/(i+1))
120
+
121
+
122
+ print('final result:')
123
+ print('fid: ', sum(fid)/repeat_time)
124
+ print('fid_word_perb',sum(fid_word_perb)/repeat_time)
125
+ print('fid_per',sum(fid_per)/repeat_time)
126
+ print('div: ', sum(div)/repeat_time)
127
+ print('top1: ', sum(top1)/repeat_time)
128
+ print('top2: ', sum(top2)/repeat_time)
129
+ print('top3: ', sum(top3)/repeat_time)
130
+ print('matching: ', sum(matching)/repeat_time)
131
+ # print('multi: ', sum(multi)/repeat_time)
132
+
133
+ fid = np.array(fid)
134
+ fid_word_perb=np.array(fid_word_perb)
135
+ fid_per=np.array(fid_per)
136
+ div = np.array(div)
137
+ top1 = np.array(top1)
138
+ top2 = np.array(top2)
139
+ top3 = np.array(top3)
140
+ matching = np.array(matching)
141
+ # multi = np.array(multi)
142
+ # msg_final = f"FID. {np.mean(fid):.3f}, FID_PERB.{np.mean(fid_per):.3f}conf. {np.std(fid)*1.96/np.sqrt(repeat_time):.3f}, Diversity. {np.mean(div):.3f}, conf. {np.std(div)*1.96/np.sqrt(repeat_time):.3f}, TOP1. {np.mean(top1):.3f}, conf. {np.std(top1)*1.96/np.sqrt(repeat_time):.3f}, TOP2. {np.mean(top2):.3f}, conf. {np.std(top2)*1.96/np.sqrt(repeat_time):.3f}, TOP3. {np.mean(top3):.3f}, conf. {np.std(top3)*1.96/np.sqrt(repeat_time):.3f}, Matching. {np.mean(matching):.3f}, conf. {np.std(matching)*1.96/np.sqrt(repeat_time):.3f}, Multi. {np.mean(multi):.3f}, conf. {np.std(multi)*1.96/np.sqrt(repeat_time):.3f}"
143
+ msg_final = f"FID. {np.mean(fid):.3f}, {np.std(fid)*1.96/np.sqrt(repeat_time):.3f}, FID_word_perb.{np.mean(fid_word_perb):.3f}, {np.std(fid_word_perb)*1.96/np.sqrt(repeat_time):.3f},FID_PERB.{np.mean(fid_per):.3f}, conf. {np.std(fid)*1.96/np.sqrt(repeat_time):.3f}, Diversity. {np.mean(div):.3f}, conf. {np.std(div)*1.96/np.sqrt(repeat_time):.3f}, TOP1. {np.mean(top1):.3f}, conf. {np.std(top1)*1.96/np.sqrt(repeat_time):.3f}, TOP2. {np.mean(top2):.3f}, conf. {np.std(top2)*1.96/np.sqrt(repeat_time):.3f}, TOP3. {np.mean(top3):.3f}, conf. {np.std(top3)*1.96/np.sqrt(repeat_time):.3f}, Matching. {np.mean(matching):.3f}, conf. {np.std(matching)*1.96/np.sqrt(repeat_time):.3f}, conf. {np.std(multi)*1.96/np.sqrt(repeat_time):.3f}"
144
+ logger.info(msg_final)
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 tencent
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,13 +1,227 @@
1
- ---
2
- title: SATO
3
- emoji: 🏃
4
- colorFrom: green
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 4.28.3
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SATO: Stable Text-to-Motion Framework
2
+
3
+ [Wenshuo chen*](https://github.com/shurdy123), [Hongru Xiao*](https://github.com/Hongru0306), [Erhang Zhang*](https://github.com/zhangerhang), [Lijie Hu](https://sites.google.com/view/lijiehu/homepage), [Lei Wang](https://leiwangr.github.io/), [Mengyuan Liu](), [Chen Chen](https://www.crcv.ucf.edu/chenchen/)
4
+
5
+ [![Website shields.io](https://img.shields.io/website?url=http%3A//poco.is.tue.mpg.de)](https://sato-team.github.io/Stable-Text-to-Motion-Framework/) [![YouTube Badge](https://img.shields.io/badge/YouTube-Watch-red?style=flat-square&logo=youtube)]() [![arXiv](https://img.shields.io/badge/arXiv-2308.12965-00ff00.svg)]()
6
+ ## Existing Challenges
7
+ A fundamental challenge inherent in text-to-motion tasks stems from the variability of textual inputs. Even when conveying similar or the same meanings and intentions, texts can exhibit considerable variations in vocabulary and structure due to individual user preferences or linguistic nuances. Despite the considerable advancements made in these models, we find a notable weakness: all of them demonstrate instability in prediction when encountering minor textual perturbations, such as synonym substitutions. In the following demonstration, we showcase the instability of predictions generated by the previous method when presented with different user inputs conveying identical semantic meaning.
8
+ <!-- <div style="display:flex;">
9
+ <img src="assets/run_lola.gif" width="45%" style="margin-right: 1%;">
10
+ <img src="assets/yt_solo.gif" width="45%">
11
+ </div> -->
12
+
13
+ <p align="center">
14
+ <table align="center">
15
+ <tr>
16
+ <th colspan="4">Original text: A man kicks something or someone with his left leg.</th>
17
+ </tr>
18
+ <tr>
19
+ <th align="center"><u><a href="https://github.com/Mael-zys/T2M-GPT"><nobr>T2M-GPT</nobr> </a></u></th>
20
+ <th align="center"><u><a href="https://guytevet.github.io/mdm-page/"><nobr>MDM</nobr> </a></u></th>
21
+ <th align="center"><u><a href="https://github.com/EricGuo5513/momask-codes"><nobr>MoMask</nobr> </a></u></th>
22
+ </tr>
23
+
24
+ <tr>
25
+ <td width="250" align="center"><img src="images/example/kick/gpt.gif" width="150px" height="150px" alt="gif"></td>
26
+ <td width="250" align="center"><img src="images/example/kick/mdm.gif" width="150px" height="150px" alt="gif"></td>
27
+ <td width="250" align="center"><img src="images/example/kick/momask.gif" width="150px" height="150px" alt="gif"></td>
28
+ </tr>
29
+
30
+ <tr>
31
+ <th colspan="4" >Perturbed text: A human boots something or someone with his left leg.</th>
32
+ </tr>
33
+ <tr>
34
+ <th align="center"><u><a href="https://github.com/Mael-zys/T2M-GPT"><nobr>T2M-GPT</nobr> </a></u></th>
35
+ <th align="center"><u><a href="https://guytevet.github.io/mdm-page/"><nobr>MDM</nobr> </a></u></th>
36
+ <th align="center"><u><a href="https://github.com/EricGuo5513/momask-codes"><nobr>MoMask</nobr> </a></u></th>
37
+ </tr>
38
+
39
+ <tr>
40
+ <td width="250" align="center"><img src="images/example/boot/gpt.gif" width="150px" height="150px" alt="gif"></td>
41
+ <td width="250" align="center"><img src="images/example/boot/mdm.gif" width="150px" height="150px" alt="gif"></td>
42
+ <td width="250" align="center"><img src="images/example/boot/momask.gif" width="150px" height="150px" alt="gif"></td>
43
+ </tr>
44
+ </table>
45
+ </p>
46
+
47
+ ## Motivation
48
+ ![motivation](images/motivation.png)
49
+ The model's inconsistent outputs are accompanied by unstable attention patterns. We further elucidate the aforementioned experimental findings: When perturbed text is inputted, the model exhibits unstable attention, often neglecting critical text elements necessary for accurate motion prediction. This instability further complicates the encoding of text into consistent embeddings, leading to a cascade of consecutive temporal motion generation errors.
50
+
51
+
52
+ ## Visualization
53
+ <p align="center">
54
+ <table align="center">
55
+ <tr>
56
+ <th colspan="4">Original text: person is walking normally in a circle.</th>
57
+ </tr>
58
+ <tr>
59
+ <th align="center"><u><a href="https://github.com/Mael-zys/T2M-GPT"><nobr>T2M-GPT</nobr> </a></u></th>
60
+ <th align="center"><u><a href="https://guytevet.github.io/mdm-page/"><nobr>MDM</nobr> </a></u></th>
61
+ <th align="center"><u><a href="https://github.com/EricGuo5513/momask-codes"><nobr>MoMask</nobr> </a></u></th>
62
+ <th align="center"><nobr>SATO</nobr> </th>
63
+ </tr>
64
+
65
+ <tr>
66
+ <td width="250" align="center"><img src="images/visualization/circle/gpt.gif" width="150px" height="150px" alt="gif"></td>
67
+ <td width="250" align="center"><img src="images/visualization/circle/mdm.gif" width="150px" height="150px" alt="gif"></td>
68
+ <td width="250" align="center"><img src="images/visualization/circle/momask.gif" width="150px" height="150px" alt="gif"></td>
69
+ <td width="250" align="center"><img src="images/visualization/circle/sato.gif" width="150px" height="150px" alt="gif"></td>
70
+ </tr>
71
+
72
+ <tr>
73
+ <th colspan="4" >Perturbed text: <span style="color: red;">human</span> is walking <span style="color: red;">usually</span> in a <span style="color: red;">loop.</th>
74
+ </tr>
75
+ <tr>
76
+ <th align="center"><u><a href="https://github.com/Mael-zys/T2M-GPT"><nobr>T2M-GPT</nobr> </a></u></th>
77
+ <th align="center"><u><a href="https://guytevet.github.io/mdm-page/"><nobr>MDM</nobr> </a></u></th>
78
+ <th align="center"><u><a href="https://github.com/EricGuo5513/momask-codes"><nobr>MoMask</nobr> </a></u></th>
79
+ <th align="center"><nobr>SATO</nobr> </th>
80
+ </tr>
81
+
82
+ <tr>
83
+ <td width="250" align="center"><img src="images/visualization/loop/gpt.gif" width="150px" height="150px" alt="gif"></td>
84
+ <td width="250" align="center"><img src="images/visualization/loop/mdm.gif" width="150px" height="150px" alt="gif"></td>
85
+ <td width="250" align="center"><img src="images/visualization/loop/momask.gif" width="150px" height="150px" alt="gif"></td>
86
+ <td width="250" align="center"><img src="images/visualization/loop/sato.gif" width="150px" height="150px" alt="gif"></td>
87
+ </tr>
88
+ </table>
89
+ </p>
90
+ <center>
91
+ <h3>
92
+ <p style="color: blue;">Explanation: T2M-GPT, MDM, and MoMask all don't walk in a loop.</p>
93
+ </h3>
94
+
95
+ <p align="center">
96
+ <table align="center">
97
+ <tr>
98
+ <th colspan="4">Original text: a person uses his right arm to help himself to stand up.</th>
99
+ </tr>
100
+ <tr>
101
+ <th align="center"><u><a href="https://github.com/Mael-zys/T2M-GPT"><nobr>T2M-GPT</nobr> </a></u></th>
102
+ <th align="center"><u><a href="https://guytevet.github.io/mdm-page/"><nobr>MDM</nobr> </a></u></th>
103
+ <th align="center"><u><a href="https://github.com/EricGuo5513/momask-codes"><nobr>MoMask</nobr> </a></u></th>
104
+ <th align="center"><nobr>SATO</nobr> </th>
105
+ </tr>
106
+
107
+ <tr>
108
+ <td width="250" align="center"><img src="images/visualization/use/gpt.gif" width="150px" height="150px" alt="gif"></td>
109
+ <td width="250" align="center"><img src="images/visualization/use/mdm.gif" width="150px" height="150px" alt="gif"></td>
110
+ <td width="250" align="center"><img src="images/visualization/use/momask.gif" width="150px" height="150px" alt="gif"></td>
111
+ <td width="250" align="center"><img src="images/visualization/use/sato.gif" width="150px" height="150px" alt="gif"></td>
112
+ </tr>
113
+
114
+ <tr>
115
+ <th colspan="4" >Perturbed text: A human <span style="color: red;">utilizes</span> his right arm to help himself to stand up.</th>
116
+ </tr>
117
+ <tr>
118
+ <th align="center"><u><a href="https://github.com/Mael-zys/T2M-GPT"><nobr>T2M-GPT</nobr> </a></u></th>
119
+ <th align="center"><u><a href="https://guytevet.github.io/mdm-page/"><nobr>MDM</nobr> </a></u></th>
120
+ <th align="center"><u><a href="https://github.com/EricGuo5513/momask-codes"><nobr>MoMask</nobr> </a></u></th>
121
+ <th align="center"><nobr>SATO</nobr> </th>
122
+ </tr>
123
+
124
+ <tr>
125
+ <td width="250" align="center"><img src="images/visualization/utilize/gpt.gif" width="150px" height="150px" alt="gif"></td>
126
+ <td width="250" align="center"><img src="images/visualization/utilize/mdm.gif" width="150px" height="150px" alt="gif"></td>
127
+ <td width="250" align="center"><img src="images/visualization/utilize/momask.gif" width="150px" height="150px" alt="gif"></td>
128
+ <td width="250" align="center"><img src="images/visualization/utilize/sato.gif" width="150px" height="150px" alt="gif"></td>
129
+ </tr>
130
+ </table>
131
+ </p>
132
+ <center>
133
+ <h3>
134
+ <p style="color: blue;">Explanation: T2M-GPT, MDM, and MoMask all lack the action of transitioning from squatting to standing up, resulting in a catastrophic error.</p>
135
+ </h3>
136
+
137
+
138
+ ## How to Use the Code
139
+
140
+ * [1. Setup and Installation](#setup)
141
+
142
+ * [2.Dependencies](#Dependencies)
143
+
144
+ * [3. Quick Start](#quickstart)
145
+
146
+ * [4. Datasets](#datasets)
147
+
148
+ * [4. Train](#train)
149
+
150
+ * [5. Evaluation](#eval)
151
+
152
+ * [6. Acknowledgments](#acknowledgements)
153
+
154
+
155
+ ## Setup and Installation <a name="setup"></a>
156
+
157
+ Clone the repository:
158
+
159
+ ```shell
160
+ git clone https://github.com/sato-team/Stable-Text-to-motion-Framework.git
161
+ ```
162
+
163
+ Create fresh conda environment and install all the dependencies:
164
+
165
+ ```
166
+ conda env create -f environment.yml
167
+ conda activate SATO
168
+ ```
169
+
170
+ The code was tested on Python 3.8 and PyTorch 1.8.1.
171
+
172
+ ## Dependencies<a name="Dependencies"></a>
173
+
174
+ ```shell
175
+ bash dataset/prepare/download_extractor.sh
176
+ bash dataset/prepare/download_glove.sh
177
+ ```
178
+
179
+ ## **Quick Start**<a name="quickstart"></a>
180
+
181
+ A quick reference guide for using our code is provided in quickstart.ipynb.
182
+
183
+ ## Datasets<a name="datasets"></a>
184
+
185
+ We are using two 3D human motion-language dataset: HumanML3D and KIT-ML. For both datasets, you could find the details as well as download [link](https://github.com/EricGuo5513/HumanML3D).
186
+ We perturbed the input texts based on the two datasets mentioned. You can access the perturbed text dataset through the following [link](https://drive.google.com/file/d/1XLvu2jfG1YKyujdANhYHV_NfFTyOJPvP/view?usp=sharing).
187
+ Take HumanML3D for an example, the dataset structure should look like this:
188
+ ```
189
+ ./dataset/HumanML3D/
190
+ ├── new_joint_vecs/
191
+ ├── texts/ # You need to replace the 'texts' folder in the original dataset with the 'texts' folder from our dataset.
192
+ ├── Mean.npy
193
+ ├── Std.npy
194
+ ├── train.txt
195
+ ├── val.txt
196
+ ├── test.txt
197
+ ├── train_val.txt
198
+ └── all.txt
199
+ ```
200
+ ### **Train**<a name="train"></a>
201
+
202
+ We will release the training code soon.
203
+
204
+ ### **Evaluation**<a name="eval"></a>
205
+
206
+ You can download the pretrained models in this [link](https://drive.google.com/drive/folders/1rs8QPJ3UPzLW4H3vWAAX9hJn4ln7m_ts?usp=sharing).
207
+
208
+ ```shell
209
+ python eval_t2m.py --resume-pth pretrained/net_best_fid.pth --clip_path pretrained/clip_best_fid.pth
210
+ ```
211
+
212
+ ## Acknowledgements<a name="acknowledgements"></a>
213
+
214
+ We appreciate helps from :
215
+
216
+ - Open Source Code:[T2M-GPT](https://github.com/Mael-zys/T2M-GPT), [MoMask ](https://github.com/EricGuo5513/momask-codes), [MDM](https://guytevet.github.io/mdm-page/), etc.
217
+ - [Hongru Xiao](https://github.com/Hongru0306), [Erhang Zhang](https://github.com/zhangerhang), [Lijie Hu](https://sites.google.com/view/lijiehu/homepage), [Lei Wang](https://leiwangr.github.io/), [Mengyuan Liu](), [Chen Chen](https://www.crcv.ucf.edu/chenchen/) for discussions and guidance throughout the project, which has been instrumental to our work.
218
+ - [Zhen Zhao](https://github.com/Zanebla) for project website.
219
+ - If you find our work helpful, we would appreciate it if you could give our project a star!
220
+ ## Citing<a name="citing"></a>
221
+
222
+ If you find this code useful for your research, please consider citing the following paper:
223
+
224
+ ```bibtex
225
+
226
+ ```
227
+
VQ_eval.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+
4
+ import torch
5
+ from torch.utils.tensorboard import SummaryWriter
6
+ import numpy as np
7
+ import models.vqvae as vqvae
8
+ import options.option_vq as option_vq
9
+ import utils.utils_model as utils_model
10
+ from dataset import dataset_TM_eval
11
+ import utils.eval_trans as eval_trans
12
+ from options.get_eval_option import get_opt
13
+ from models.evaluator_wrapper import EvaluatorModelWrapper
14
+ import warnings
15
+ warnings.filterwarnings('ignore')
16
+ import numpy as np
17
+ ##### ---- Exp dirs ---- #####
18
+ args = option_vq.get_args_parser()
19
+ torch.manual_seed(args.seed)
20
+
21
+ args.out_dir = os.path.join(args.out_dir, f'{args.exp_name}')
22
+ os.makedirs(args.out_dir, exist_ok = True)
23
+
24
+ ##### ---- Logger ---- #####
25
+ logger = utils_model.get_logger(args.out_dir)
26
+ writer = SummaryWriter(args.out_dir)
27
+ logger.info(json.dumps(vars(args), indent=4, sort_keys=True))
28
+
29
+
30
+ from utils.word_vectorizer import WordVectorizer
31
+ w_vectorizer = WordVectorizer('./glove', 'our_vab')
32
+
33
+
34
+ dataset_opt_path = 'checkpoints/kit/Comp_v6_KLD005/opt.txt' if args.dataname == 'kit' else 'checkpoints/t2m/Comp_v6_KLD005/opt.txt'
35
+
36
+ wrapper_opt = get_opt(dataset_opt_path, torch.device('cuda'))
37
+ eval_wrapper = EvaluatorModelWrapper(wrapper_opt)
38
+
39
+
40
+ ##### ---- Dataloader ---- #####
41
+ args.nb_joints = 21 if args.dataname == 'kit' else 22
42
+
43
+ val_loader = dataset_TM_eval.DATALoader(args.dataname, True, 32, w_vectorizer, unit_length=2**args.down_t)
44
+
45
+ ##### ---- Network ---- #####
46
+ net = vqvae.HumanVQVAE(args, ## use args to define different parameters in different quantizers
47
+ args.nb_code,
48
+ args.code_dim,
49
+ args.output_emb_width,
50
+ args.down_t,
51
+ args.stride_t,
52
+ args.width,
53
+ args.depth,
54
+ args.dilation_growth_rate,
55
+ args.vq_act,
56
+ args.vq_norm)
57
+
58
+ if args.resume_pth :
59
+ logger.info('loading checkpoint from {}'.format(args.resume_pth))
60
+ ckpt = torch.load(args.resume_pth, map_location='cpu')
61
+ net.load_state_dict(ckpt['net'], strict=True)
62
+ net.train()
63
+ net.cuda()
64
+
65
+ fid = []
66
+ div = []
67
+ top1 = []
68
+ top2 = []
69
+ top3 = []
70
+ matching = []
71
+ repeat_time = 20
72
+ for i in range(repeat_time):
73
+ best_fid, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, writer, logger = eval_trans.evaluation_vqvae(args.out_dir, val_loader, net, logger, writer, 0, best_fid=1000, best_iter=0, best_div=100, best_top1=0, best_top2=0, best_top3=0, best_matching=100, eval_wrapper=eval_wrapper, draw=False, save=False, savenpy=(i==0))
74
+ fid.append(best_fid)
75
+ div.append(best_div)
76
+ top1.append(best_top1)
77
+ top2.append(best_top2)
78
+ top3.append(best_top3)
79
+ matching.append(best_matching)
80
+ print('final result:')
81
+ print('fid: ', sum(fid)/repeat_time)
82
+ print('div: ', sum(div)/repeat_time)
83
+ print('top1: ', sum(top1)/repeat_time)
84
+ print('top2: ', sum(top2)/repeat_time)
85
+ print('top3: ', sum(top3)/repeat_time)
86
+ print('matching: ', sum(matching)/repeat_time)
87
+
88
+ fid = np.array(fid)
89
+ div = np.array(div)
90
+ top1 = np.array(top1)
91
+ top2 = np.array(top2)
92
+ top3 = np.array(top3)
93
+ matching = np.array(matching)
94
+ msg_final = f"FID. {np.mean(fid):.3f}, conf. {np.std(fid)*1.96/np.sqrt(repeat_time):.3f}, Diversity. {np.mean(div):.3f}, conf. {np.std(div)*1.96/np.sqrt(repeat_time):.3f}, TOP1. {np.mean(top1):.3f}, conf. {np.std(top1)*1.96/np.sqrt(repeat_time):.3f}, TOP2. {np.mean(top2):.3f}, conf. {np.std(top2)*1.96/np.sqrt(repeat_time):.3f}, TOP3. {np.mean(top3):.3f}, conf. {np.std(top3)*1.96/np.sqrt(repeat_time):.3f}, Matching. {np.mean(matching):.3f}, conf. {np.std(matching)*1.96/np.sqrt(repeat_time):.3f}"
95
+ logger.info(msg_final)
attack.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
4
+
5
+ class PGDAttacker():
6
+ def __init__(self, radius, steps, step_size, random_start, norm_type, ascending=True):
7
+ self.radius = radius # attack radius
8
+ self.steps = steps # how many step to conduct pgd
9
+ self.step_size = step_size # coefficient of PGD
10
+ self.random_start = random_start
11
+ self.norm_type = norm_type # which norm of your noise
12
+ self.ascending = ascending # perform gradient ascending, i.e, to maximum the loss
13
+
14
+ def output(self, x, model, tokens_lens, text_token):
15
+
16
+ x = x + model.positional_embedding.type(model.dtype)
17
+
18
+ x = x.permute(1, 0, 2) # NLD -> LND
19
+ x, weight = model.transformer(x)
20
+ x = x.permute(1, 0, 2) # LND -> NLD
21
+ x = model.ln_final(x).type(model.dtype)
22
+ x = x[torch.arange(x.shape[0]), text_token.argmax(dim=-1)] @ model.text_projection
23
+
24
+ attention_weights_all = []
25
+ for i in range(len(tokens_lens)):
26
+ attention_weights = weight[-1][i][min(76, tokens_lens[i])][:1+min(75, max(tokens_lens))][1:][:-1]
27
+ attention_weights_all.append(attention_weights)
28
+ attention_weights = torch.stack(attention_weights_all, dim=0)
29
+
30
+ return x, attention_weights
31
+
32
+ def perturb(self, device, m_tokens_len, bs, criterion, x, y,a_indices,encoder, tokens_lens=None, model=None, text_token=None):
33
+ if self.steps==0 or self.radius==0:
34
+ return x.clone()
35
+
36
+ adv_x = x.clone()
37
+
38
+ if self.random_start:
39
+ if self.norm_type == 'l-infty':
40
+ adv_x += 2 * (torch.rand_like(x) - 0.5) * self.radius
41
+ else:
42
+ adv_x += 2 * (torch.rand_like(x) - 0.5) * self.radius / self.steps
43
+ self._clip_(adv_x, x)
44
+
45
+ ''' temporarily shutdown autograd of model to improve pgd efficiency '''
46
+ # adv_x, attention_weights = self.output(adv_x, model, tokens_lens, text_token)
47
+
48
+ # model.eval()
49
+ encoder.eval()
50
+ for pp in encoder.parameters():
51
+ pp.requires_grad = False
52
+
53
+ for step in range(self.steps):
54
+ adv_x_o = adv_x.clone()
55
+ adv_x.requires_grad_()
56
+ _y = encoder(a_indices,adv_x)
57
+ loss = criterion(y.to(device), _y, m_tokens_len, bs)
58
+ grad = torch.autograd.grad(loss, [adv_x])[0]
59
+
60
+ with torch.no_grad():
61
+ if not self.ascending: grad.mul_(-1)
62
+
63
+ if self.norm_type == 'l-infty':
64
+ adv_x.add_(torch.sign(grad), alpha=self.step_size)
65
+ else:
66
+ if self.norm_type == 'l2':
67
+ grad_norm = (grad.reshape(grad.shape[0],-1)**2).sum(dim=1).sqrt()
68
+ elif self.norm_type == 'l1':
69
+ grad_norm = grad.reshape(grad.shape[0],-1).abs().sum(dim=1)
70
+ grad_norm = grad_norm.reshape( -1, *( [1] * (len(x.shape)-1) ) )
71
+ scaled_grad = grad / (grad_norm + 1e-10)
72
+ adv_x.add_(scaled_grad, alpha=self.step_size)
73
+
74
+ self._clip_(adv_x, adv_x_o)
75
+
76
+ ''' reopen autograd of model after pgd '''
77
+ # decoder.trian()
78
+ for pp in encoder.parameters():
79
+ pp.requires_grad = True
80
+
81
+ return adv_x # , attention_weights
82
+
83
+ def perturb_random(self, criterion, x, data, decoder,y,target_model,encoder=None):
84
+ if self.steps==0 or self.radius==0:
85
+ return x.clone()
86
+ adv_x = x.clone()
87
+ if self.norm_type == 'l-infty':
88
+ adv_x += 2 * (torch.rand_like(x) - 0.5) * self.radius
89
+ else:
90
+ adv_x += 2 * (torch.rand_like(x) - 0.5) * self.radius / self.steps
91
+ self._clip_(adv_x, x)
92
+ return adv_x.data
93
+
94
+ def perturb_iat(self, criterion, x, data, decoder,y,target_model,encoder=None):
95
+ if self.steps==0 or self.radius==0:
96
+ return x.clone()
97
+
98
+ B = x.shape[0]
99
+ L = x.shape[1]
100
+ H = x.shape[2]
101
+ nb_num = 8
102
+
103
+ alpha = torch.rand(B,L,nb_num,1).to(device)
104
+
105
+ A_1 = x.unsqueeze(2).expand(B,L,nb_num,H)
106
+ A_2 = x.unsqueeze(1).expand(B,L,L,H)
107
+ rand_idx = []
108
+ for i in range(L):
109
+ rand_idx.append(np.random.choice(L,nb_num,replace=False))
110
+ rand_idx = np.array(rand_idx)
111
+ rand_idx = torch.tensor(rand_idx).long().reshape(1,L,1,nb_num).expand(B,L,H,nb_num).to(device)
112
+ # A_2 = A_2[:,np.arange(0,L), rand_idx,:]
113
+ A_2 = torch.gather(A_2.reshape(B,L,H,L),-1,rand_idx).reshape(B,L,nb_num, H)
114
+ A_e = A_1 - A_2
115
+ # A_e
116
+ # adv_x = (A_e * alpha).sum(dim=-1) + x.clone()
117
+
118
+ adv_x = x.clone()
119
+
120
+ if self.random_start:
121
+ if self.norm_type == 'l-infty':
122
+ adv_x += 2 * (torch.rand_like(x) - 0.5) * self.radius
123
+ else:
124
+ adv_x += 2 * (torch.rand_like(x) - 0.5) * self.radius / self.steps
125
+ self._clip_(adv_x, x)
126
+
127
+ # assert adv_x.shape[0] == 8
128
+
129
+ ''' temporarily shutdown autograd of model to improve pgd efficiency '''
130
+ # model.eval()
131
+ decoder.eval()
132
+ for pp in decoder.parameters():
133
+ pp.requires_grad = False
134
+
135
+ adv_x = x.clone()
136
+
137
+ alpha.requires_grad_()
138
+
139
+ for step in range(self.steps):
140
+ alpha.requires_grad_()
141
+ dot_Ae_alpha = (A_e * alpha).sum(dim=-2)
142
+ # print("dot_Ae_alpha:", dot_Ae_alpha.shape)
143
+
144
+ adv_x.add_(torch.sign(dot_Ae_alpha), alpha=self.step_size)
145
+
146
+ self._clip_(adv_x, x)
147
+
148
+ if encoder is None:
149
+ adv_x_input = adv_x.squeeze(-1)
150
+ else:
151
+ adv_x_input = adv_x
152
+
153
+ _y = target_model(adv_x_input, data,decoder,encoder)
154
+ loss = criterion(y.to(device), _y)
155
+ grad = torch.autograd.grad(loss, [alpha],retain_graph=True)[0]
156
+ # with torch.no_grad():
157
+ with torch.no_grad():
158
+ if not self.ascending: grad.mul_(-1)
159
+ assert self.norm_type == 'l-infty'
160
+ alpha = alpha.detach()+ grad * 0.01
161
+
162
+ ''' reopen autograd of model after pgd '''
163
+ # decoder.trian()
164
+ for pp in decoder.parameters():
165
+ pp.requires_grad = True
166
+
167
+ return adv_x.data
168
+
169
+ def _clip_(self, adv_x, x):
170
+ adv_x -= x
171
+ if self.norm_type == 'l-infty':
172
+ adv_x.clamp_(-self.radius, self.radius)
173
+ else:
174
+ if self.norm_type == 'l2':
175
+ norm = (adv_x.reshape(adv_x.shape[0],-1)**2).sum(dim=1).sqrt()
176
+ elif self.norm_type == 'l1':
177
+ norm = adv_x.reshape(adv_x.shape[0],-1).abs().sum(dim=1)
178
+ norm = norm.reshape( -1, *( [1] * (len(x.shape)-1) ) )
179
+ adv_x /= (norm + 1e-10)
180
+ adv_x *= norm.clamp(max=self.radius)
181
+ adv_x += x
182
+ adv_x.clamp_(0, 1)
environment.yml ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: SATO
2
+ channels:
3
+ - pytorch
4
+ - defaults
5
+ dependencies:
6
+ - _libgcc_mutex=0.1=main
7
+ - _openmp_mutex=4.5=1_gnu
8
+ - blas=1.0=mkl
9
+ - bzip2=1.0.8=h7b6447c_0
10
+ - ca-certificates=2021.7.5=h06a4308_1
11
+ - certifi=2021.5.30=py38h06a4308_0
12
+ - cudatoolkit=10.1.243=h6bb024c_0
13
+ - ffmpeg=4.3=hf484d3e_0
14
+ - freetype=2.10.4=h5ab3b9f_0
15
+ - gmp=6.2.1=h2531618_2
16
+ - gnutls=3.6.15=he1e5248_0
17
+ - intel-openmp=2021.3.0=h06a4308_3350
18
+ - jpeg=9b=h024ee3a_2
19
+ - lame=3.100=h7b6447c_0
20
+ - lcms2=2.12=h3be6417_0
21
+ - ld_impl_linux-64=2.35.1=h7274673_9
22
+ - libffi=3.3=he6710b0_2
23
+ - libgcc-ng=9.3.0=h5101ec6_17
24
+ - libgomp=9.3.0=h5101ec6_17
25
+ - libiconv=1.15=h63c8f33_5
26
+ - libidn2=2.3.2=h7f8727e_0
27
+ - libpng=1.6.37=hbc83047_0
28
+ - libstdcxx-ng=9.3.0=hd4cf53a_17
29
+ - libtasn1=4.16.0=h27cfd23_0
30
+ - libtiff=4.2.0=h85742a9_0
31
+ - libunistring=0.9.10=h27cfd23_0
32
+ - libuv=1.40.0=h7b6447c_0
33
+ - libwebp-base=1.2.0=h27cfd23_0
34
+ - lz4-c=1.9.3=h295c915_1
35
+ - mkl=2021.3.0=h06a4308_520
36
+ - mkl-service=2.4.0=py38h7f8727e_0
37
+ - mkl_fft=1.3.0=py38h42c9631_2
38
+ - mkl_random=1.2.2=py38h51133e4_0
39
+ - ncurses=6.2=he6710b0_1
40
+ - nettle=3.7.3=hbbd107a_1
41
+ - ninja=1.10.2=hff7bd54_1
42
+ - numpy=1.20.3=py38hf144106_0
43
+ - numpy-base=1.20.3=py38h74d4b33_0
44
+ - olefile=0.46=py_0
45
+ - openh264=2.1.0=hd408876_0
46
+ - openjpeg=2.3.0=h05c96fa_1
47
+ - openssl=1.1.1k=h27cfd23_0
48
+ - pillow=8.3.1=py38h2c7a002_0
49
+ - pip=21.0.1=py38h06a4308_0
50
+ - python=3.8.11=h12debd9_0_cpython
51
+ - pytorch=1.8.1=py3.8_cuda10.1_cudnn7.6.3_0
52
+ - readline=8.1=h27cfd23_0
53
+ - setuptools=52.0.0=py38h06a4308_0
54
+ - six=1.16.0=pyhd3eb1b0_0
55
+ - sqlite=3.36.0=hc218d9a_0
56
+ - tk=8.6.10=hbc83047_0
57
+ - torchaudio=0.8.1=py38
58
+ - torchvision=0.9.1=py38_cu101
59
+ - typing_extensions=3.10.0.0=pyh06a4308_0
60
+ - wheel=0.37.0=pyhd3eb1b0_0
61
+ - xz=5.2.5=h7b6447c_0
62
+ - zlib=1.2.11=h7b6447c_3
63
+ - zstd=1.4.9=haebb681_0
64
+ - pip:
65
+ - absl-py==0.13.0
66
+ - backcall==0.2.0
67
+ - cachetools==4.2.2
68
+ - charset-normalizer==2.0.4
69
+ - chumpy==0.70
70
+ - cycler==0.10.0
71
+ - decorator==5.0.9
72
+ - google-auth==1.35.0
73
+ - google-auth-oauthlib==0.4.5
74
+ - grpcio==1.39.0
75
+ - idna==3.2
76
+ - imageio==2.9.0
77
+ - ipdb==0.13.9
78
+ - ipython==7.26.0
79
+ - ipython-genutils==0.2.0
80
+ - jedi==0.18.0
81
+ - joblib==1.0.1
82
+ - kiwisolver==1.3.1
83
+ - markdown==3.3.4
84
+ - matplotlib==3.4.3
85
+ - matplotlib-inline==0.1.2
86
+ - oauthlib==3.1.1
87
+ - pandas==1.3.2
88
+ - parso==0.8.2
89
+ - pexpect==4.8.0
90
+ - pickleshare==0.7.5
91
+ - prompt-toolkit==3.0.20
92
+ - protobuf==3.17.3
93
+ - ptyprocess==0.7.0
94
+ - pyasn1==0.4.8
95
+ - pyasn1-modules==0.2.8
96
+ - pygments==2.10.0
97
+ - pyparsing==2.4.7
98
+ - python-dateutil==2.8.2
99
+ - pytz==2021.1
100
+ - pyyaml==5.4.1
101
+ - requests==2.26.0
102
+ - requests-oauthlib==1.3.0
103
+ - rsa==4.7.2
104
+ - scikit-learn==0.24.2
105
+ - scipy==1.7.1
106
+ - sklearn==0.0
107
+ - smplx==0.1.28
108
+ - tensorboard==2.6.0
109
+ - tensorboard-data-server==0.6.1
110
+ - tensorboard-plugin-wit==1.8.0
111
+ - threadpoolctl==2.2.0
112
+ - toml==0.10.2
113
+ - tqdm==4.62.2
114
+ - traitlets==5.0.5
115
+ - urllib3==1.26.6
116
+ - wcwidth==0.2.5
117
+ - werkzeug==2.0.1
118
+ - git+https://github.com/openai/CLIP.git
119
+ - git+https://github.com/nghorbani/human_body_prior
120
+ - gdown
121
+ - moviepy
eval_trans_per.py ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ # import clip
4
+ from CLIP.clip import clip
5
+ import numpy as np
6
+ import torch
7
+ from scipy import linalg
8
+ from tqdm import tqdm
9
+ import visualization.plot_3d_global as plot_3d
10
+ from utils.motion_process import recover_from_ric
11
+ from tqdm import trange
12
+
13
+ def tensorborad_add_video_xyz(writer, xyz, nb_iter, tag, nb_vis=4, title_batch=None, outname=None):
14
+ xyz = xyz[:1]
15
+ bs, seq = xyz.shape[:2]
16
+ xyz = xyz.reshape(bs, seq, -1, 3)
17
+ plot_xyz = plot_3d.draw_to_batch(xyz.cpu().numpy(),title_batch, outname)
18
+ plot_xyz =np.transpose(plot_xyz, (0, 1, 4, 2, 3))
19
+ writer.add_video(tag, plot_xyz, nb_iter, fps = 20)
20
+
21
+ @torch.no_grad()
22
+ def evaluation_vqvae(out_dir, val_loader, net, logger, writer, nb_iter, best_fid, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, eval_wrapper, draw = True, save = True, savegif=False, savenpy=False) :
23
+ net.eval()
24
+ nb_sample = 0
25
+
26
+ draw_org = []
27
+ draw_pred = []
28
+ draw_text = []
29
+
30
+
31
+ motion_annotation_list = []
32
+ motion_pred_list = []
33
+
34
+ R_precision_real = 0
35
+ R_precision = 0
36
+
37
+ nb_sample = 0
38
+ matching_score_real = 0
39
+ matching_score_pred = 0
40
+ for batch in val_loader:
41
+ word_embeddings, pos_one_hots, caption, sent_len, motion, m_length, token, name = batch
42
+
43
+ motion = motion.cuda()
44
+ et, em = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, motion, m_length)
45
+ bs, seq = motion.shape[0], motion.shape[1]
46
+
47
+ num_joints = 21 if motion.shape[-1] == 251 else 22
48
+
49
+ pred_pose_eval = torch.zeros((bs, seq, motion.shape[-1])).cuda()
50
+
51
+ for i in range(bs):
52
+ pose = val_loader.dataset.inv_transform(motion[i:i+1, :m_length[i], :].detach().cpu().numpy())
53
+ pose_xyz = recover_from_ric(torch.from_numpy(pose).float().cuda(), num_joints)
54
+
55
+
56
+ pred_pose, loss_commit, perplexity = net(motion[i:i+1, :m_length[i]])
57
+ pred_denorm = val_loader.dataset.inv_transform(pred_pose.detach().cpu().numpy())
58
+ pred_xyz = recover_from_ric(torch.from_numpy(pred_denorm).float().cuda(), num_joints)
59
+
60
+ if savenpy:
61
+ np.save(os.path.join(out_dir, name[i]+'_gt.npy'), pose_xyz[:, :m_length[i]].cpu().numpy())
62
+ np.save(os.path.join(out_dir, name[i]+'_pred.npy'), pred_xyz.detach().cpu().numpy())
63
+
64
+ pred_pose_eval[i:i+1,:m_length[i],:] = pred_pose
65
+
66
+ if i < min(4, bs):
67
+ draw_org.append(pose_xyz)
68
+ draw_pred.append(pred_xyz)
69
+ draw_text.append(caption[i])
70
+
71
+ et_pred, em_pred = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, pred_pose_eval, m_length)
72
+
73
+ motion_pred_list.append(em_pred)
74
+ motion_annotation_list.append(em)
75
+
76
+ temp_R, temp_match = calculate_R_precision(et.cpu().numpy(), em.cpu().numpy(), top_k=3, sum_all=True)
77
+ R_precision_real += temp_R
78
+ matching_score_real += temp_match
79
+ temp_R, temp_match = calculate_R_precision(et_pred.cpu().numpy(), em_pred.cpu().numpy(), top_k=3, sum_all=True)
80
+ R_precision += temp_R
81
+ matching_score_pred += temp_match
82
+
83
+ nb_sample += bs
84
+
85
+ motion_annotation_np = torch.cat(motion_annotation_list, dim=0).cpu().numpy()
86
+ motion_pred_np = torch.cat(motion_pred_list, dim=0).cpu().numpy()
87
+ gt_mu, gt_cov = calculate_activation_statistics(motion_annotation_np)
88
+ mu, cov= calculate_activation_statistics(motion_pred_np)
89
+
90
+ diversity_real = calculate_diversity(motion_annotation_np, 300 if nb_sample > 300 else 100)
91
+ diversity = calculate_diversity(motion_pred_np, 300 if nb_sample > 300 else 100)
92
+
93
+ R_precision_real = R_precision_real / nb_sample
94
+ R_precision = R_precision / nb_sample
95
+
96
+ matching_score_real = matching_score_real / nb_sample
97
+ matching_score_pred = matching_score_pred / nb_sample
98
+
99
+ fid = calculate_frechet_distance(gt_mu, gt_cov, mu, cov)
100
+
101
+ msg = f"--> \t Eva. Iter {nb_iter} :, FID. {fid:.4f}, Diversity Real. {diversity_real:.4f}, Diversity. {diversity:.4f}, R_precision_real. {R_precision_real}, R_precision. {R_precision}, matching_score_real. {matching_score_real}, matching_score_pred. {matching_score_pred}"
102
+ logger.info(msg)
103
+
104
+ if draw:
105
+ writer.add_scalar('./Test/FID', fid, nb_iter)
106
+ writer.add_scalar('./Test/Diversity', diversity, nb_iter)
107
+ writer.add_scalar('./Test/top1', R_precision[0], nb_iter)
108
+ writer.add_scalar('./Test/top2', R_precision[1], nb_iter)
109
+ writer.add_scalar('./Test/top3', R_precision[2], nb_iter)
110
+ writer.add_scalar('./Test/matching_score', matching_score_pred, nb_iter)
111
+
112
+
113
+ if nb_iter % 5000 == 0 :
114
+ for ii in range(4):
115
+ tensorborad_add_video_xyz(writer, draw_org[ii], nb_iter, tag='./Vis/org_eval'+str(ii), nb_vis=1, title_batch=[draw_text[ii]], outname=[os.path.join(out_dir, 'gt'+str(ii)+'.gif')] if savegif else None)
116
+
117
+ if nb_iter % 5000 == 0 :
118
+ for ii in range(4):
119
+ tensorborad_add_video_xyz(writer, draw_pred[ii], nb_iter, tag='./Vis/pred_eval'+str(ii), nb_vis=1, title_batch=[draw_text[ii]], outname=[os.path.join(out_dir, 'pred'+str(ii)+'.gif')] if savegif else None)
120
+
121
+
122
+ if fid < best_fid :
123
+ print(fid,best_fid)
124
+
125
+ msg = f"--> --> \t FID Improved from {best_fid:.5f} to {fid:.5f} !!!"
126
+ logger.info(msg)
127
+ best_fid, best_iter = fid, nb_iter
128
+ if save:
129
+ torch.save({'net' : net.state_dict()}, os.path.join(out_dir, 'net_best_fid.pth'))
130
+
131
+ if abs(diversity_real - diversity) < abs(diversity_real - best_div) :
132
+ msg = f"--> --> \t Diversity Improved from {best_div:.5f} to {diversity:.5f} !!!"
133
+ logger.info(msg)
134
+ best_div = diversity
135
+ if save:
136
+ torch.save({'net' : net.state_dict()}, os.path.join(out_dir, 'net_best_div.pth'))
137
+
138
+ if R_precision[0] > best_top1 :
139
+ msg = f"--> --> \t Top1 Improved from {best_top1:.4f} to {R_precision[0]:.4f} !!!"
140
+ logger.info(msg)
141
+ best_top1 = R_precision[0]
142
+ if save:
143
+ torch.save({'net' : net.state_dict()}, os.path.join(out_dir, 'net_best_top1.pth'))
144
+
145
+ if R_precision[1] > best_top2 :
146
+ msg = f"--> --> \t Top2 Improved from {best_top2:.4f} to {R_precision[1]:.4f} !!!"
147
+ logger.info(msg)
148
+ best_top2 = R_precision[1]
149
+
150
+ if R_precision[2] > best_top3 :
151
+ msg = f"--> --> \t Top3 Improved from {best_top3:.4f} to {R_precision[2]:.4f} !!!"
152
+ logger.info(msg)
153
+ best_top3 = R_precision[2]
154
+
155
+ if matching_score_pred < best_matching :
156
+ msg = f"--> --> \t matching_score Improved from {best_matching:.5f} to {matching_score_pred:.5f} !!!"
157
+ logger.info(msg)
158
+ best_matching = matching_score_pred
159
+ if save:
160
+ torch.save({'net' : net.state_dict()}, os.path.join(out_dir, 'net_best_matching.pth'))
161
+
162
+ if save:
163
+ torch.save({'net' : net.state_dict()}, os.path.join(out_dir, 'net_last.pth'))
164
+
165
+ net.train()
166
+ return best_fid, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, writer, logger
167
+
168
+
169
+ @torch.no_grad()
170
+ def evaluation_transformer(out_dir, val_loader, net, trans, logger, writer, nb_iter, best_fid, best_fid_syn,best_fid_perturbation,best_iter, best_div, best_top1, best_top2, best_top3, best_matching, clip_model, eval_wrapper, draw = True, save = True, savegif=False,PGD=None,crit=None) :
171
+
172
+ trans.eval()
173
+ #这里是不是应该clip也eval()
174
+ nb_sample = 0
175
+
176
+ draw_org = []
177
+ draw_pred = []
178
+ draw_text = []
179
+ draw_text_pred = []
180
+
181
+ motion_annotation_list = []
182
+ motion_pred_list = []
183
+ motion_pred_per_list = []
184
+ R_precision_real = 0
185
+ R_precision = 0
186
+ matching_score_real = 0
187
+ matching_score_pred = 0
188
+
189
+ nb_sample = 0
190
+ for i in range(1):
191
+ for batch in tqdm(val_loader):
192
+ word_embeddings, pos_one_hots, clip_text, clip_text_perb, sent_len, pose, m_length, token, name = batch
193
+
194
+ bs, seq = pose.shape[:2]
195
+ num_joints = 21 if pose.shape[-1] == 251 else 22
196
+
197
+ text = clip.tokenize(clip_text, truncate=True).cuda()
198
+ text_perb = clip.tokenize(clip_text_perb, truncate=True).cuda()
199
+
200
+
201
+ feat_clip_text = clip_model.encode_text(text)[0].float()
202
+ feat_clip_text_per = clip_model.encode_text(text_perb)[0].float()
203
+
204
+
205
+ pred_pose_eval = torch.zeros((bs, seq, pose.shape[-1])).cuda()
206
+ pred_pose_eval_per = torch.zeros((bs, seq, pose.shape[-1])).cuda()
207
+ pred_len = torch.ones(bs).long()
208
+ pred_len_per = torch.ones(bs).long()
209
+
210
+ for k in range(bs):
211
+ try:
212
+ index_motion = trans.sample(feat_clip_text[k:k+1], False)
213
+ index_motion_per = trans.sample(feat_clip_text_per[k:k+1], False)
214
+ except:
215
+ # print('---------------------')
216
+ index_motion = torch.ones(1,1).cuda().long()
217
+ index_motion_per = torch.ones(1,1).cuda().long()
218
+
219
+ pred_pose = net.forward_decoder(index_motion)
220
+ pred_pose_per = net.forward_decoder(index_motion_per)
221
+
222
+ cur_len = pred_pose.shape[1]
223
+ cur_len_per = pred_pose_per.shape[1]
224
+
225
+ pred_len[k] = min(cur_len, seq)
226
+ pred_len_per[k] = min(cur_len_per, seq)
227
+ pred_pose_eval[k:k+1, :cur_len] = pred_pose[:, :seq]
228
+ pred_pose_eval_per[k:k+1, :cur_len_per] = pred_pose_per[:, :seq]
229
+
230
+ if draw:
231
+ pred_denorm = val_loader.dataset.inv_transform(pred_pose.detach().cpu().numpy())
232
+ pred_xyz = recover_from_ric(torch.from_numpy(pred_denorm).float().cuda(), num_joints)
233
+
234
+ if i == 0 and k < 4:
235
+ draw_pred.append(pred_xyz)
236
+ draw_text_pred.append(clip_text[k])
237
+
238
+ et_pred, em_pred = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, pred_pose_eval, pred_len)
239
+ et_pred_per, em_pred_per = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, pred_pose_eval_per, pred_len_per)
240
+
241
+ if i == 0:
242
+ pose = pose.cuda().float()
243
+
244
+ et, em = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, pose, m_length)
245
+ motion_annotation_list.append(em)
246
+ motion_pred_list.append(em_pred)
247
+ motion_pred_per_list.append(em_pred_per)
248
+
249
+ if draw:
250
+ pose = val_loader.dataset.inv_transform(pose.detach().cpu().numpy())
251
+ pose_xyz = recover_from_ric(torch.from_numpy(pose).float().cuda(), num_joints)
252
+
253
+
254
+ for j in range(min(4, bs)):
255
+ draw_org.append(pose_xyz[j][:m_length[j]].unsqueeze(0))
256
+ draw_text.append(clip_text[j])
257
+
258
+ temp_R, temp_match = calculate_R_precision(et.cpu().numpy(), em.cpu().numpy(), top_k=3, sum_all=True)
259
+ R_precision_real += temp_R
260
+ matching_score_real += temp_match
261
+ temp_R, temp_match = calculate_R_precision(et_pred.cpu().numpy(), em_pred.cpu().numpy(), top_k=3, sum_all=True)
262
+ R_precision += temp_R
263
+ matching_score_pred += temp_match
264
+
265
+ nb_sample += bs
266
+
267
+ motion_annotation_np = torch.cat(motion_annotation_list, dim=0).cpu().numpy()
268
+ motion_pred_np = torch.cat(motion_pred_list, dim=0).cpu().numpy()
269
+ motion_pred_per_np = torch.cat(motion_pred_per_list, dim=0).cpu().numpy()
270
+ gt_mu, gt_cov = calculate_activation_statistics(motion_annotation_np)
271
+ mu, cov= calculate_activation_statistics(motion_pred_np)
272
+ mu_per, cov_per= calculate_activation_statistics(motion_pred_per_np)
273
+
274
+ diversity_real = calculate_diversity(motion_annotation_np, 300 if nb_sample > 300 else 100)
275
+ diversity = calculate_diversity(motion_pred_np, 300 if nb_sample > 300 else 100)
276
+
277
+ R_precision_real = R_precision_real / nb_sample
278
+ R_precision = R_precision / nb_sample
279
+
280
+ matching_score_real = matching_score_real / nb_sample
281
+ matching_score_pred = matching_score_pred / nb_sample
282
+
283
+
284
+ fid = calculate_frechet_distance(gt_mu, gt_cov, mu, cov)
285
+ fid_syn = calculate_frechet_distance(gt_mu,gt_cov,mu_per,cov_per)
286
+ fid_perturbation = calculate_frechet_distance(mu_per, cov_per, mu, cov)
287
+
288
+ msg = f"--> \t Eva. Iter {nb_iter} :, FID. {fid:.4f},FID_syn{fid_syn:.5f},FID_perturbation_and_origin.{fid_perturbation:.5f} Diversity Real. {diversity_real:.4f}, Diversity. {diversity:.4f}, R_precision_real. {R_precision_real}, R_precision. {R_precision}, matching_score_real. {matching_score_real}, matching_score_pred. {matching_score_pred}"
289
+ logger.info(msg)
290
+
291
+
292
+ if draw:
293
+ writer.add_scalar('./Test/FID', fid, nb_iter)
294
+ writer.add_scalar('./Test/FID_perturbation_and_origin', fid_perturbation, nb_iter)
295
+ writer.add_scalar('./Test/FID_syn', fid_syn, nb_iter)
296
+ writer.add_scalar('./Test/Diversity', diversity, nb_iter)
297
+ writer.add_scalar('./Test/top1', R_precision[0], nb_iter)
298
+ writer.add_scalar('./Test/top2', R_precision[1], nb_iter)
299
+ writer.add_scalar('./Test/top3', R_precision[2], nb_iter)
300
+ writer.add_scalar('./Test/matching_score', matching_score_pred, nb_iter)
301
+
302
+
303
+ # if nb_iter % 10000 == 0 :
304
+ # for ii in range(4):
305
+ # tensorborad_add_video_xyz(writer, draw_org[ii], nb_iter, tag='./Vis/org_eval'+str(ii), nb_vis=1, title_batch=[draw_text[ii]], outname=[os.path.join(out_dir, 'gt'+str(ii)+'.gif')] if savegif else None)
306
+
307
+ # if nb_iter % 10000 == 0 :
308
+ # for ii in range(4):
309
+ # tensorborad_add_video_xyz(writer, draw_pred[ii], nb_iter, tag='./Vis/pred_eval'+str(ii), nb_vis=1, title_batch=[draw_text_pred[ii]], outname=[os.path.join(out_dir, 'pred'+str(ii)+'.gif')] if savegif else None)
310
+
311
+ if isinstance(best_fid, tuple):
312
+ best_fid=best_fid[0]
313
+ if isinstance(best_fid_perturbation, tuple):
314
+ best_fid_perturbation=best_fid_perturbation[0]
315
+ if fid < best_fid :
316
+ msg = f"--> --> \t FID Improved from {best_fid:.5f} to {fid:.5f} !!!"
317
+ logger.info(msg)
318
+ best_fid, best_iter = fid, nb_iter
319
+ if save:
320
+ state_dict = clip_model.state_dict()
321
+ torch.save(state_dict, os.path.join(out_dir, 'clip_best.pth'))
322
+ torch.save({'trans' : trans.state_dict()}, os.path.join(out_dir, 'net_best_fid.pth'))
323
+ msg = f"--> --> \t Current FID is {fid:.5f} !!!"
324
+ logger.info(msg)
325
+ if fid_syn < best_fid_syn:
326
+ msg = f"--> --> \t FID_syn {best_fid_syn:.5f} to {fid_syn:.5f} !!!"
327
+ logger.info(msg)
328
+ best_fid_syn = fid_syn
329
+
330
+ if fid_perturbation < best_fid_perturbation :
331
+ msg = f"--> --> \t FID_perturbation_and_origin {best_fid_perturbation:.5f} to {fid_perturbation:.5f} !!!"
332
+ logger.info(msg)
333
+ best_fid_perturbation = fid_perturbation
334
+
335
+ if matching_score_pred < best_matching :
336
+ msg = f"--> --> \t matching_score Improved from {best_matching:.5f} to {matching_score_pred:.5f} !!!"
337
+ logger.info(msg)
338
+ best_matching = matching_score_pred
339
+
340
+ if abs(diversity_real - diversity) < abs(diversity_real - best_div) :
341
+ msg = f"--> --> \t Diversity Improved from {best_div:.5f} to {diversity:.5f} !!!"
342
+ logger.info(msg)
343
+ best_div = diversity
344
+
345
+ if R_precision[0] > best_top1 :
346
+ msg = f"--> --> \t Top1 Improved from {best_top1:.4f} to {R_precision[0]:.4f} !!!"
347
+ logger.info(msg)
348
+ best_top1 = R_precision[0]
349
+
350
+ if R_precision[1] > best_top2 :
351
+ msg = f"--> --> \t Top2 Improved from {best_top2:.4f} to {R_precision[1]:.4f} !!!"
352
+ logger.info(msg)
353
+ best_top2 = R_precision[1]
354
+
355
+ if R_precision[2] > best_top3 :
356
+ msg = f"--> --> \t Top3 Improved from {best_top3:.4f} to {R_precision[2]:.4f} !!!"
357
+ logger.info(msg)
358
+ best_top3 = R_precision[2]
359
+
360
+ if save:
361
+ state_dict = clip_model.state_dict()
362
+ torch.save(state_dict, os.path.join(out_dir, 'clip_last.pth'))
363
+ torch.save({'trans' : trans.state_dict()}, os.path.join(out_dir, 'net_last.pth'))
364
+
365
+ trans.train()
366
+ return best_fid, best_fid_syn, best_fid_perturbation, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, writer, logger
367
+
368
+
369
+ @torch.no_grad()
370
+ def evaluation_transformer_test(out_dir, val_loader, net, trans, logger, writer, nb_iter, best_fid,best_fid_word_perb,best_fid_perturbation, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, best_multi, clip_model, eval_wrapper, draw = True, save = True, savegif=False, savenpy=False) :
371
+
372
+ trans.eval()
373
+ nb_sample = 0
374
+
375
+ draw_org = []
376
+ draw_pred = []
377
+ draw_text = []
378
+ draw_text_pred = []
379
+ draw_name = []
380
+
381
+ motion_annotation_list = []
382
+ motion_pred_list = []
383
+ motion_pred_per_list = []
384
+
385
+ motion_multimodality = []
386
+ R_precision_real = 0
387
+ R_precision = 0
388
+ matching_score_real = 0
389
+ matching_score_pred = 0
390
+
391
+ nb_sample = 0
392
+
393
+ for batch in tqdm(val_loader, desc="Validation Progress"):
394
+
395
+ word_embeddings, pos_one_hots, clip_text, clip_text_perb, sent_len, pose, m_length, token, name = batch
396
+ bs, seq = pose.shape[:2]
397
+ num_joints = 21 if pose.shape[-1] == 251 else 22
398
+
399
+ text = clip.tokenize(clip_text, truncate=True).cuda()
400
+ text_perb = clip.tokenize(clip_text_perb, truncate=True).cuda()
401
+ feat_clip_text = clip_model.encode_text(text)[0].float()
402
+ feat_clip_text_per = clip_model.encode_text(text_perb)[0].float()
403
+
404
+
405
+ motion_multimodality_batch = []
406
+ for i in range(1):
407
+ pred_pose_eval = torch.zeros((bs, seq, pose.shape[-1])).cuda()
408
+ pred_pose_eval_per = torch.zeros((bs, seq, pose.shape[-1])).cuda()
409
+
410
+ pred_len = torch.ones(bs).long()
411
+ pred_len_per = torch.ones(bs).long()
412
+
413
+ for k in range(bs):
414
+ try:
415
+ index_motion = trans.sample(feat_clip_text[k:k+1], True)
416
+ index_motion_per = trans.sample(feat_clip_text_per[k:k+1], True)
417
+ except:
418
+ index_motion = torch.ones(1,1).cuda().long()
419
+ index_motion_per = torch.ones(1,1).cuda().long()
420
+
421
+ pred_pose = net.forward_decoder(index_motion)
422
+ pred_pose_per = net.forward_decoder(index_motion_per)
423
+ cur_len = pred_pose.shape[1]
424
+ cur_len_per = pred_pose_per.shape[1]
425
+
426
+ pred_len[k] = min(cur_len, seq)
427
+ pred_len_per[k] = min(cur_len_per, seq)
428
+
429
+ pred_pose_eval[k:k+1, :cur_len] = pred_pose[:, :seq]
430
+ pred_pose_eval_per[k:k+1, :cur_len_per] = pred_pose_per[:, :seq]
431
+
432
+ if i == 0 and (draw or savenpy):
433
+ pred_denorm = val_loader.dataset.inv_transform(pred_pose.detach().cpu().numpy())
434
+ pred_xyz = recover_from_ric(torch.from_numpy(pred_denorm).float().cuda(), num_joints)
435
+
436
+ if savenpy:
437
+ np.save(os.path.join(out_dir, name[k]+'_pred.npy'), pred_xyz.detach().cpu().numpy())
438
+
439
+ if draw:
440
+ if i == 0:
441
+ draw_pred.append(pred_xyz)
442
+ draw_text_pred.append(clip_text[k])
443
+ draw_name.append(name[k])
444
+
445
+ et_pred, em_pred = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, pred_pose_eval, pred_len)
446
+ et_pred_per, em_pred_per = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, pred_pose_eval_per, pred_len_per)
447
+
448
+ # motion_multimodality_batch.append(em_pred.reshape(bs, 1, -1))
449
+
450
+ if i == 0:
451
+ pose = pose.cuda().float()
452
+
453
+ et, em = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, pose, m_length)
454
+ motion_annotation_list.append(em)
455
+ motion_pred_list.append(em_pred)
456
+ motion_pred_per_list.append(em_pred_per)
457
+
458
+ if draw or savenpy:
459
+ pose = val_loader.dataset.inv_transform(pose.detach().cpu().numpy())
460
+ pose_xyz = recover_from_ric(torch.from_numpy(pose).float().cuda(), num_joints)
461
+
462
+ if savenpy:
463
+ for j in range(bs):
464
+ np.save(os.path.join(out_dir, name[j]+'_gt.npy'), pose_xyz[j][:m_length[j]].unsqueeze(0).cpu().numpy())
465
+
466
+ if draw:
467
+ for j in range(bs):
468
+ draw_org.append(pose_xyz[j][:m_length[j]].unsqueeze(0))
469
+ draw_text.append(clip_text[j])
470
+
471
+ temp_R, temp_match = calculate_R_precision(et.cpu().numpy(), em.cpu().numpy(), top_k=3, sum_all=True)
472
+ R_precision_real += temp_R
473
+ matching_score_real += temp_match
474
+ temp_R, temp_match = calculate_R_precision(et_pred.cpu().numpy(), em_pred.cpu().numpy(), top_k=3, sum_all=True)
475
+ R_precision += temp_R
476
+ matching_score_pred += temp_match
477
+
478
+ nb_sample += bs
479
+
480
+ # motion_multimodality.append(torch.cat(motion_multimodality_batch, dim=1))
481
+
482
+ motion_annotation_np = torch.cat(motion_annotation_list, dim=0).cpu().numpy()
483
+ motion_pred_np = torch.cat(motion_pred_list, dim=0).cpu().numpy()
484
+ motion_pred_per_np = torch.cat(motion_pred_per_list, dim=0).cpu().numpy()
485
+ gt_mu, gt_cov = calculate_activation_statistics(motion_annotation_np)
486
+ mu, cov= calculate_activation_statistics(motion_pred_np) # mu cov使用的是motion_perb_np
487
+ mu_per, cov_per= calculate_activation_statistics(motion_pred_per_np)
488
+ gt_mu[np.isnan(gt_mu) | np.isinf(gt_mu)] = 0.0
489
+ gt_cov[np.isnan(gt_cov) | np.isinf(gt_cov)] = 0.0
490
+ mu[np.isnan(mu) | np.isinf(mu)] = 0.0
491
+ cov[np.isnan(cov) | np.isinf(cov)] = 0.0
492
+ mu_per[np.isnan(mu_per) | np.isinf(mu_per)] = 0.0
493
+ cov_per[np.isnan(cov_per) | np.isinf(cov_per)] = 0.0
494
+ diversity_real = calculate_diversity(motion_annotation_np, 300 if nb_sample > 300 else 100)
495
+ diversity = calculate_diversity(motion_pred_np, 300 if nb_sample > 300 else 100)
496
+
497
+ R_precision_real = R_precision_real / nb_sample
498
+ R_precision = R_precision / nb_sample
499
+
500
+ matching_score_real = matching_score_real / nb_sample
501
+ matching_score_pred = matching_score_pred / nb_sample
502
+
503
+ multimodality = 0
504
+ # motion_multimodality = torch.cat(motion_multimodality, dim=0).cpu().numpy()
505
+ # multimodality = calculate_multimodality(motion_multimodality, 10)
506
+ try:
507
+ fid = calculate_frechet_distance(gt_mu, gt_cov, mu, cov)
508
+ fid_perturbation = calculate_frechet_distance(mu_per, cov_per, mu, cov)
509
+ fid_word_perb = calculate_frechet_distance(gt_mu,gt_cov,mu_per,cov_per)
510
+ except:
511
+ print('数据有问题!!')
512
+ msg = f"--> \t Eva. Iter {nb_iter} :, FID. {fid:.4f}, FID_syn. {fid_word_perb:.5f}, FID_Perturbation. {fid_perturbation:.4f}, Diversity Real. {diversity_real:.4f}, Diversity. {diversity:.4f}, R_precision_real. {R_precision_real}, R_precision. {R_precision}, matching_score_real. {matching_score_real}, matching_score_pred. {matching_score_pred}, multimodality. {multimodality:.4f}"
513
+ logger.info(msg)
514
+
515
+
516
+ if draw:
517
+ for ii in range(len(draw_org)):
518
+ tensorborad_add_video_xyz(writer, draw_org[ii], nb_iter, tag='./Vis/'+draw_name[ii]+'_org', nb_vis=1, title_batch=[draw_text[ii]], outname=[os.path.join(out_dir, draw_name[ii]+'_skel_gt.gif')] if savegif else None)
519
+
520
+ tensorborad_add_video_xyz(writer, draw_pred[ii], nb_iter, tag='./Vis/'+draw_name[ii]+'_pred', nb_vis=1, title_batch=[draw_text_pred[ii]], outname=[os.path.join(out_dir, draw_name[ii]+'_skel_pred.gif')] if savegif else None)
521
+
522
+ trans.train()
523
+ return fid,fid_word_perb,fid_perturbation, best_iter, diversity, R_precision[0], R_precision[1], R_precision[2], matching_score_pred, multimodality, writer, logger
524
+
525
+ # (X - X_train)*(X - X_train) = -2X*X_train + X*X + X_train*X_train
526
+ def euclidean_distance_matrix(matrix1, matrix2):
527
+ """
528
+ Params:
529
+ -- matrix1: N1 x D
530
+ -- matrix2: N2 x D
531
+ Returns:
532
+ -- dist: N1 x N2
533
+ dist[i, j] == distance(matrix1[i], matrix2[j])
534
+ """
535
+ assert matrix1.shape[1] == matrix2.shape[1]
536
+ d1 = -2 * np.dot(matrix1, matrix2.T) # shape (num_test, num_train)
537
+ d2 = np.sum(np.square(matrix1), axis=1, keepdims=True) # shape (num_test, 1)
538
+ d3 = np.sum(np.square(matrix2), axis=1) # shape (num_train, )
539
+ dists = np.sqrt(d1 + d2 + d3) # broadcasting
540
+ return dists
541
+
542
+
543
+
544
+ def calculate_top_k(mat, top_k):
545
+ size = mat.shape[0]
546
+ gt_mat = np.expand_dims(np.arange(size), 1).repeat(size, 1)
547
+ bool_mat = (mat == gt_mat)
548
+ correct_vec = False
549
+ top_k_list = []
550
+ for i in range(top_k):
551
+ # print(correct_vec, bool_mat[:, i])
552
+ correct_vec = (correct_vec | bool_mat[:, i])
553
+ # print(correct_vec)
554
+ top_k_list.append(correct_vec[:, None])
555
+ top_k_mat = np.concatenate(top_k_list, axis=1)
556
+ return top_k_mat
557
+
558
+
559
+ def calculate_R_precision(embedding1, embedding2, top_k, sum_all=False):
560
+ dist_mat = euclidean_distance_matrix(embedding1, embedding2)
561
+ matching_score = dist_mat.trace()
562
+ argmax = np.argsort(dist_mat, axis=1)
563
+ top_k_mat = calculate_top_k(argmax, top_k)
564
+ if sum_all:
565
+ return top_k_mat.sum(axis=0), matching_score
566
+ else:
567
+ return top_k_mat, matching_score
568
+
569
+ def calculate_multimodality(activation, multimodality_times):
570
+ assert len(activation.shape) == 3
571
+ assert activation.shape[1] > multimodality_times
572
+ num_per_sent = activation.shape[1]
573
+
574
+ first_dices = np.random.choice(num_per_sent, multimodality_times, replace=False)
575
+ second_dices = np.random.choice(num_per_sent, multimodality_times, replace=False)
576
+ dist = linalg.norm(activation[:, first_dices] - activation[:, second_dices], axis=2)
577
+ return dist.mean()
578
+
579
+
580
+ def calculate_diversity(activation, diversity_times):
581
+ assert len(activation.shape) == 2
582
+ assert activation.shape[0] > diversity_times
583
+ num_samples = activation.shape[0]
584
+
585
+ first_indices = np.random.choice(num_samples, diversity_times, replace=False)
586
+ second_indices = np.random.choice(num_samples, diversity_times, replace=False)
587
+ dist = linalg.norm(activation[first_indices] - activation[second_indices], axis=1)
588
+ return dist.mean()
589
+
590
+
591
+
592
+ def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
593
+
594
+ mu1 = np.atleast_1d(mu1)
595
+ mu2 = np.atleast_1d(mu2)
596
+
597
+ sigma1 = np.atleast_2d(sigma1)
598
+ sigma2 = np.atleast_2d(sigma2)
599
+
600
+ assert mu1.shape == mu2.shape, \
601
+ 'Training and test mean vectors have different lengths'
602
+ assert sigma1.shape == sigma2.shape, \
603
+ 'Training and test covariances have different dimensions'
604
+
605
+ diff = mu1 - mu2
606
+
607
+ # Product might be almost singular
608
+ covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
609
+ if not np.isfinite(covmean).all():
610
+ msg = ('fid calculation produces singular product; '
611
+ 'adding %s to diagonal of cov estimates') % eps
612
+ print(msg)
613
+ offset = np.eye(sigma1.shape[0]) * eps
614
+ covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
615
+
616
+ # Numerical error might give slight imaginary component
617
+ if np.iscomplexobj(covmean):
618
+ if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
619
+ m = np.max(np.abs(covmean.imag))
620
+ raise ValueError('Imaginary component {}'.format(m))
621
+ covmean = covmean.real
622
+
623
+ tr_covmean = np.trace(covmean)
624
+
625
+ return (diff.dot(diff) + np.trace(sigma1)
626
+ + np.trace(sigma2) - 2 * tr_covmean)
627
+
628
+
629
+
630
+ def calculate_activation_statistics(activations):
631
+
632
+ mu = np.mean(activations, axis=0)
633
+ cov = np.cov(activations, rowvar=False)
634
+ return mu, cov
635
+
636
+
637
+ def calculate_frechet_feature_distance(feature_list1, feature_list2):
638
+ feature_list1 = np.stack(feature_list1)
639
+ feature_list2 = np.stack(feature_list2)
640
+
641
+ # normalize the scale
642
+ mean = np.mean(feature_list1, axis=0)
643
+ std = np.std(feature_list1, axis=0) + 1e-10
644
+ feature_list1 = (feature_list1 - mean) / std
645
+ feature_list2 = (feature_list2 - mean) / std
646
+
647
+ dist = calculate_frechet_distance(
648
+ mu1=np.mean(feature_list1, axis=0),
649
+ sigma1=np.cov(feature_list1, rowvar=False),
650
+ mu2=np.mean(feature_list2, axis=0),
651
+ sigma2=np.cov(feature_list2, rowvar=False),
652
+ )
653
+ return dist
losses.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from CLIP.clip import clip
2
+ from CLIP.clip import model
3
+ import torch
4
+
5
+ def topk_overlap_loss(gt, pred, K=2, metric='l1'):
6
+ idx = torch.argsort(gt, descending=True)
7
+ # print(idx)
8
+ idx = idx[:K]
9
+ pred_TopK_1 = pred.gather(-1,idx)
10
+ gt_Topk_1 = gt.gather(-1,idx)
11
+
12
+ idx_pred = torch.argsort(pred, descending=True)
13
+ idx_pred = idx_pred[:K]
14
+ try:
15
+ gt_TopK_2 = gt.gather(-1, idx_pred)
16
+ except Exception as e:
17
+ print(e)
18
+ print(gt.shape)
19
+ print(idx_pred.shape)
20
+ pred_TopK_2 = pred.gather(-1, idx_pred)
21
+
22
+ gt_Topk_1_normed = torch.nn.functional.softmax(gt_Topk_1, dim=-1)
23
+ pred_TopK_1_normed = torch.nn.functional.softmax(pred_TopK_1, dim=-1)
24
+ gt_TopK_2_normed = torch.nn.functional.softmax(gt_TopK_2, dim=-1)
25
+ pred_TopK_2_normed = torch.nn.functional.softmax(pred_TopK_2, dim=-1)
26
+
27
+ def kl(a,b):
28
+ return torch.nn.functional.kl_div(a.log(), b, reduction="batchmean")
29
+
30
+ def jsd(a,b):
31
+ loss = kl(a,b) + kl(b,a)
32
+ loss /= 2
33
+ return loss
34
+
35
+
36
+ if metric == 'l1':
37
+ loss = torch.abs((pred_TopK_1 - gt_Topk_1)) + torch.abs(gt_TopK_2 - pred_TopK_2)
38
+ loss = loss/(2*K)
39
+ elif metric == "l2":
40
+ loss = torch.norm(pred_TopK_1 - gt_Topk_1, p=2) + torch.norm(gt_TopK_2 - pred_TopK_2, p=2)
41
+ loss = loss/(2*K)
42
+ elif metric == "kl-full":
43
+ loss = kl(gt,pred)
44
+ elif metric == "jsd-full":
45
+ loss = jsd(gt,pred)
46
+ elif metric == "kl-topk":
47
+ loss = kl(gt_Topk_1_normed,pred_TopK_1_normed) + kl(gt_TopK_2_normed,pred_TopK_2_normed)
48
+ loss /=2
49
+ elif metric == "jsd-topk":
50
+ loss = jsd(gt_Topk_1_normed, pred_TopK_1_normed) + jsd(gt_TopK_2_normed, pred_TopK_2_normed)
51
+ loss /= 2
52
+ return loss
53
+
54
+ def topk_overlap_loss_batch(gt,pred,K=2,metric='l1'):
55
+ idx = torch.argsort(gt,dim=1,descending=True)
56
+ # print(idx)
57
+ idx = idx[:,:K]
58
+ pred_TopK_1 = pred.gather(1,idx)
59
+ gt_Topk_1 = gt.gather(1,idx)
60
+
61
+ idx_pred = torch.argsort(pred,dim=1,descending=True)
62
+ idx_pred = idx_pred[:,:K]
63
+ try:
64
+ gt_TopK_2 = gt.gather(1, idx_pred)
65
+ except Exception as e:
66
+ print(e)
67
+ print(gt.shape)
68
+ print(idx_pred.shape)
69
+ pred_TopK_2 = pred.gather(1, idx_pred)
70
+
71
+ gt_Topk_1_normed = torch.nn.functional.softmax(gt_Topk_1,dim=-1)
72
+ pred_TopK_1_normed = torch.nn.functional.softmax(pred_TopK_1,dim=-1)
73
+ gt_TopK_2_normed = torch.nn.functional.softmax(gt_TopK_2,dim=-1)
74
+ pred_TopK_2_normed = torch.nn.functional.softmax(pred_TopK_2,dim=-1)
75
+
76
+ def kl(a,b):
77
+ return torch.nn.functional.kl_div(a.log(), b, reduction="batchmean")
78
+
79
+ def jsd(a,b):
80
+ loss = kl(a,b) + kl(b,a)
81
+ loss /= 2
82
+ return loss
83
+
84
+
85
+ if metric == 'l1':
86
+ loss = torch.abs((pred_TopK_1 - gt_Topk_1)) + torch.abs(gt_TopK_2 - pred_TopK_2)
87
+ loss = loss/(2*K)
88
+ elif metric == "l2":
89
+ loss = torch.norm(pred_TopK_1 - gt_Topk_1, p=2) + torch.norm(gt_TopK_2 - pred_TopK_2, p=2)
90
+ loss = loss/(2*K)
91
+ elif metric == "kl-full":
92
+ loss = kl(gt,pred)
93
+ elif metric == "jsd-full":
94
+ loss = jsd(gt,pred)
95
+ elif metric == "kl-topk":
96
+ loss = kl(gt_Topk_1_normed,pred_TopK_1_normed) + kl(gt_TopK_2_normed,pred_TopK_2_normed)
97
+ loss /=2
98
+ elif metric == "jsd-topk":
99
+ loss = jsd(gt_Topk_1_normed, pred_TopK_1_normed) + jsd(gt_TopK_2_normed, pred_TopK_2_normed)
100
+ loss /= 2
101
+ return loss
102
+
metrics.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import json
4
+ import os
5
+ import shutil
6
+ from copy import deepcopy
7
+ import torch
8
+ import torch.nn as nn
9
+
10
+ from sklearn.utils import shuffle
11
+ # from tqdm import tqdm
12
+ import time
13
+
14
+ def tvd(predictions, targets): #accepts two numpy arrays of dimension: (num. instances, )
15
+ return (0.5 * np.abs(predictions - targets)).sum()
16
+
17
+ def batch_tvd(predictions, targets,reduce=True): #accepts two Torch tensors... " "
18
+ if reduce == False:
19
+ return (0.5 * torch.abs(predictions - targets))
20
+ else:
21
+ return (0.5 * torch.abs(predictions - targets)).sum()
22
+ def get_sorting_index_with_noise_from_lengths(lengths, noise_frac):
23
+ if noise_frac > 0:
24
+ noisy_lengths = [x + np.random.randint(np.floor(-x * noise_frac), np.ceil(x * noise_frac)) for x in lengths]
25
+ else:
26
+ noisy_lengths = lengths
27
+ return np.argsort(noisy_lengths)
28
+
29
+
30
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
31
+
32
+
33
+ def kld(a1, a2):
34
+ # (B, *, A), #(B, *, A)
35
+ a1 = torch.clamp(a1, 0, 1)
36
+ a2 = torch.clamp(a2, 0, 1)
37
+ log_a1 = torch.log(a1 + 1e-10)
38
+ log_a2 = torch.log(a2 + 1e-10)
39
+
40
+ kld = a1 * (log_a1 - log_a2)
41
+ kld = kld.sum(-1)
42
+
43
+ return kld
44
+
45
+
46
+ def jsd(p, q):
47
+ m = 0.5 * (p + q)
48
+ jsd = 0.5 * (kld(p, m) + kld(q, m)) # for each instance in the batch
49
+
50
+ return jsd.unsqueeze(-1) # jsd.squeeze(1).sum()
51
+
52
+
53
+ def tvd(predictions, targets): #accepts two numpy arrays of dimension: (num. instances, )
54
+ return (0.5 * np.abs(predictions - targets)).sum()
55
+
56
+ def batch_tvd(predictions, targets): #accepts two Torch tensors... " "
57
+ return (0.5 * torch.abs(predictions - targets)).sum()
58
+
59
+
60
+
61
+ def batch_jaccard_similarity(gt, pred):
62
+ intersection = torch.min(gt, pred).sum(dim=1)
63
+ union = torch.max(gt, pred).sum(dim=1)
64
+ similarity = intersection / union
65
+ return similarity
66
+
67
+ def jaccard_similarity(gt, pred, top_k=2):
68
+
69
+ gt_top_k = torch.topk(gt, top_k, dim=1).values
70
+ pred_top_k = torch.topk(pred, top_k, dim=1).values
71
+
72
+
73
+ jaccard_sim = batch_jaccard_similarity(gt_top_k, pred_top_k)
74
+
75
+
76
+ mean_similarity = jaccard_sim.mean()
77
+
78
+ return mean_similarity
79
+
80
+
81
+
82
+ def intersection_of_two_tensor(t1, t2):
83
+ combined = torch.cat((t1, t2))
84
+ uniques, counts = combined.unique(return_counts=True)
85
+ intersection = uniques[counts > 1]
86
+ return intersection
87
+
88
+ def topK_overlap_true_loss(a,b,K=2):
89
+ t1 = torch.argsort(a, descending=True)
90
+ t2 = torch.argsort(b, descending=True)
91
+ t1 = t1.detach().cpu().numpy()
92
+ t2 = t2.detach().cpu().numpy()
93
+ N = t1.shape[0]
94
+ loss = []
95
+ for i in range(N):
96
+ inset = np.intersect1d(t1[i,:K],t2[i,:K])
97
+ overlap = len(inset)/K
98
+ # print(overlap)
99
+ loss.append(overlap)
100
+ return np.mean(loss)
101
+
102
+
103
+ class AverageMeter():
104
+ def __init__(self):
105
+ self.cnt = 0
106
+ self.sum = 0
107
+ self.mean = 0
108
+
109
+ def update(self, val, cnt):
110
+ self.cnt += cnt
111
+ self.sum += val * cnt
112
+ self.mean = self.sum / self.cnt
113
+
114
+ def average(self):
115
+ return self.mean
116
+
117
+ def total(self):
118
+ return self.sum
119
+
120
+
121
+
122
+ def topk_overlap_loss(gt,pred,K=2,metric='l1'):
123
+ idx = torch.argsort(gt,dim=1,descending=True)
124
+ # print(idx)
125
+ idx = idx[:,:K]
126
+ pred_TopK_1 = pred.gather(1,idx)
127
+ gt_Topk_1 = gt.gather(1,idx)
128
+
129
+ idx_pred = torch.argsort(pred,dim=1,descending=True)
130
+ idx_pred = idx_pred[:,:K]
131
+ try:
132
+ gt_TopK_2 = gt.gather(1, idx_pred)
133
+ except Exception as e:
134
+ print(e)
135
+ print(gt.shape)
136
+ print(idx_pred.shape)
137
+ pred_TopK_2 = pred.gather(1, idx_pred)
138
+
139
+ gt_Topk_1_normed = torch.nn.functional.softmax(gt_Topk_1,dim=-1)
140
+ pred_TopK_1_normed = torch.nn.functional.softmax(pred_TopK_1,dim=-1)
141
+ gt_TopK_2_normed = torch.nn.functional.softmax(gt_TopK_2,dim=-1)
142
+ pred_TopK_2_normed = torch.nn.functional.softmax(pred_TopK_2,dim=-1)
143
+
144
+ def kl(a,b):
145
+ return torch.nn.functional.kl_div(a.log(), b, reduction="batchmean")
146
+
147
+ def jsd(a,b):
148
+ loss = kl(a,b) + kl(b,a)
149
+ loss /= 2
150
+ return loss
151
+
152
+
153
+ if metric == 'l1':
154
+ loss = torch.abs((pred_TopK_1 - gt_Topk_1)) + torch.abs(gt_TopK_2 - pred_TopK_2)
155
+ loss = loss/(2*K)
156
+ elif metric == "l2":
157
+ loss = torch.norm(pred_TopK_1 - gt_Topk_1, p=2) + torch.norm(gt_TopK_2 - pred_TopK_2, p=2)
158
+ loss = loss/(2*K)
159
+ elif metric == "kl-full":
160
+ loss = kl(gt,pred)
161
+ elif metric == "jsd-full":
162
+ loss = jsd(gt,pred)
163
+ elif metric == "kl-topk":
164
+ loss = kl(gt_Topk_1_normed,pred_TopK_1_normed) + kl(gt_TopK_2_normed,pred_TopK_2_normed)
165
+ loss /=2
166
+ elif metric == "jsd-topk":
167
+ loss = jsd(gt_Topk_1_normed, pred_TopK_1_normed) + jsd(gt_TopK_2_normed, pred_TopK_2_normed)
168
+ loss /= 2
169
+ return loss
170
+
171
+ if __name__ == '__main__':
172
+
173
+ from torch.autograd import gradcheck
174
+ import torch
175
+ import torch.nn as nn
176
+
177
+ # intersection_of_two_tensor(t1[i], t2[i])
178
+
179
+ t1 = torch.tensor(
180
+ np.array([[100, 2, 3, 4],
181
+ [2, 1, 3, 7]],),requires_grad=True, dtype=torch.double
182
+ )
183
+ print(t1.shape)
184
+ t2 = torch.tensor(
185
+ np.array([[1, 2, 3, 4],
186
+ [2, 4, 6, 7]]),requires_grad=True, dtype=torch.double
187
+ )
188
+ print(t2.shape)
189
+
190
+
191
+
192
+ print(topK_overlap_true_loss(torch.argsort(t1,descending=True),torch.argsort(t2,descending=True),K=2))
quickstart.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
render_final.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from models.rotation2xyz import Rotation2xyz
2
+ import numpy as np
3
+ from trimesh import Trimesh
4
+ import os
5
+ os.environ['PYOPENGL_PLATFORM'] = "osmesa"
6
+
7
+ import torch
8
+ from visualize.simplify_loc2rot import joints2smpl
9
+ import pyrender
10
+ import matplotlib.pyplot as plt
11
+
12
+ import io
13
+ import imageio
14
+ from shapely import geometry
15
+ import trimesh
16
+ from pyrender.constants import RenderFlags
17
+ import math
18
+ # import ffmpeg
19
+ from PIL import Image
20
+
21
+ class WeakPerspectiveCamera(pyrender.Camera):
22
+ def __init__(self,
23
+ scale,
24
+ translation,
25
+ znear=pyrender.camera.DEFAULT_Z_NEAR,
26
+ zfar=None,
27
+ name=None):
28
+ super(WeakPerspectiveCamera, self).__init__(
29
+ znear=znear,
30
+ zfar=zfar,
31
+ name=name,
32
+ )
33
+ self.scale = scale
34
+ self.translation = translation
35
+
36
+ def get_projection_matrix(self, width=None, height=None):
37
+ P = np.eye(4)
38
+ P[0, 0] = self.scale[0]
39
+ P[1, 1] = self.scale[1]
40
+ P[0, 3] = self.translation[0] * self.scale[0]
41
+ P[1, 3] = -self.translation[1] * self.scale[1]
42
+ P[2, 2] = -1
43
+ return P
44
+
45
+ def render(motions, outdir='test_vis', device_id=0, name=None, pred=True):
46
+ frames, njoints, nfeats = motions.shape
47
+ MINS = motions.min(axis=0).min(axis=0)
48
+ MAXS = motions.max(axis=0).max(axis=0)
49
+
50
+ height_offset = MINS[1]
51
+ motions[:, :, 1] -= height_offset
52
+ trajec = motions[:, 0, [0, 2]]
53
+
54
+ j2s = joints2smpl(num_frames=frames, device_id=0, cuda=True)
55
+ rot2xyz = Rotation2xyz(device=torch.device("cuda:0"))
56
+ faces = rot2xyz.smpl_model.faces
57
+
58
+ if (not os.path.exists(outdir + name+'_pred.pt') and pred) or (not os.path.exists(outdir + name+'_gt.pt') and not pred):
59
+ print(f'Running SMPLify, it may take a few minutes.')
60
+ motion_tensor, opt_dict = j2s.joint2smpl(motions) # [nframes, njoints, 3]
61
+
62
+ vertices = rot2xyz(torch.tensor(motion_tensor).clone(), mask=None,
63
+ pose_rep='rot6d', translation=True, glob=True,
64
+ jointstype='vertices',
65
+ vertstrans=True)
66
+
67
+ if pred:
68
+ torch.save(vertices, outdir + name+'_pred.pt')
69
+ else:
70
+ torch.save(vertices, outdir + name+'_gt.pt')
71
+ else:
72
+ if pred:
73
+ vertices = torch.load(outdir + name+'_pred.pt')
74
+ else:
75
+ vertices = torch.load(outdir + name+'_gt.pt')
76
+ frames = vertices.shape[3] # shape: 1, nb_frames, 3, nb_joints
77
+ print (vertices.shape)
78
+ MINS = torch.min(torch.min(vertices[0], axis=0)[0], axis=1)[0]
79
+ MAXS = torch.max(torch.max(vertices[0], axis=0)[0], axis=1)[0]
80
+ # vertices[:,:,1,:] -= MINS[1] + 1e-5
81
+
82
+
83
+ out_list = []
84
+
85
+ minx = MINS[0] - 0.5
86
+ maxx = MAXS[0] + 0.5
87
+ minz = MINS[2] - 0.5
88
+ maxz = MAXS[2] + 0.5
89
+ polygon = geometry.Polygon([[minx, minz], [minx, maxz], [maxx, maxz], [maxx, minz]])
90
+ polygon_mesh = trimesh.creation.extrude_polygon(polygon, 1e-5)
91
+
92
+ vid = []
93
+ for i in range(frames):
94
+ if i % 10 == 0:
95
+ print(i)
96
+
97
+ mesh = Trimesh(vertices=vertices[0, :, :, i].squeeze().tolist(), faces=faces)
98
+
99
+ base_color = (0.11, 0.53, 0.8, 0.5)
100
+ ## OPAQUE rendering without alpha
101
+ ## BLEND rendering consider alpha
102
+ material = pyrender.MetallicRoughnessMaterial(
103
+ metallicFactor=0.7,
104
+ alphaMode='OPAQUE',
105
+ baseColorFactor=base_color
106
+ )
107
+
108
+
109
+ mesh = pyrender.Mesh.from_trimesh(mesh, material=material)
110
+
111
+ polygon_mesh.visual.face_colors = [0, 0, 0, 0.21]
112
+ polygon_render = pyrender.Mesh.from_trimesh(polygon_mesh, smooth=False)
113
+
114
+ bg_color = [1, 1, 1, 0.8]
115
+ scene = pyrender.Scene(bg_color=bg_color, ambient_light=(0.4, 0.4, 0.4))
116
+
117
+ sx, sy, tx, ty = [0.75, 0.75, 0, 0.10]
118
+
119
+ camera = pyrender.PerspectiveCamera(yfov=(np.pi / 3.0))
120
+
121
+ light = pyrender.DirectionalLight(color=[1,1,1], intensity=300)
122
+
123
+ scene.add(mesh)
124
+
125
+ c = np.pi / 2
126
+
127
+ scene.add(polygon_render, pose=np.array([[ 1, 0, 0, 0],
128
+
129
+ [ 0, np.cos(c), -np.sin(c), MINS[1].cpu().numpy()],
130
+
131
+ [ 0, np.sin(c), np.cos(c), 0],
132
+
133
+ [ 0, 0, 0, 1]]))
134
+
135
+ light_pose = np.eye(4)
136
+ light_pose[:3, 3] = [0, -1, 1]
137
+ scene.add(light, pose=light_pose.copy())
138
+
139
+ light_pose[:3, 3] = [0, 1, 1]
140
+ scene.add(light, pose=light_pose.copy())
141
+
142
+ light_pose[:3, 3] = [1, 1, 2]
143
+ scene.add(light, pose=light_pose.copy())
144
+
145
+
146
+ c = -np.pi / 6
147
+
148
+ scene.add(camera, pose=[[ 1, 0, 0, (minx+maxx).cpu().numpy()/2],
149
+
150
+ [ 0, np.cos(c), -np.sin(c), 1.5],
151
+
152
+ [ 0, np.sin(c), np.cos(c), max(4, minz.cpu().numpy()+(1.5-MINS[1].cpu().numpy())*2, (maxx-minx).cpu().numpy())],
153
+
154
+ [ 0, 0, 0, 1]
155
+ ])
156
+
157
+ # render scene
158
+ r = pyrender.OffscreenRenderer(960, 960)
159
+
160
+ color, _ = r.render(scene, flags=RenderFlags.RGBA)
161
+ # Image.fromarray(color).save(outdir+name+'_'+str(i)+'.png')
162
+
163
+ vid.append(color)
164
+
165
+ r.delete()
166
+
167
+ out = np.stack(vid, axis=0)
168
+ if pred:
169
+ imageio.mimsave(outdir + name+'_pred.gif', out, fps=20)
170
+ else:
171
+ imageio.mimsave(outdir + name+'_gt.gif', out, fps=20)
172
+
173
+
174
+
175
+
176
+
177
+ if __name__ == "__main__":
178
+ import argparse
179
+ parser = argparse.ArgumentParser()
180
+ parser.add_argument("--filedir", type=str, default='/CV/xhr/xhr_project/Paper/text2Pose/t2m/T2M-GPT-main/visualization/pose_np', help='motion npy file dir')
181
+ parser.add_argument('--motion-list', default=None, nargs="1", type=str, help="motion name list")
182
+ args = parser.parse_args()
183
+
184
+ filename_list = args.motion_list
185
+ filedir = args.filedir
186
+
187
+ for filename in filename_list:
188
+ motions = np.load(filedir + filename+'.npy')
189
+ print('pred', motions.shape, filename)
190
+ render(motions[0], outdir=filedir, device_id=0, name=filename, pred=True)
191
+
192
+ # motions = np.load(filedir + filename+'_pred.npy')
193
+ # print('pred', motions.shape, filename)
194
+ # render(motions[0], outdir=filedir, device_id=0, name=filename, pred=True)
195
+
196
+ # motions = np.load(filedir + filename+'_gt.npy')
197
+ # print('gt', motions.shape, filename)
198
+ # render(motions[0], outdir=filedir, device_id=0, name=filename, pred=False)
requirements.txt ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==0.13.0
2
+ backcall==0.2.0
3
+ cachetools==4.2.2
4
+ charset-normalizer==2.0.4
5
+ chumpy==0.70
6
+ cycler==0.10.0
7
+ decorator==5.0.9
8
+ google-auth==1.35.0
9
+ google-auth-oauthlib==0.4.5
10
+ grpcio==1.39.0
11
+ idna==3.2
12
+ imageio==2.9.0
13
+ ipdb==0.13.9
14
+ ipython==7.26.0
15
+ ipython-genutils==0.2.0
16
+ jedi==0.18.0
17
+ joblib==1.0.1
18
+ kiwisolver==1.3.1
19
+ markdown==3.3.4
20
+ matplotlib==3.4.3
21
+ matplotlib-inline==0.1.2
22
+ oauthlib==3.1.1
23
+ pandas==1.3.2
24
+ parso==0.8.2
25
+ pexpect==4.8.0
26
+ pickleshare==0.7.5
27
+ prompt-toolkit==3.0.20
28
+ protobuf==3.17.3
29
+ ptyprocess==0.7.0
30
+ pyasn1==0.4.8
31
+ pyasn1-modules==0.2.8
32
+ pygments==2.10.0
33
+ pyparsing==2.4.7
34
+ python-dateutil==2.8.2
35
+ pytz==2021.1
36
+ pyyaml==5.4.1
37
+ requests==2.26.0
38
+ requests-oauthlib==1.3.0
39
+ rsa==4.7.2
40
+ scikit-learn==0.24.2
41
+ scipy==1.7.1
42
+ sklearn==0.0
43
+ smplx==0.1.28
44
+ tensorboard==2.6.0
45
+ tensorboard-data-server==0.6.1
46
+ tensorboard-plugin-wit==1.8.0
47
+ threadpoolctl==2.2.0
48
+ toml==0.10.2
49
+ tqdm==4.62.2
50
+ traitlets==5.0.5
51
+ urllib3==1.26.6
52
+ wcwidth==0.2.5
53
+ werkzeug==2.0.1
54
+ # git+https://github.com/openai/CLIP.git
55
+ # git+https://github.com/nghorbani/human_body_prior
56
+ gdown
57
+ moviepy
train_vq.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+
4
+ import torch
5
+ import torch.optim as optim
6
+ from torch.utils.tensorboard import SummaryWriter
7
+
8
+ import models.vqvae as vqvae
9
+ import utils.losses as losses
10
+ import options.option_vq as option_vq
11
+ import utils.utils_model as utils_model
12
+ from dataset import dataset_VQ, dataset_TM_eval
13
+ import utils.eval_trans as eval_trans
14
+ from options.get_eval_option import get_opt
15
+ from models.evaluator_wrapper import EvaluatorModelWrapper
16
+ import warnings
17
+ warnings.filterwarnings('ignore')
18
+ from utils.word_vectorizer import WordVectorizer
19
+ from multiprocessing import freeze_support
20
+ def update_lr_warm_up(optimizer, nb_iter, warm_up_iter, lr):
21
+
22
+ current_lr = lr * (nb_iter + 1) / (warm_up_iter + 1)
23
+ for param_group in optimizer.param_groups:
24
+ param_group["lr"] = current_lr
25
+
26
+ return optimizer, current_lr
27
+
28
+ ##### ---- Exp dirs ---- #####
29
+ args = option_vq.get_args_parser()
30
+ torch.manual_seed(args.seed)
31
+
32
+ args.out_dir = os.path.join(args.out_dir, f'{args.exp_name}')
33
+ os.makedirs(args.out_dir, exist_ok = True)
34
+
35
+ ##### ---- Logger ---- #####
36
+ logger = utils_model.get_logger(args.out_dir)
37
+ writer = SummaryWriter(args.out_dir)
38
+ logger.info(json.dumps(vars(args), indent=4, sort_keys=True))
39
+
40
+
41
+
42
+ w_vectorizer = WordVectorizer('./glove', 'our_vab')
43
+ # w_vectorizer = WordVectorizer('D:\project\\faithfulpose\T2M-GPT-main\glove', 'our_vab')
44
+
45
+
46
+ if args.dataname == 'kit' :
47
+ dataset_opt_path = 'checkpoints/kit/Comp_v6_KLD005/opt.txt'
48
+ # dataset_opt_path = 'D:\project\\faithfulpose\T2M-GPT-main\checkpoints\kit\Comp_v6_KLD005\opt.txt'
49
+ args.nb_joints = 21
50
+
51
+ else :
52
+ dataset_opt_path = 'checkpoints/t2m/Comp_v6_KLD005/opt.txt'
53
+ args.nb_joints = 22
54
+
55
+ logger.info(f'Training on {args.dataname}, motions are with {args.nb_joints} joints')
56
+
57
+ wrapper_opt = get_opt(dataset_opt_path, torch.device('cuda'))
58
+ eval_wrapper = EvaluatorModelWrapper(wrapper_opt)
59
+
60
+
61
+ ##### ---- Dataloader ---- #####
62
+ train_loader = dataset_VQ.DATALoader(args.dataname,
63
+ args.batch_size,
64
+ window_size=args.window_size,
65
+ unit_length=2**args.down_t)
66
+
67
+ train_loader_iter = dataset_VQ.cycle(train_loader)
68
+
69
+ val_loader = dataset_TM_eval.DATALoader(args.dataname, False,
70
+ 32,
71
+ w_vectorizer,
72
+ unit_length=2**args.down_t)
73
+
74
+ ##### ---- Network ---- #####
75
+ net = vqvae.HumanVQVAE(args, ## use args to define different parameters in different quantizers
76
+ args.nb_code,
77
+ args.code_dim,
78
+ args.output_emb_width,
79
+ args.down_t,
80
+ args.stride_t,
81
+ args.width,
82
+ args.depth,
83
+ args.dilation_growth_rate,
84
+ args.vq_act,
85
+ args.vq_norm)
86
+
87
+
88
+ if args.resume_pth :
89
+ logger.info('loading checkpoint from {}'.format(args.resume_pth))
90
+ ckpt = torch.load(args.resume_pth, map_location='cpu')
91
+ net.load_state_dict(ckpt['net'], strict=True)
92
+ net.train()
93
+ net.cuda()
94
+
95
+ ##### ---- Optimizer & Scheduler ---- #####
96
+ optimizer = optim.AdamW(net.parameters(), lr=args.lr, betas=(0.9, 0.99), weight_decay=args.weight_decay)
97
+ scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=args.lr_scheduler, gamma=args.gamma)
98
+
99
+
100
+ Loss = losses.ReConsLoss(args.recons_loss, args.nb_joints)
101
+
102
+ ##### ------ warm-up ------- #####
103
+ avg_recons, avg_perplexity, avg_commit = 0., 0., 0.
104
+
105
+
106
+ for nb_iter in range(1, args.warm_up_iter):
107
+
108
+ optimizer, current_lr = update_lr_warm_up(optimizer, nb_iter, args.warm_up_iter, args.lr)
109
+
110
+ gt_motion = next(train_loader_iter)
111
+ gt_motion = gt_motion.cuda().float() # (bs, 64, dim)
112
+
113
+ pred_motion, loss_commit, perplexity = net(gt_motion)
114
+ loss_motion = Loss(pred_motion, gt_motion)
115
+ loss_vel = Loss.forward_vel(pred_motion, gt_motion)
116
+
117
+ loss = loss_motion + args.commit * loss_commit + args.loss_vel * loss_vel
118
+
119
+ optimizer.zero_grad()
120
+ loss.backward()
121
+ optimizer.step()
122
+
123
+ avg_recons += loss_motion.item()
124
+ avg_perplexity += perplexity.item()
125
+ avg_commit += loss_commit.item()
126
+
127
+ if nb_iter % args.print_iter == 0 :
128
+ avg_recons /= args.print_iter
129
+ avg_perplexity /= args.print_iter
130
+ avg_commit /= args.print_iter
131
+
132
+ logger.info(f"Warmup. Iter {nb_iter} : lr {current_lr:.5f} \t Commit. {avg_commit:.5f} \t PPL. {avg_perplexity:.2f} \t Recons. {avg_recons:.5f}")
133
+
134
+ avg_recons, avg_perplexity, avg_commit = 0., 0., 0.
135
+
136
+ # ##### ---- Training ---- #####
137
+ avg_recons, avg_perplexity, avg_commit = 0., 0., 0.
138
+ best_fid, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, writer, logger = eval_trans.evaluation_vqvae(args.out_dir, val_loader, net, logger, writer, 0, best_fid=1000, best_iter=0, best_div=100, best_top1=0, best_top2=0, best_top3=0, best_matching=100, eval_wrapper=eval_wrapper)
139
+
140
+ for nb_iter in range(1, args.total_iter + 1):
141
+
142
+ gt_motion = next(train_loader_iter)
143
+ gt_motion = gt_motion.cuda().float() # bs, nb_joints, joints_dim, seq_len
144
+
145
+ pred_motion, loss_commit, perplexity = net(gt_motion)
146
+ loss_motion = Loss(pred_motion, gt_motion)
147
+ loss_vel = Loss.forward_vel(pred_motion, gt_motion)
148
+
149
+ loss = loss_motion + args.commit * loss_commit + args.loss_vel * loss_vel
150
+
151
+ optimizer.zero_grad()
152
+ loss.backward()
153
+ optimizer.step()
154
+ scheduler.step()
155
+
156
+ avg_recons += loss_motion.item()
157
+ avg_perplexity += perplexity.item()
158
+ avg_commit += loss_commit.item()
159
+
160
+ if nb_iter % args.print_iter == 0 :
161
+ avg_recons /= args.print_iter
162
+ avg_perplexity /= args.print_iter
163
+ avg_commit /= args.print_iter
164
+
165
+ writer.add_scalar('./Train/L1', avg_recons, nb_iter)
166
+ writer.add_scalar('./Train/PPL', avg_perplexity, nb_iter)
167
+ writer.add_scalar('./Train/Commit', avg_commit, nb_iter)
168
+
169
+ logger.info(f"Train. Iter {nb_iter} : \t Commit. {avg_commit:.5f} \t PPL. {avg_perplexity:.2f} \t Recons. {avg_recons:.5f}")
170
+
171
+ avg_recons, avg_perplexity, avg_commit = 0., 0., 0.,
172
+
173
+ if nb_iter % args.eval_iter==0 :
174
+ best_fid, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, writer, logger = eval_trans.evaluation_vqvae(args.out_dir, val_loader, net, logger, writer, nb_iter, best_fid, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, eval_wrapper=eval_wrapper)
175
+