Spaces:
Runtime error
Runtime error
Commit
·
9a2da78
1
Parent(s):
6a6f1e5
Upload 473 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- generate_human_motion/VQTrans/GPT_eval_multi.py +121 -0
- generate_human_motion/VQTrans/VQ_eval.py +95 -0
- generate_human_motion/VQTrans/ViT-B-32.pt +3 -0
- generate_human_motion/VQTrans/__init__.py +0 -0
- generate_human_motion/VQTrans/__pycache__/__init__.cpython-310.pyc +0 -0
- generate_human_motion/VQTrans/body_models/smpl/J_regressor_extra.npy +3 -0
- generate_human_motion/VQTrans/body_models/smpl/SMPL_NEUTRAL.pkl +3 -0
- generate_human_motion/VQTrans/body_models/smpl/kintree_table.pkl +3 -0
- generate_human_motion/VQTrans/body_models/smpl/smplfaces.npy +3 -0
- generate_human_motion/VQTrans/checkpoints/kit.zip +3 -0
- generate_human_motion/VQTrans/checkpoints/t2m.zip +3 -0
- generate_human_motion/VQTrans/checkpoints/train_vq.py +171 -0
- generate_human_motion/VQTrans/dataset/dataset_TM_eval.py +217 -0
- generate_human_motion/VQTrans/dataset/dataset_TM_train.py +161 -0
- generate_human_motion/VQTrans/dataset/dataset_VQ.py +109 -0
- generate_human_motion/VQTrans/dataset/dataset_tokenize.py +117 -0
- generate_human_motion/VQTrans/dataset/prepare/download_extractor.sh +15 -0
- generate_human_motion/VQTrans/dataset/prepare/download_glove.sh +9 -0
- generate_human_motion/VQTrans/dataset/prepare/download_model.sh +12 -0
- generate_human_motion/VQTrans/dataset/prepare/download_smpl.sh +13 -0
- generate_human_motion/VQTrans/environment.yml +121 -0
- generate_human_motion/VQTrans/models/__init__.py +0 -0
- generate_human_motion/VQTrans/models/__pycache__/__init__.cpython-310.pyc +0 -0
- generate_human_motion/VQTrans/models/__pycache__/encdec.cpython-310.pyc +0 -0
- generate_human_motion/VQTrans/models/__pycache__/pos_encoding.cpython-310.pyc +0 -0
- generate_human_motion/VQTrans/models/__pycache__/quantize_cnn.cpython-310.pyc +0 -0
- generate_human_motion/VQTrans/models/__pycache__/resnet.cpython-310.pyc +0 -0
- generate_human_motion/VQTrans/models/__pycache__/rotation2xyz.cpython-310.pyc +0 -0
- generate_human_motion/VQTrans/models/__pycache__/smpl.cpython-310.pyc +0 -0
- generate_human_motion/VQTrans/models/__pycache__/t2m_trans.cpython-310.pyc +0 -0
- generate_human_motion/VQTrans/models/__pycache__/vqvae.cpython-310.pyc +0 -0
- generate_human_motion/VQTrans/models/encdec.py +67 -0
- generate_human_motion/VQTrans/models/evaluator_wrapper.py +92 -0
- generate_human_motion/VQTrans/models/modules.py +109 -0
- generate_human_motion/VQTrans/models/pos_encoding.py +43 -0
- generate_human_motion/VQTrans/models/quantize_cnn.py +415 -0
- generate_human_motion/VQTrans/models/resnet.py +82 -0
- generate_human_motion/VQTrans/models/rotation2xyz.py +92 -0
- generate_human_motion/VQTrans/models/smpl.py +97 -0
- generate_human_motion/VQTrans/models/t2m_trans.py +211 -0
- generate_human_motion/VQTrans/models/vqvae.py +118 -0
- generate_human_motion/VQTrans/options/__pycache__/option_transformer.cpython-310.pyc +0 -0
- generate_human_motion/VQTrans/options/get_eval_option.py +83 -0
- generate_human_motion/VQTrans/options/option_transformer.py +68 -0
- generate_human_motion/VQTrans/options/option_vq.py +61 -0
- generate_human_motion/VQTrans/output/02ab4ad275eda92f352e2ed8d942eeef_pred.pt +3 -0
- generate_human_motion/VQTrans/output/06c27c738e874b23067c006f52e18ebc_pred.pt +3 -0
- generate_human_motion/VQTrans/output/0edd5f692aeec051d748dee0844f94e1_pred.pt +3 -0
- generate_human_motion/VQTrans/output/23cb7d0e26bb1646b3d386331971449c_pred.pt +3 -0
.gitattributes
CHANGED
@@ -32,3 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
35 |
+
generate_human_motion/VQTrans/output/results.gif filter=lfs diff=lfs merge=lfs -text
|
generate_human_motion/VQTrans/GPT_eval_multi.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
8 |
+
import options.option_transformer as option_trans
|
9 |
+
import models.vqvae as vqvae
|
10 |
+
import utils.utils_model as utils_model
|
11 |
+
import utils.eval_trans as eval_trans
|
12 |
+
from dataset import dataset_TM_eval
|
13 |
+
import models.t2m_trans as 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 |
+
|
19 |
+
##### ---- Exp dirs ---- #####
|
20 |
+
args = option_trans.get_args_parser()
|
21 |
+
torch.manual_seed(args.seed)
|
22 |
+
|
23 |
+
args.out_dir = os.path.join(args.out_dir, f'{args.exp_name}')
|
24 |
+
os.makedirs(args.out_dir, exist_ok = True)
|
25 |
+
|
26 |
+
##### ---- Logger ---- #####
|
27 |
+
logger = utils_model.get_logger(args.out_dir)
|
28 |
+
writer = SummaryWriter(args.out_dir)
|
29 |
+
logger.info(json.dumps(vars(args), indent=4, sort_keys=True))
|
30 |
+
|
31 |
+
from utils.word_vectorizer import WordVectorizer
|
32 |
+
w_vectorizer = WordVectorizer('./glove', 'our_vab')
|
33 |
+
val_loader = dataset_TM_eval.DATALoader(args.dataname, True, 32, w_vectorizer)
|
34 |
+
|
35 |
+
dataset_opt_path = 'checkpoints/kit/Comp_v6_KLD005/opt.txt' if args.dataname == 'kit' else 'checkpoints/t2m/Comp_v6_KLD005/opt.txt'
|
36 |
+
|
37 |
+
wrapper_opt = get_opt(dataset_opt_path, torch.device('cuda'))
|
38 |
+
eval_wrapper = EvaluatorModelWrapper(wrapper_opt)
|
39 |
+
|
40 |
+
##### ---- Network ---- #####
|
41 |
+
|
42 |
+
## load clip model and datasets
|
43 |
+
clip_model, clip_preprocess = clip.load("ViT-B/32", device=torch.device('cuda'), jit=False, download_root='/apdcephfs_cq2/share_1290939/maelyszhang/.cache/clip') # Must set jit=False for training
|
44 |
+
clip.model.convert_weights(clip_model) # Actually this line is unnecessary since clip by default already on float16
|
45 |
+
clip_model.eval()
|
46 |
+
for p in clip_model.parameters():
|
47 |
+
p.requires_grad = False
|
48 |
+
|
49 |
+
net = vqvae.HumanVQVAE(args, ## use args to define different parameters in different quantizers
|
50 |
+
args.nb_code,
|
51 |
+
args.code_dim,
|
52 |
+
args.output_emb_width,
|
53 |
+
args.down_t,
|
54 |
+
args.stride_t,
|
55 |
+
args.width,
|
56 |
+
args.depth,
|
57 |
+
args.dilation_growth_rate)
|
58 |
+
|
59 |
+
|
60 |
+
trans_encoder = trans.Text2Motion_Transformer(num_vq=args.nb_code,
|
61 |
+
embed_dim=args.embed_dim_gpt,
|
62 |
+
clip_dim=args.clip_dim,
|
63 |
+
block_size=args.block_size,
|
64 |
+
num_layers=args.num_layers,
|
65 |
+
n_head=args.n_head_gpt,
|
66 |
+
drop_out_rate=args.drop_out_rate,
|
67 |
+
fc_rate=args.ff_rate)
|
68 |
+
|
69 |
+
|
70 |
+
print ('loading checkpoint from {}'.format(args.resume_pth))
|
71 |
+
ckpt = torch.load(args.resume_pth, map_location='cpu')
|
72 |
+
net.load_state_dict(ckpt['net'], strict=True)
|
73 |
+
net.eval()
|
74 |
+
net.cuda()
|
75 |
+
|
76 |
+
if args.resume_trans is not None:
|
77 |
+
print ('loading transformer checkpoint from {}'.format(args.resume_trans))
|
78 |
+
ckpt = torch.load(args.resume_trans, map_location='cpu')
|
79 |
+
trans_encoder.load_state_dict(ckpt['trans'], strict=True)
|
80 |
+
trans_encoder.train()
|
81 |
+
trans_encoder.cuda()
|
82 |
+
|
83 |
+
|
84 |
+
fid = []
|
85 |
+
div = []
|
86 |
+
top1 = []
|
87 |
+
top2 = []
|
88 |
+
top3 = []
|
89 |
+
matching = []
|
90 |
+
multi = []
|
91 |
+
repeat_time = 20
|
92 |
+
|
93 |
+
|
94 |
+
for i in range(repeat_time):
|
95 |
+
best_fid, 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_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))
|
96 |
+
fid.append(best_fid)
|
97 |
+
div.append(best_div)
|
98 |
+
top1.append(best_top1)
|
99 |
+
top2.append(best_top2)
|
100 |
+
top3.append(best_top3)
|
101 |
+
matching.append(best_matching)
|
102 |
+
multi.append(best_multi)
|
103 |
+
|
104 |
+
print('final result:')
|
105 |
+
print('fid: ', sum(fid)/repeat_time)
|
106 |
+
print('div: ', sum(div)/repeat_time)
|
107 |
+
print('top1: ', sum(top1)/repeat_time)
|
108 |
+
print('top2: ', sum(top2)/repeat_time)
|
109 |
+
print('top3: ', sum(top3)/repeat_time)
|
110 |
+
print('matching: ', sum(matching)/repeat_time)
|
111 |
+
print('multi: ', sum(multi)/repeat_time)
|
112 |
+
|
113 |
+
fid = np.array(fid)
|
114 |
+
div = np.array(div)
|
115 |
+
top1 = np.array(top1)
|
116 |
+
top2 = np.array(top2)
|
117 |
+
top3 = np.array(top3)
|
118 |
+
matching = np.array(matching)
|
119 |
+
multi = np.array(multi)
|
120 |
+
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}, Multi. {np.mean(multi):.3f}, conf. {np.std(multi)*1.96/np.sqrt(repeat_time):.3f}"
|
121 |
+
logger.info(msg_final)
|
generate_human_motion/VQTrans/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)
|
generate_human_motion/VQTrans/ViT-B-32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af
|
3 |
+
size 353976522
|
generate_human_motion/VQTrans/__init__.py
ADDED
File without changes
|
generate_human_motion/VQTrans/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (162 Bytes). View file
|
|
generate_human_motion/VQTrans/body_models/smpl/J_regressor_extra.npy
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cc968ea4f9855571e82f90203280836b01f13ee42a8e1b89d8d580b801242a89
|
3 |
+
size 496160
|
generate_human_motion/VQTrans/body_models/smpl/SMPL_NEUTRAL.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:98e65c74ad9b998783132f00880d1025a8d64b158e040e6ef13a557e5098bc42
|
3 |
+
size 39001280
|
generate_human_motion/VQTrans/body_models/smpl/kintree_table.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:62116ec76c6192ae912557122ea935267ba7188144efb9306ea1366f0e50d4d2
|
3 |
+
size 349
|
generate_human_motion/VQTrans/body_models/smpl/smplfaces.npy
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7ee8e99db736acf178a6078ab5710ca942edc3738d34c72f41a35c40b370e045
|
3 |
+
size 165440
|
generate_human_motion/VQTrans/checkpoints/kit.zip
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0e9d54e1c68bacad61277f89c7d05f9c88a68fd92ff79f79644128bb9b2508cb
|
3 |
+
size 704518254
|
generate_human_motion/VQTrans/checkpoints/t2m.zip
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:09e0628dbc585416217617c0583415c8f654ff855703d72fdb713f7061c0863e
|
3 |
+
size 1222422692
|
generate_human_motion/VQTrans/checkpoints/train_vq.py
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
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 |
+
|
44 |
+
if args.dataname == 'kit' :
|
45 |
+
dataset_opt_path = 'checkpoints/kit/Comp_v6_KLD005/opt.txt'
|
46 |
+
args.nb_joints = 21
|
47 |
+
|
48 |
+
else :
|
49 |
+
dataset_opt_path = 'checkpoints/t2m/Comp_v6_KLD005/opt.txt'
|
50 |
+
args.nb_joints = 22
|
51 |
+
|
52 |
+
logger.info(f'Training on {args.dataname}, motions are with {args.nb_joints} joints')
|
53 |
+
|
54 |
+
wrapper_opt = get_opt(dataset_opt_path, torch.device('cuda'))
|
55 |
+
eval_wrapper = EvaluatorModelWrapper(wrapper_opt)
|
56 |
+
|
57 |
+
|
58 |
+
##### ---- Dataloader ---- #####
|
59 |
+
train_loader = dataset_VQ.DATALoader(args.dataname,
|
60 |
+
args.batch_size,
|
61 |
+
window_size=args.window_size,
|
62 |
+
unit_length=2**args.down_t)
|
63 |
+
|
64 |
+
train_loader_iter = dataset_VQ.cycle(train_loader)
|
65 |
+
|
66 |
+
val_loader = dataset_TM_eval.DATALoader(args.dataname, False,
|
67 |
+
32,
|
68 |
+
w_vectorizer,
|
69 |
+
unit_length=2**args.down_t)
|
70 |
+
|
71 |
+
##### ---- Network ---- #####
|
72 |
+
net = vqvae.HumanVQVAE(args, ## use args to define different parameters in different quantizers
|
73 |
+
args.nb_code,
|
74 |
+
args.code_dim,
|
75 |
+
args.output_emb_width,
|
76 |
+
args.down_t,
|
77 |
+
args.stride_t,
|
78 |
+
args.width,
|
79 |
+
args.depth,
|
80 |
+
args.dilation_growth_rate,
|
81 |
+
args.vq_act,
|
82 |
+
args.vq_norm)
|
83 |
+
|
84 |
+
|
85 |
+
if args.resume_pth :
|
86 |
+
logger.info('loading checkpoint from {}'.format(args.resume_pth))
|
87 |
+
ckpt = torch.load(args.resume_pth, map_location='cpu')
|
88 |
+
net.load_state_dict(ckpt['net'], strict=True)
|
89 |
+
net.train()
|
90 |
+
net.cuda()
|
91 |
+
|
92 |
+
##### ---- Optimizer & Scheduler ---- #####
|
93 |
+
optimizer = optim.AdamW(net.parameters(), lr=args.lr, betas=(0.9, 0.99), weight_decay=args.weight_decay)
|
94 |
+
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=args.lr_scheduler, gamma=args.gamma)
|
95 |
+
|
96 |
+
|
97 |
+
Loss = losses.ReConsLoss(args.recons_loss, args.nb_joints)
|
98 |
+
|
99 |
+
##### ------ warm-up ------- #####
|
100 |
+
avg_recons, avg_perplexity, avg_commit = 0., 0., 0.
|
101 |
+
|
102 |
+
for nb_iter in range(1, args.warm_up_iter):
|
103 |
+
|
104 |
+
optimizer, current_lr = update_lr_warm_up(optimizer, nb_iter, args.warm_up_iter, args.lr)
|
105 |
+
|
106 |
+
gt_motion = next(train_loader_iter)
|
107 |
+
gt_motion = gt_motion.cuda().float() # (bs, 64, dim)
|
108 |
+
|
109 |
+
pred_motion, loss_commit, perplexity = net(gt_motion)
|
110 |
+
loss_motion = Loss(pred_motion, gt_motion)
|
111 |
+
loss_vel = Loss.forward_vel(pred_motion, gt_motion)
|
112 |
+
|
113 |
+
loss = loss_motion + args.commit * loss_commit + args.loss_vel * loss_vel
|
114 |
+
|
115 |
+
optimizer.zero_grad()
|
116 |
+
loss.backward()
|
117 |
+
optimizer.step()
|
118 |
+
|
119 |
+
avg_recons += loss_motion.item()
|
120 |
+
avg_perplexity += perplexity.item()
|
121 |
+
avg_commit += loss_commit.item()
|
122 |
+
|
123 |
+
if nb_iter % args.print_iter == 0 :
|
124 |
+
avg_recons /= args.print_iter
|
125 |
+
avg_perplexity /= args.print_iter
|
126 |
+
avg_commit /= args.print_iter
|
127 |
+
|
128 |
+
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}")
|
129 |
+
|
130 |
+
avg_recons, avg_perplexity, avg_commit = 0., 0., 0.
|
131 |
+
|
132 |
+
##### ---- Training ---- #####
|
133 |
+
avg_recons, avg_perplexity, avg_commit = 0., 0., 0.
|
134 |
+
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)
|
135 |
+
|
136 |
+
for nb_iter in range(1, args.total_iter + 1):
|
137 |
+
|
138 |
+
gt_motion = next(train_loader_iter)
|
139 |
+
gt_motion = gt_motion.cuda().float() # bs, nb_joints, joints_dim, seq_len
|
140 |
+
|
141 |
+
pred_motion, loss_commit, perplexity = net(gt_motion)
|
142 |
+
loss_motion = Loss(pred_motion, gt_motion)
|
143 |
+
loss_vel = Loss.forward_vel(pred_motion, gt_motion)
|
144 |
+
|
145 |
+
loss = loss_motion + args.commit * loss_commit + args.loss_vel * loss_vel
|
146 |
+
|
147 |
+
optimizer.zero_grad()
|
148 |
+
loss.backward()
|
149 |
+
optimizer.step()
|
150 |
+
scheduler.step()
|
151 |
+
|
152 |
+
avg_recons += loss_motion.item()
|
153 |
+
avg_perplexity += perplexity.item()
|
154 |
+
avg_commit += loss_commit.item()
|
155 |
+
|
156 |
+
if nb_iter % args.print_iter == 0 :
|
157 |
+
avg_recons /= args.print_iter
|
158 |
+
avg_perplexity /= args.print_iter
|
159 |
+
avg_commit /= args.print_iter
|
160 |
+
|
161 |
+
writer.add_scalar('./Train/L1', avg_recons, nb_iter)
|
162 |
+
writer.add_scalar('./Train/PPL', avg_perplexity, nb_iter)
|
163 |
+
writer.add_scalar('./Train/Commit', avg_commit, nb_iter)
|
164 |
+
|
165 |
+
logger.info(f"Train. Iter {nb_iter} : \t Commit. {avg_commit:.5f} \t PPL. {avg_perplexity:.2f} \t Recons. {avg_recons:.5f}")
|
166 |
+
|
167 |
+
avg_recons, avg_perplexity, avg_commit = 0., 0., 0.,
|
168 |
+
|
169 |
+
if nb_iter % args.eval_iter==0 :
|
170 |
+
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)
|
171 |
+
|
generate_human_motion/VQTrans/dataset/dataset_TM_eval.py
ADDED
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch.utils import data
|
3 |
+
import numpy as np
|
4 |
+
from os.path import join as pjoin
|
5 |
+
import random
|
6 |
+
import codecs as cs
|
7 |
+
from tqdm import tqdm
|
8 |
+
|
9 |
+
import utils.paramUtil as paramUtil
|
10 |
+
from torch.utils.data._utils.collate import default_collate
|
11 |
+
|
12 |
+
|
13 |
+
def collate_fn(batch):
|
14 |
+
batch.sort(key=lambda x: x[3], reverse=True)
|
15 |
+
return default_collate(batch)
|
16 |
+
|
17 |
+
|
18 |
+
'''For use of training text-2-motion generative model'''
|
19 |
+
class Text2MotionDataset(data.Dataset):
|
20 |
+
def __init__(self, dataset_name, is_test, w_vectorizer, feat_bias = 5, max_text_len = 20, unit_length = 4):
|
21 |
+
|
22 |
+
self.max_length = 20
|
23 |
+
self.pointer = 0
|
24 |
+
self.dataset_name = dataset_name
|
25 |
+
self.is_test = is_test
|
26 |
+
self.max_text_len = max_text_len
|
27 |
+
self.unit_length = unit_length
|
28 |
+
self.w_vectorizer = w_vectorizer
|
29 |
+
if dataset_name == 't2m':
|
30 |
+
self.data_root = './dataset/HumanML3D'
|
31 |
+
self.motion_dir = pjoin(self.data_root, 'new_joint_vecs')
|
32 |
+
self.text_dir = pjoin(self.data_root, 'texts')
|
33 |
+
self.joints_num = 22
|
34 |
+
radius = 4
|
35 |
+
fps = 20
|
36 |
+
self.max_motion_length = 196
|
37 |
+
dim_pose = 263
|
38 |
+
kinematic_chain = paramUtil.t2m_kinematic_chain
|
39 |
+
self.meta_dir = 'checkpoints/t2m/VQVAEV3_CB1024_CMT_H1024_NRES3/meta'
|
40 |
+
elif dataset_name == 'kit':
|
41 |
+
self.data_root = './dataset/KIT-ML'
|
42 |
+
self.motion_dir = pjoin(self.data_root, 'new_joint_vecs')
|
43 |
+
self.text_dir = pjoin(self.data_root, 'texts')
|
44 |
+
self.joints_num = 21
|
45 |
+
radius = 240 * 8
|
46 |
+
fps = 12.5
|
47 |
+
dim_pose = 251
|
48 |
+
self.max_motion_length = 196
|
49 |
+
kinematic_chain = paramUtil.kit_kinematic_chain
|
50 |
+
self.meta_dir = 'checkpoints/kit/VQVAEV3_CB1024_CMT_H1024_NRES3/meta'
|
51 |
+
|
52 |
+
mean = np.load(pjoin(self.meta_dir, 'mean.npy'))
|
53 |
+
std = np.load(pjoin(self.meta_dir, 'std.npy'))
|
54 |
+
|
55 |
+
if is_test:
|
56 |
+
split_file = pjoin(self.data_root, 'test.txt')
|
57 |
+
else:
|
58 |
+
split_file = pjoin(self.data_root, 'val.txt')
|
59 |
+
|
60 |
+
min_motion_len = 40 if self.dataset_name =='t2m' else 24
|
61 |
+
# min_motion_len = 64
|
62 |
+
|
63 |
+
joints_num = self.joints_num
|
64 |
+
|
65 |
+
data_dict = {}
|
66 |
+
id_list = []
|
67 |
+
with cs.open(split_file, 'r') as f:
|
68 |
+
for line in f.readlines():
|
69 |
+
id_list.append(line.strip())
|
70 |
+
|
71 |
+
new_name_list = []
|
72 |
+
length_list = []
|
73 |
+
for name in tqdm(id_list):
|
74 |
+
try:
|
75 |
+
motion = np.load(pjoin(self.motion_dir, name + '.npy'))
|
76 |
+
if (len(motion)) < min_motion_len or (len(motion) >= 200):
|
77 |
+
continue
|
78 |
+
text_data = []
|
79 |
+
flag = False
|
80 |
+
with cs.open(pjoin(self.text_dir, name + '.txt')) as f:
|
81 |
+
for line in f.readlines():
|
82 |
+
text_dict = {}
|
83 |
+
line_split = line.strip().split('#')
|
84 |
+
caption = line_split[0]
|
85 |
+
tokens = line_split[1].split(' ')
|
86 |
+
f_tag = float(line_split[2])
|
87 |
+
to_tag = float(line_split[3])
|
88 |
+
f_tag = 0.0 if np.isnan(f_tag) else f_tag
|
89 |
+
to_tag = 0.0 if np.isnan(to_tag) else to_tag
|
90 |
+
|
91 |
+
text_dict['caption'] = caption
|
92 |
+
text_dict['tokens'] = tokens
|
93 |
+
if f_tag == 0.0 and to_tag == 0.0:
|
94 |
+
flag = True
|
95 |
+
text_data.append(text_dict)
|
96 |
+
else:
|
97 |
+
try:
|
98 |
+
n_motion = motion[int(f_tag*fps) : int(to_tag*fps)]
|
99 |
+
if (len(n_motion)) < min_motion_len or (len(n_motion) >= 200):
|
100 |
+
continue
|
101 |
+
new_name = random.choice('ABCDEFGHIJKLMNOPQRSTUVW') + '_' + name
|
102 |
+
while new_name in data_dict:
|
103 |
+
new_name = random.choice('ABCDEFGHIJKLMNOPQRSTUVW') + '_' + name
|
104 |
+
data_dict[new_name] = {'motion': n_motion,
|
105 |
+
'length': len(n_motion),
|
106 |
+
'text':[text_dict]}
|
107 |
+
new_name_list.append(new_name)
|
108 |
+
length_list.append(len(n_motion))
|
109 |
+
except:
|
110 |
+
print(line_split)
|
111 |
+
print(line_split[2], line_split[3], f_tag, to_tag, name)
|
112 |
+
# break
|
113 |
+
|
114 |
+
if flag:
|
115 |
+
data_dict[name] = {'motion': motion,
|
116 |
+
'length': len(motion),
|
117 |
+
'text': text_data}
|
118 |
+
new_name_list.append(name)
|
119 |
+
length_list.append(len(motion))
|
120 |
+
except Exception as e:
|
121 |
+
# print(e)
|
122 |
+
pass
|
123 |
+
|
124 |
+
name_list, length_list = zip(*sorted(zip(new_name_list, length_list), key=lambda x: x[1]))
|
125 |
+
self.mean = mean
|
126 |
+
self.std = std
|
127 |
+
self.length_arr = np.array(length_list)
|
128 |
+
self.data_dict = data_dict
|
129 |
+
self.name_list = name_list
|
130 |
+
self.reset_max_len(self.max_length)
|
131 |
+
|
132 |
+
def reset_max_len(self, length):
|
133 |
+
assert length <= self.max_motion_length
|
134 |
+
self.pointer = np.searchsorted(self.length_arr, length)
|
135 |
+
print("Pointer Pointing at %d"%self.pointer)
|
136 |
+
self.max_length = length
|
137 |
+
|
138 |
+
def inv_transform(self, data):
|
139 |
+
return data * self.std + self.mean
|
140 |
+
|
141 |
+
def forward_transform(self, data):
|
142 |
+
return (data - self.mean) / self.std
|
143 |
+
|
144 |
+
def __len__(self):
|
145 |
+
return len(self.data_dict) - self.pointer
|
146 |
+
|
147 |
+
def __getitem__(self, item):
|
148 |
+
idx = self.pointer + item
|
149 |
+
name = self.name_list[idx]
|
150 |
+
data = self.data_dict[name]
|
151 |
+
# data = self.data_dict[self.name_list[idx]]
|
152 |
+
motion, m_length, text_list = data['motion'], data['length'], data['text']
|
153 |
+
# Randomly select a caption
|
154 |
+
text_data = random.choice(text_list)
|
155 |
+
caption, tokens = text_data['caption'], text_data['tokens']
|
156 |
+
|
157 |
+
if len(tokens) < self.max_text_len:
|
158 |
+
# pad with "unk"
|
159 |
+
tokens = ['sos/OTHER'] + tokens + ['eos/OTHER']
|
160 |
+
sent_len = len(tokens)
|
161 |
+
tokens = tokens + ['unk/OTHER'] * (self.max_text_len + 2 - sent_len)
|
162 |
+
else:
|
163 |
+
# crop
|
164 |
+
tokens = tokens[:self.max_text_len]
|
165 |
+
tokens = ['sos/OTHER'] + tokens + ['eos/OTHER']
|
166 |
+
sent_len = len(tokens)
|
167 |
+
pos_one_hots = []
|
168 |
+
word_embeddings = []
|
169 |
+
for token in tokens:
|
170 |
+
word_emb, pos_oh = self.w_vectorizer[token]
|
171 |
+
pos_one_hots.append(pos_oh[None, :])
|
172 |
+
word_embeddings.append(word_emb[None, :])
|
173 |
+
pos_one_hots = np.concatenate(pos_one_hots, axis=0)
|
174 |
+
word_embeddings = np.concatenate(word_embeddings, axis=0)
|
175 |
+
|
176 |
+
if self.unit_length < 10:
|
177 |
+
coin2 = np.random.choice(['single', 'single', 'double'])
|
178 |
+
else:
|
179 |
+
coin2 = 'single'
|
180 |
+
|
181 |
+
if coin2 == 'double':
|
182 |
+
m_length = (m_length // self.unit_length - 1) * self.unit_length
|
183 |
+
elif coin2 == 'single':
|
184 |
+
m_length = (m_length // self.unit_length) * self.unit_length
|
185 |
+
idx = random.randint(0, len(motion) - m_length)
|
186 |
+
motion = motion[idx:idx+m_length]
|
187 |
+
|
188 |
+
"Z Normalization"
|
189 |
+
motion = (motion - self.mean) / self.std
|
190 |
+
|
191 |
+
if m_length < self.max_motion_length:
|
192 |
+
motion = np.concatenate([motion,
|
193 |
+
np.zeros((self.max_motion_length - m_length, motion.shape[1]))
|
194 |
+
], axis=0)
|
195 |
+
|
196 |
+
return word_embeddings, pos_one_hots, caption, sent_len, motion, m_length, '_'.join(tokens), name
|
197 |
+
|
198 |
+
|
199 |
+
|
200 |
+
|
201 |
+
def DATALoader(dataset_name, is_test,
|
202 |
+
batch_size, w_vectorizer,
|
203 |
+
num_workers = 8, unit_length = 4) :
|
204 |
+
|
205 |
+
val_loader = torch.utils.data.DataLoader(Text2MotionDataset(dataset_name, is_test, w_vectorizer, unit_length=unit_length),
|
206 |
+
batch_size,
|
207 |
+
shuffle = True,
|
208 |
+
num_workers=num_workers,
|
209 |
+
collate_fn=collate_fn,
|
210 |
+
drop_last = True)
|
211 |
+
return val_loader
|
212 |
+
|
213 |
+
|
214 |
+
def cycle(iterable):
|
215 |
+
while True:
|
216 |
+
for x in iterable:
|
217 |
+
yield x
|
generate_human_motion/VQTrans/dataset/dataset_TM_train.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch.utils import data
|
3 |
+
import numpy as np
|
4 |
+
from os.path import join as pjoin
|
5 |
+
import random
|
6 |
+
import codecs as cs
|
7 |
+
from tqdm import tqdm
|
8 |
+
import utils.paramUtil as paramUtil
|
9 |
+
from torch.utils.data._utils.collate import default_collate
|
10 |
+
|
11 |
+
|
12 |
+
def collate_fn(batch):
|
13 |
+
batch.sort(key=lambda x: x[3], reverse=True)
|
14 |
+
return default_collate(batch)
|
15 |
+
|
16 |
+
|
17 |
+
'''For use of training text-2-motion generative model'''
|
18 |
+
class Text2MotionDataset(data.Dataset):
|
19 |
+
def __init__(self, dataset_name, feat_bias = 5, unit_length = 4, codebook_size = 1024, tokenizer_name=None):
|
20 |
+
|
21 |
+
self.max_length = 64
|
22 |
+
self.pointer = 0
|
23 |
+
self.dataset_name = dataset_name
|
24 |
+
|
25 |
+
self.unit_length = unit_length
|
26 |
+
# self.mot_start_idx = codebook_size
|
27 |
+
self.mot_end_idx = codebook_size
|
28 |
+
self.mot_pad_idx = codebook_size + 1
|
29 |
+
if dataset_name == 't2m':
|
30 |
+
self.data_root = './dataset/HumanML3D'
|
31 |
+
self.motion_dir = pjoin(self.data_root, 'new_joint_vecs')
|
32 |
+
self.text_dir = pjoin(self.data_root, 'texts')
|
33 |
+
self.joints_num = 22
|
34 |
+
radius = 4
|
35 |
+
fps = 20
|
36 |
+
self.max_motion_length = 26 if unit_length == 8 else 51
|
37 |
+
dim_pose = 263
|
38 |
+
kinematic_chain = paramUtil.t2m_kinematic_chain
|
39 |
+
elif dataset_name == 'kit':
|
40 |
+
self.data_root = './dataset/KIT-ML'
|
41 |
+
self.motion_dir = pjoin(self.data_root, 'new_joint_vecs')
|
42 |
+
self.text_dir = pjoin(self.data_root, 'texts')
|
43 |
+
self.joints_num = 21
|
44 |
+
radius = 240 * 8
|
45 |
+
fps = 12.5
|
46 |
+
dim_pose = 251
|
47 |
+
self.max_motion_length = 26 if unit_length == 8 else 51
|
48 |
+
kinematic_chain = paramUtil.kit_kinematic_chain
|
49 |
+
|
50 |
+
split_file = pjoin(self.data_root, 'train.txt')
|
51 |
+
|
52 |
+
|
53 |
+
id_list = []
|
54 |
+
with cs.open(split_file, 'r') as f:
|
55 |
+
for line in f.readlines():
|
56 |
+
id_list.append(line.strip())
|
57 |
+
|
58 |
+
new_name_list = []
|
59 |
+
data_dict = {}
|
60 |
+
for name in tqdm(id_list):
|
61 |
+
try:
|
62 |
+
m_token_list = np.load(pjoin(self.data_root, tokenizer_name, '%s.npy'%name))
|
63 |
+
|
64 |
+
# Read text
|
65 |
+
with cs.open(pjoin(self.text_dir, name + '.txt')) as f:
|
66 |
+
text_data = []
|
67 |
+
flag = False
|
68 |
+
lines = f.readlines()
|
69 |
+
|
70 |
+
for line in lines:
|
71 |
+
try:
|
72 |
+
text_dict = {}
|
73 |
+
line_split = line.strip().split('#')
|
74 |
+
caption = line_split[0]
|
75 |
+
t_tokens = line_split[1].split(' ')
|
76 |
+
f_tag = float(line_split[2])
|
77 |
+
to_tag = float(line_split[3])
|
78 |
+
f_tag = 0.0 if np.isnan(f_tag) else f_tag
|
79 |
+
to_tag = 0.0 if np.isnan(to_tag) else to_tag
|
80 |
+
|
81 |
+
text_dict['caption'] = caption
|
82 |
+
text_dict['tokens'] = t_tokens
|
83 |
+
if f_tag == 0.0 and to_tag == 0.0:
|
84 |
+
flag = True
|
85 |
+
text_data.append(text_dict)
|
86 |
+
else:
|
87 |
+
m_token_list_new = [tokens[int(f_tag*fps/unit_length) : int(to_tag*fps/unit_length)] for tokens in m_token_list if int(f_tag*fps/unit_length) < int(to_tag*fps/unit_length)]
|
88 |
+
|
89 |
+
if len(m_token_list_new) == 0:
|
90 |
+
continue
|
91 |
+
new_name = '%s_%f_%f'%(name, f_tag, to_tag)
|
92 |
+
|
93 |
+
data_dict[new_name] = {'m_token_list': m_token_list_new,
|
94 |
+
'text':[text_dict]}
|
95 |
+
new_name_list.append(new_name)
|
96 |
+
except:
|
97 |
+
pass
|
98 |
+
|
99 |
+
if flag:
|
100 |
+
data_dict[name] = {'m_token_list': m_token_list,
|
101 |
+
'text':text_data}
|
102 |
+
new_name_list.append(name)
|
103 |
+
except:
|
104 |
+
pass
|
105 |
+
self.data_dict = data_dict
|
106 |
+
self.name_list = new_name_list
|
107 |
+
|
108 |
+
def __len__(self):
|
109 |
+
return len(self.data_dict)
|
110 |
+
|
111 |
+
def __getitem__(self, item):
|
112 |
+
data = self.data_dict[self.name_list[item]]
|
113 |
+
m_token_list, text_list = data['m_token_list'], data['text']
|
114 |
+
m_tokens = random.choice(m_token_list)
|
115 |
+
|
116 |
+
text_data = random.choice(text_list)
|
117 |
+
caption= text_data['caption']
|
118 |
+
|
119 |
+
|
120 |
+
coin = np.random.choice([False, False, True])
|
121 |
+
# print(len(m_tokens))
|
122 |
+
if coin:
|
123 |
+
# drop one token at the head or tail
|
124 |
+
coin2 = np.random.choice([True, False])
|
125 |
+
if coin2:
|
126 |
+
m_tokens = m_tokens[:-1]
|
127 |
+
else:
|
128 |
+
m_tokens = m_tokens[1:]
|
129 |
+
m_tokens_len = m_tokens.shape[0]
|
130 |
+
|
131 |
+
if m_tokens_len+1 < self.max_motion_length:
|
132 |
+
m_tokens = np.concatenate([m_tokens, np.ones((1), dtype=int) * self.mot_end_idx, np.ones((self.max_motion_length-1-m_tokens_len), dtype=int) * self.mot_pad_idx], axis=0)
|
133 |
+
else:
|
134 |
+
m_tokens = np.concatenate([m_tokens, np.ones((1), dtype=int) * self.mot_end_idx], axis=0)
|
135 |
+
|
136 |
+
return caption, m_tokens.reshape(-1), m_tokens_len
|
137 |
+
|
138 |
+
|
139 |
+
|
140 |
+
|
141 |
+
def DATALoader(dataset_name,
|
142 |
+
batch_size, codebook_size, tokenizer_name, unit_length=4,
|
143 |
+
num_workers = 8) :
|
144 |
+
|
145 |
+
train_loader = torch.utils.data.DataLoader(Text2MotionDataset(dataset_name, codebook_size = codebook_size, tokenizer_name = tokenizer_name, unit_length=unit_length),
|
146 |
+
batch_size,
|
147 |
+
shuffle=True,
|
148 |
+
num_workers=num_workers,
|
149 |
+
#collate_fn=collate_fn,
|
150 |
+
drop_last = True)
|
151 |
+
|
152 |
+
|
153 |
+
return train_loader
|
154 |
+
|
155 |
+
|
156 |
+
def cycle(iterable):
|
157 |
+
while True:
|
158 |
+
for x in iterable:
|
159 |
+
yield x
|
160 |
+
|
161 |
+
|
generate_human_motion/VQTrans/dataset/dataset_VQ.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch.utils import data
|
3 |
+
import numpy as np
|
4 |
+
from os.path import join as pjoin
|
5 |
+
import random
|
6 |
+
import codecs as cs
|
7 |
+
from tqdm import tqdm
|
8 |
+
|
9 |
+
|
10 |
+
|
11 |
+
class VQMotionDataset(data.Dataset):
|
12 |
+
def __init__(self, dataset_name, window_size = 64, unit_length = 4):
|
13 |
+
self.window_size = window_size
|
14 |
+
self.unit_length = unit_length
|
15 |
+
self.dataset_name = dataset_name
|
16 |
+
|
17 |
+
if dataset_name == 't2m':
|
18 |
+
self.data_root = './dataset/HumanML3D'
|
19 |
+
self.motion_dir = pjoin(self.data_root, 'new_joint_vecs')
|
20 |
+
self.text_dir = pjoin(self.data_root, 'texts')
|
21 |
+
self.joints_num = 22
|
22 |
+
self.max_motion_length = 196
|
23 |
+
self.meta_dir = 'checkpoints/t2m/VQVAEV3_CB1024_CMT_H1024_NRES3/meta'
|
24 |
+
|
25 |
+
elif dataset_name == 'kit':
|
26 |
+
self.data_root = './dataset/KIT-ML'
|
27 |
+
self.motion_dir = pjoin(self.data_root, 'new_joint_vecs')
|
28 |
+
self.text_dir = pjoin(self.data_root, 'texts')
|
29 |
+
self.joints_num = 21
|
30 |
+
|
31 |
+
self.max_motion_length = 196
|
32 |
+
self.meta_dir = 'checkpoints/kit/VQVAEV3_CB1024_CMT_H1024_NRES3/meta'
|
33 |
+
|
34 |
+
joints_num = self.joints_num
|
35 |
+
|
36 |
+
mean = np.load(pjoin(self.meta_dir, 'mean.npy'))
|
37 |
+
std = np.load(pjoin(self.meta_dir, 'std.npy'))
|
38 |
+
|
39 |
+
split_file = pjoin(self.data_root, 'train.txt')
|
40 |
+
|
41 |
+
self.data = []
|
42 |
+
self.lengths = []
|
43 |
+
id_list = []
|
44 |
+
with cs.open(split_file, 'r') as f:
|
45 |
+
for line in f.readlines():
|
46 |
+
id_list.append(line.strip())
|
47 |
+
|
48 |
+
for name in tqdm(id_list):
|
49 |
+
try:
|
50 |
+
motion = np.load(pjoin(self.motion_dir, name + '.npy'))
|
51 |
+
if motion.shape[0] < self.window_size:
|
52 |
+
continue
|
53 |
+
self.lengths.append(motion.shape[0] - self.window_size)
|
54 |
+
self.data.append(motion)
|
55 |
+
except:
|
56 |
+
# Some motion may not exist in KIT dataset
|
57 |
+
pass
|
58 |
+
|
59 |
+
|
60 |
+
self.mean = mean
|
61 |
+
self.std = std
|
62 |
+
print("Total number of motions {}".format(len(self.data)))
|
63 |
+
|
64 |
+
def inv_transform(self, data):
|
65 |
+
return data * self.std + self.mean
|
66 |
+
|
67 |
+
def compute_sampling_prob(self) :
|
68 |
+
|
69 |
+
prob = np.array(self.lengths, dtype=np.float32)
|
70 |
+
prob /= np.sum(prob)
|
71 |
+
return prob
|
72 |
+
|
73 |
+
def __len__(self):
|
74 |
+
return len(self.data)
|
75 |
+
|
76 |
+
def __getitem__(self, item):
|
77 |
+
motion = self.data[item]
|
78 |
+
|
79 |
+
idx = random.randint(0, len(motion) - self.window_size)
|
80 |
+
|
81 |
+
motion = motion[idx:idx+self.window_size]
|
82 |
+
"Z Normalization"
|
83 |
+
motion = (motion - self.mean) / self.std
|
84 |
+
|
85 |
+
return motion
|
86 |
+
|
87 |
+
def DATALoader(dataset_name,
|
88 |
+
batch_size,
|
89 |
+
num_workers = 8,
|
90 |
+
window_size = 64,
|
91 |
+
unit_length = 4):
|
92 |
+
|
93 |
+
trainSet = VQMotionDataset(dataset_name, window_size=window_size, unit_length=unit_length)
|
94 |
+
prob = trainSet.compute_sampling_prob()
|
95 |
+
sampler = torch.utils.data.WeightedRandomSampler(prob, num_samples = len(trainSet) * 1000, replacement=True)
|
96 |
+
train_loader = torch.utils.data.DataLoader(trainSet,
|
97 |
+
batch_size,
|
98 |
+
shuffle=True,
|
99 |
+
#sampler=sampler,
|
100 |
+
num_workers=num_workers,
|
101 |
+
#collate_fn=collate_fn,
|
102 |
+
drop_last = True)
|
103 |
+
|
104 |
+
return train_loader
|
105 |
+
|
106 |
+
def cycle(iterable):
|
107 |
+
while True:
|
108 |
+
for x in iterable:
|
109 |
+
yield x
|
generate_human_motion/VQTrans/dataset/dataset_tokenize.py
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch.utils import data
|
3 |
+
import numpy as np
|
4 |
+
from os.path import join as pjoin
|
5 |
+
import random
|
6 |
+
import codecs as cs
|
7 |
+
from tqdm import tqdm
|
8 |
+
|
9 |
+
|
10 |
+
|
11 |
+
class VQMotionDataset(data.Dataset):
|
12 |
+
def __init__(self, dataset_name, feat_bias = 5, window_size = 64, unit_length = 8):
|
13 |
+
self.window_size = window_size
|
14 |
+
self.unit_length = unit_length
|
15 |
+
self.feat_bias = feat_bias
|
16 |
+
|
17 |
+
self.dataset_name = dataset_name
|
18 |
+
min_motion_len = 40 if dataset_name =='t2m' else 24
|
19 |
+
|
20 |
+
if dataset_name == 't2m':
|
21 |
+
self.data_root = './dataset/HumanML3D'
|
22 |
+
self.motion_dir = pjoin(self.data_root, 'new_joint_vecs')
|
23 |
+
self.text_dir = pjoin(self.data_root, 'texts')
|
24 |
+
self.joints_num = 22
|
25 |
+
radius = 4
|
26 |
+
fps = 20
|
27 |
+
self.max_motion_length = 196
|
28 |
+
dim_pose = 263
|
29 |
+
self.meta_dir = 'checkpoints/t2m/VQVAEV3_CB1024_CMT_H1024_NRES3/meta'
|
30 |
+
#kinematic_chain = paramUtil.t2m_kinematic_chain
|
31 |
+
elif dataset_name == 'kit':
|
32 |
+
self.data_root = './dataset/KIT-ML'
|
33 |
+
self.motion_dir = pjoin(self.data_root, 'new_joint_vecs')
|
34 |
+
self.text_dir = pjoin(self.data_root, 'texts')
|
35 |
+
self.joints_num = 21
|
36 |
+
radius = 240 * 8
|
37 |
+
fps = 12.5
|
38 |
+
dim_pose = 251
|
39 |
+
self.max_motion_length = 196
|
40 |
+
self.meta_dir = 'checkpoints/kit/VQVAEV3_CB1024_CMT_H1024_NRES3/meta'
|
41 |
+
#kinematic_chain = paramUtil.kit_kinematic_chain
|
42 |
+
|
43 |
+
joints_num = self.joints_num
|
44 |
+
|
45 |
+
mean = np.load(pjoin(self.meta_dir, 'mean.npy'))
|
46 |
+
std = np.load(pjoin(self.meta_dir, 'std.npy'))
|
47 |
+
|
48 |
+
split_file = pjoin(self.data_root, 'train.txt')
|
49 |
+
|
50 |
+
data_dict = {}
|
51 |
+
id_list = []
|
52 |
+
with cs.open(split_file, 'r') as f:
|
53 |
+
for line in f.readlines():
|
54 |
+
id_list.append(line.strip())
|
55 |
+
|
56 |
+
new_name_list = []
|
57 |
+
length_list = []
|
58 |
+
for name in tqdm(id_list):
|
59 |
+
try:
|
60 |
+
motion = np.load(pjoin(self.motion_dir, name + '.npy'))
|
61 |
+
if (len(motion)) < min_motion_len or (len(motion) >= 200):
|
62 |
+
continue
|
63 |
+
|
64 |
+
data_dict[name] = {'motion': motion,
|
65 |
+
'length': len(motion),
|
66 |
+
'name': name}
|
67 |
+
new_name_list.append(name)
|
68 |
+
length_list.append(len(motion))
|
69 |
+
except:
|
70 |
+
# Some motion may not exist in KIT dataset
|
71 |
+
pass
|
72 |
+
|
73 |
+
|
74 |
+
self.mean = mean
|
75 |
+
self.std = std
|
76 |
+
self.length_arr = np.array(length_list)
|
77 |
+
self.data_dict = data_dict
|
78 |
+
self.name_list = new_name_list
|
79 |
+
|
80 |
+
def inv_transform(self, data):
|
81 |
+
return data * self.std + self.mean
|
82 |
+
|
83 |
+
def __len__(self):
|
84 |
+
return len(self.data_dict)
|
85 |
+
|
86 |
+
def __getitem__(self, item):
|
87 |
+
name = self.name_list[item]
|
88 |
+
data = self.data_dict[name]
|
89 |
+
motion, m_length = data['motion'], data['length']
|
90 |
+
|
91 |
+
m_length = (m_length // self.unit_length) * self.unit_length
|
92 |
+
|
93 |
+
idx = random.randint(0, len(motion) - m_length)
|
94 |
+
motion = motion[idx:idx+m_length]
|
95 |
+
|
96 |
+
"Z Normalization"
|
97 |
+
motion = (motion - self.mean) / self.std
|
98 |
+
|
99 |
+
return motion, name
|
100 |
+
|
101 |
+
def DATALoader(dataset_name,
|
102 |
+
batch_size = 1,
|
103 |
+
num_workers = 8, unit_length = 4) :
|
104 |
+
|
105 |
+
train_loader = torch.utils.data.DataLoader(VQMotionDataset(dataset_name, unit_length=unit_length),
|
106 |
+
batch_size,
|
107 |
+
shuffle=True,
|
108 |
+
num_workers=num_workers,
|
109 |
+
#collate_fn=collate_fn,
|
110 |
+
drop_last = True)
|
111 |
+
|
112 |
+
return train_loader
|
113 |
+
|
114 |
+
def cycle(iterable):
|
115 |
+
while True:
|
116 |
+
for x in iterable:
|
117 |
+
yield x
|
generate_human_motion/VQTrans/dataset/prepare/download_extractor.sh
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
rm -rf checkpoints
|
2 |
+
mkdir checkpoints
|
3 |
+
cd checkpoints
|
4 |
+
echo -e "Downloading extractors"
|
5 |
+
gdown --fuzzy https://drive.google.com/file/d/1o7RTDQcToJjTm9_mNWTyzvZvjTWpZfug/view
|
6 |
+
gdown --fuzzy https://drive.google.com/file/d/1tX79xk0fflp07EZ660Xz1RAFE33iEyJR/view
|
7 |
+
|
8 |
+
|
9 |
+
unzip t2m.zip
|
10 |
+
unzip kit.zip
|
11 |
+
|
12 |
+
echo -e "Cleaning\n"
|
13 |
+
rm t2m.zip
|
14 |
+
rm kit.zip
|
15 |
+
echo -e "Downloading done!"
|
generate_human_motion/VQTrans/dataset/prepare/download_glove.sh
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
echo -e "Downloading glove (in use by the evaluators)"
|
2 |
+
gdown --fuzzy https://drive.google.com/file/d/1bCeS6Sh_mLVTebxIgiUHgdPrroW06mb6/view?usp=sharing
|
3 |
+
rm -rf glove
|
4 |
+
|
5 |
+
unzip glove.zip
|
6 |
+
echo -e "Cleaning\n"
|
7 |
+
rm glove.zip
|
8 |
+
|
9 |
+
echo -e "Downloading done!"
|
generate_human_motion/VQTrans/dataset/prepare/download_model.sh
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
mkdir -p pretrained
|
3 |
+
cd pretrained/
|
4 |
+
|
5 |
+
echo -e "The pretrained model files will be stored in the 'pretrained' folder\n"
|
6 |
+
gdown 1LaOvwypF-jM2Axnq5dc-Iuvv3w_G-WDE
|
7 |
+
|
8 |
+
unzip VQTrans_pretrained.zip
|
9 |
+
echo -e "Cleaning\n"
|
10 |
+
rm VQTrans_pretrained.zip
|
11 |
+
|
12 |
+
echo -e "Downloading done!"
|
generate_human_motion/VQTrans/dataset/prepare/download_smpl.sh
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
mkdir -p body_models
|
3 |
+
cd body_models/
|
4 |
+
|
5 |
+
echo -e "The smpl files will be stored in the 'body_models/smpl/' folder\n"
|
6 |
+
gdown 1INYlGA76ak_cKGzvpOV2Pe6RkYTlXTW2
|
7 |
+
rm -rf smpl
|
8 |
+
|
9 |
+
unzip smpl.zip
|
10 |
+
echo -e "Cleaning\n"
|
11 |
+
rm smpl.zip
|
12 |
+
|
13 |
+
echo -e "Downloading done!"
|
generate_human_motion/VQTrans/environment.yml
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: VQTrans
|
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
|
generate_human_motion/VQTrans/models/__init__.py
ADDED
File without changes
|
generate_human_motion/VQTrans/models/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (169 Bytes). View file
|
|
generate_human_motion/VQTrans/models/__pycache__/encdec.cpython-310.pyc
ADDED
Binary file (2.05 kB). View file
|
|
generate_human_motion/VQTrans/models/__pycache__/pos_encoding.cpython-310.pyc
ADDED
Binary file (1.78 kB). View file
|
|
generate_human_motion/VQTrans/models/__pycache__/quantize_cnn.cpython-310.pyc
ADDED
Binary file (9.31 kB). View file
|
|
generate_human_motion/VQTrans/models/__pycache__/resnet.cpython-310.pyc
ADDED
Binary file (2.81 kB). View file
|
|
generate_human_motion/VQTrans/models/__pycache__/rotation2xyz.cpython-310.pyc
ADDED
Binary file (2.4 kB). View file
|
|
generate_human_motion/VQTrans/models/__pycache__/smpl.cpython-310.pyc
ADDED
Binary file (3.45 kB). View file
|
|
generate_human_motion/VQTrans/models/__pycache__/t2m_trans.cpython-310.pyc
ADDED
Binary file (6.89 kB). View file
|
|
generate_human_motion/VQTrans/models/__pycache__/vqvae.cpython-310.pyc
ADDED
Binary file (3.54 kB). View file
|
|
generate_human_motion/VQTrans/models/encdec.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
from resnet import Resnet1D
|
3 |
+
|
4 |
+
class Encoder(nn.Module):
|
5 |
+
def __init__(self,
|
6 |
+
input_emb_width = 3,
|
7 |
+
output_emb_width = 512,
|
8 |
+
down_t = 3,
|
9 |
+
stride_t = 2,
|
10 |
+
width = 512,
|
11 |
+
depth = 3,
|
12 |
+
dilation_growth_rate = 3,
|
13 |
+
activation='relu',
|
14 |
+
norm=None):
|
15 |
+
super().__init__()
|
16 |
+
|
17 |
+
blocks = []
|
18 |
+
filter_t, pad_t = stride_t * 2, stride_t // 2
|
19 |
+
blocks.append(nn.Conv1d(input_emb_width, width, 3, 1, 1))
|
20 |
+
blocks.append(nn.ReLU())
|
21 |
+
|
22 |
+
for i in range(down_t):
|
23 |
+
input_dim = width
|
24 |
+
block = nn.Sequential(
|
25 |
+
nn.Conv1d(input_dim, width, filter_t, stride_t, pad_t),
|
26 |
+
Resnet1D(width, depth, dilation_growth_rate, activation=activation, norm=norm),
|
27 |
+
)
|
28 |
+
blocks.append(block)
|
29 |
+
blocks.append(nn.Conv1d(width, output_emb_width, 3, 1, 1))
|
30 |
+
self.model = nn.Sequential(*blocks)
|
31 |
+
|
32 |
+
def forward(self, x):
|
33 |
+
return self.model(x)
|
34 |
+
|
35 |
+
class Decoder(nn.Module):
|
36 |
+
def __init__(self,
|
37 |
+
input_emb_width = 3,
|
38 |
+
output_emb_width = 512,
|
39 |
+
down_t = 3,
|
40 |
+
stride_t = 2,
|
41 |
+
width = 512,
|
42 |
+
depth = 3,
|
43 |
+
dilation_growth_rate = 3,
|
44 |
+
activation='relu',
|
45 |
+
norm=None):
|
46 |
+
super().__init__()
|
47 |
+
blocks = []
|
48 |
+
|
49 |
+
filter_t, pad_t = stride_t * 2, stride_t // 2
|
50 |
+
blocks.append(nn.Conv1d(output_emb_width, width, 3, 1, 1))
|
51 |
+
blocks.append(nn.ReLU())
|
52 |
+
for i in range(down_t):
|
53 |
+
out_dim = width
|
54 |
+
block = nn.Sequential(
|
55 |
+
Resnet1D(width, depth, dilation_growth_rate, reverse_dilation=True, activation=activation, norm=norm),
|
56 |
+
nn.Upsample(scale_factor=2, mode='nearest'),
|
57 |
+
nn.Conv1d(width, out_dim, 3, 1, 1)
|
58 |
+
)
|
59 |
+
blocks.append(block)
|
60 |
+
blocks.append(nn.Conv1d(width, width, 3, 1, 1))
|
61 |
+
blocks.append(nn.ReLU())
|
62 |
+
blocks.append(nn.Conv1d(width, input_emb_width, 3, 1, 1))
|
63 |
+
self.model = nn.Sequential(*blocks)
|
64 |
+
|
65 |
+
def forward(self, x):
|
66 |
+
return self.model(x)
|
67 |
+
|
generate_human_motion/VQTrans/models/evaluator_wrapper.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import torch
|
3 |
+
from os.path import join as pjoin
|
4 |
+
import numpy as np
|
5 |
+
from models.modules import MovementConvEncoder, TextEncoderBiGRUCo, MotionEncoderBiGRUCo
|
6 |
+
from utils.word_vectorizer import POS_enumerator
|
7 |
+
|
8 |
+
def build_models(opt):
|
9 |
+
movement_enc = MovementConvEncoder(opt.dim_pose-4, opt.dim_movement_enc_hidden, opt.dim_movement_latent)
|
10 |
+
text_enc = TextEncoderBiGRUCo(word_size=opt.dim_word,
|
11 |
+
pos_size=opt.dim_pos_ohot,
|
12 |
+
hidden_size=opt.dim_text_hidden,
|
13 |
+
output_size=opt.dim_coemb_hidden,
|
14 |
+
device=opt.device)
|
15 |
+
|
16 |
+
motion_enc = MotionEncoderBiGRUCo(input_size=opt.dim_movement_latent,
|
17 |
+
hidden_size=opt.dim_motion_hidden,
|
18 |
+
output_size=opt.dim_coemb_hidden,
|
19 |
+
device=opt.device)
|
20 |
+
|
21 |
+
checkpoint = torch.load(pjoin(opt.checkpoints_dir, opt.dataset_name, 'text_mot_match', 'model', 'finest.tar'),
|
22 |
+
map_location=opt.device)
|
23 |
+
movement_enc.load_state_dict(checkpoint['movement_encoder'])
|
24 |
+
text_enc.load_state_dict(checkpoint['text_encoder'])
|
25 |
+
motion_enc.load_state_dict(checkpoint['motion_encoder'])
|
26 |
+
print('Loading Evaluation Model Wrapper (Epoch %d) Completed!!' % (checkpoint['epoch']))
|
27 |
+
return text_enc, motion_enc, movement_enc
|
28 |
+
|
29 |
+
|
30 |
+
class EvaluatorModelWrapper(object):
|
31 |
+
|
32 |
+
def __init__(self, opt):
|
33 |
+
|
34 |
+
if opt.dataset_name == 't2m':
|
35 |
+
opt.dim_pose = 263
|
36 |
+
elif opt.dataset_name == 'kit':
|
37 |
+
opt.dim_pose = 251
|
38 |
+
else:
|
39 |
+
raise KeyError('Dataset not Recognized!!!')
|
40 |
+
|
41 |
+
opt.dim_word = 300
|
42 |
+
opt.max_motion_length = 196
|
43 |
+
opt.dim_pos_ohot = len(POS_enumerator)
|
44 |
+
opt.dim_motion_hidden = 1024
|
45 |
+
opt.max_text_len = 20
|
46 |
+
opt.dim_text_hidden = 512
|
47 |
+
opt.dim_coemb_hidden = 512
|
48 |
+
|
49 |
+
# print(opt)
|
50 |
+
|
51 |
+
self.text_encoder, self.motion_encoder, self.movement_encoder = build_models(opt)
|
52 |
+
self.opt = opt
|
53 |
+
self.device = opt.device
|
54 |
+
|
55 |
+
self.text_encoder.to(opt.device)
|
56 |
+
self.motion_encoder.to(opt.device)
|
57 |
+
self.movement_encoder.to(opt.device)
|
58 |
+
|
59 |
+
self.text_encoder.eval()
|
60 |
+
self.motion_encoder.eval()
|
61 |
+
self.movement_encoder.eval()
|
62 |
+
|
63 |
+
# Please note that the results does not following the order of inputs
|
64 |
+
def get_co_embeddings(self, word_embs, pos_ohot, cap_lens, motions, m_lens):
|
65 |
+
with torch.no_grad():
|
66 |
+
word_embs = word_embs.detach().to(self.device).float()
|
67 |
+
pos_ohot = pos_ohot.detach().to(self.device).float()
|
68 |
+
motions = motions.detach().to(self.device).float()
|
69 |
+
|
70 |
+
'''Movement Encoding'''
|
71 |
+
movements = self.movement_encoder(motions[..., :-4]).detach()
|
72 |
+
m_lens = m_lens // self.opt.unit_length
|
73 |
+
motion_embedding = self.motion_encoder(movements, m_lens)
|
74 |
+
|
75 |
+
'''Text Encoding'''
|
76 |
+
text_embedding = self.text_encoder(word_embs, pos_ohot, cap_lens)
|
77 |
+
return text_embedding, motion_embedding
|
78 |
+
|
79 |
+
# Please note that the results does not following the order of inputs
|
80 |
+
def get_motion_embeddings(self, motions, m_lens):
|
81 |
+
with torch.no_grad():
|
82 |
+
motions = motions.detach().to(self.device).float()
|
83 |
+
|
84 |
+
align_idx = np.argsort(m_lens.data.tolist())[::-1].copy()
|
85 |
+
motions = motions[align_idx]
|
86 |
+
m_lens = m_lens[align_idx]
|
87 |
+
|
88 |
+
'''Movement Encoding'''
|
89 |
+
movements = self.movement_encoder(motions[..., :-4]).detach()
|
90 |
+
m_lens = m_lens // self.opt.unit_length
|
91 |
+
motion_embedding = self.motion_encoder(movements, m_lens)
|
92 |
+
return motion_embedding
|
generate_human_motion/VQTrans/models/modules.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from torch.nn.utils.rnn import pack_padded_sequence
|
4 |
+
|
5 |
+
def init_weight(m):
|
6 |
+
if isinstance(m, nn.Conv1d) or isinstance(m, nn.Linear) or isinstance(m, nn.ConvTranspose1d):
|
7 |
+
nn.init.xavier_normal_(m.weight)
|
8 |
+
# m.bias.data.fill_(0.01)
|
9 |
+
if m.bias is not None:
|
10 |
+
nn.init.constant_(m.bias, 0)
|
11 |
+
|
12 |
+
|
13 |
+
class MovementConvEncoder(nn.Module):
|
14 |
+
def __init__(self, input_size, hidden_size, output_size):
|
15 |
+
super(MovementConvEncoder, self).__init__()
|
16 |
+
self.main = nn.Sequential(
|
17 |
+
nn.Conv1d(input_size, hidden_size, 4, 2, 1),
|
18 |
+
nn.Dropout(0.2, inplace=True),
|
19 |
+
nn.LeakyReLU(0.2, inplace=True),
|
20 |
+
nn.Conv1d(hidden_size, output_size, 4, 2, 1),
|
21 |
+
nn.Dropout(0.2, inplace=True),
|
22 |
+
nn.LeakyReLU(0.2, inplace=True),
|
23 |
+
)
|
24 |
+
self.out_net = nn.Linear(output_size, output_size)
|
25 |
+
self.main.apply(init_weight)
|
26 |
+
self.out_net.apply(init_weight)
|
27 |
+
|
28 |
+
def forward(self, inputs):
|
29 |
+
inputs = inputs.permute(0, 2, 1)
|
30 |
+
outputs = self.main(inputs).permute(0, 2, 1)
|
31 |
+
# print(outputs.shape)
|
32 |
+
return self.out_net(outputs)
|
33 |
+
|
34 |
+
|
35 |
+
|
36 |
+
class TextEncoderBiGRUCo(nn.Module):
|
37 |
+
def __init__(self, word_size, pos_size, hidden_size, output_size, device):
|
38 |
+
super(TextEncoderBiGRUCo, self).__init__()
|
39 |
+
self.device = device
|
40 |
+
|
41 |
+
self.pos_emb = nn.Linear(pos_size, word_size)
|
42 |
+
self.input_emb = nn.Linear(word_size, hidden_size)
|
43 |
+
self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True, bidirectional=True)
|
44 |
+
self.output_net = nn.Sequential(
|
45 |
+
nn.Linear(hidden_size * 2, hidden_size),
|
46 |
+
nn.LayerNorm(hidden_size),
|
47 |
+
nn.LeakyReLU(0.2, inplace=True),
|
48 |
+
nn.Linear(hidden_size, output_size)
|
49 |
+
)
|
50 |
+
|
51 |
+
self.input_emb.apply(init_weight)
|
52 |
+
self.pos_emb.apply(init_weight)
|
53 |
+
self.output_net.apply(init_weight)
|
54 |
+
self.hidden_size = hidden_size
|
55 |
+
self.hidden = nn.Parameter(torch.randn((2, 1, self.hidden_size), requires_grad=True))
|
56 |
+
|
57 |
+
# input(batch_size, seq_len, dim)
|
58 |
+
def forward(self, word_embs, pos_onehot, cap_lens):
|
59 |
+
num_samples = word_embs.shape[0]
|
60 |
+
|
61 |
+
pos_embs = self.pos_emb(pos_onehot)
|
62 |
+
inputs = word_embs + pos_embs
|
63 |
+
input_embs = self.input_emb(inputs)
|
64 |
+
hidden = self.hidden.repeat(1, num_samples, 1)
|
65 |
+
|
66 |
+
cap_lens = cap_lens.data.tolist()
|
67 |
+
emb = pack_padded_sequence(input_embs, cap_lens, batch_first=True)
|
68 |
+
|
69 |
+
gru_seq, gru_last = self.gru(emb, hidden)
|
70 |
+
|
71 |
+
gru_last = torch.cat([gru_last[0], gru_last[1]], dim=-1)
|
72 |
+
|
73 |
+
return self.output_net(gru_last)
|
74 |
+
|
75 |
+
|
76 |
+
class MotionEncoderBiGRUCo(nn.Module):
|
77 |
+
def __init__(self, input_size, hidden_size, output_size, device):
|
78 |
+
super(MotionEncoderBiGRUCo, self).__init__()
|
79 |
+
self.device = device
|
80 |
+
|
81 |
+
self.input_emb = nn.Linear(input_size, hidden_size)
|
82 |
+
self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True, bidirectional=True)
|
83 |
+
self.output_net = nn.Sequential(
|
84 |
+
nn.Linear(hidden_size*2, hidden_size),
|
85 |
+
nn.LayerNorm(hidden_size),
|
86 |
+
nn.LeakyReLU(0.2, inplace=True),
|
87 |
+
nn.Linear(hidden_size, output_size)
|
88 |
+
)
|
89 |
+
|
90 |
+
self.input_emb.apply(init_weight)
|
91 |
+
self.output_net.apply(init_weight)
|
92 |
+
self.hidden_size = hidden_size
|
93 |
+
self.hidden = nn.Parameter(torch.randn((2, 1, self.hidden_size), requires_grad=True))
|
94 |
+
|
95 |
+
# input(batch_size, seq_len, dim)
|
96 |
+
def forward(self, inputs, m_lens):
|
97 |
+
num_samples = inputs.shape[0]
|
98 |
+
|
99 |
+
input_embs = self.input_emb(inputs)
|
100 |
+
hidden = self.hidden.repeat(1, num_samples, 1)
|
101 |
+
|
102 |
+
cap_lens = m_lens.data.tolist()
|
103 |
+
emb = pack_padded_sequence(input_embs, cap_lens, batch_first=True, enforce_sorted=False)
|
104 |
+
|
105 |
+
gru_seq, gru_last = self.gru(emb, hidden)
|
106 |
+
|
107 |
+
gru_last = torch.cat([gru_last[0], gru_last[1]], dim=-1)
|
108 |
+
|
109 |
+
return self.output_net(gru_last)
|
generate_human_motion/VQTrans/models/pos_encoding.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Various positional encodings for the transformer.
|
3 |
+
"""
|
4 |
+
import math
|
5 |
+
import torch
|
6 |
+
from torch import nn
|
7 |
+
|
8 |
+
def PE1d_sincos(seq_length, dim):
|
9 |
+
"""
|
10 |
+
:param d_model: dimension of the model
|
11 |
+
:param length: length of positions
|
12 |
+
:return: length*d_model position matrix
|
13 |
+
"""
|
14 |
+
if dim % 2 != 0:
|
15 |
+
raise ValueError("Cannot use sin/cos positional encoding with "
|
16 |
+
"odd dim (got dim={:d})".format(dim))
|
17 |
+
pe = torch.zeros(seq_length, dim)
|
18 |
+
position = torch.arange(0, seq_length).unsqueeze(1)
|
19 |
+
div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) *
|
20 |
+
-(math.log(10000.0) / dim)))
|
21 |
+
pe[:, 0::2] = torch.sin(position.float() * div_term)
|
22 |
+
pe[:, 1::2] = torch.cos(position.float() * div_term)
|
23 |
+
|
24 |
+
return pe.unsqueeze(1)
|
25 |
+
|
26 |
+
|
27 |
+
class PositionEmbedding(nn.Module):
|
28 |
+
"""
|
29 |
+
Absolute pos embedding (standard), learned.
|
30 |
+
"""
|
31 |
+
def __init__(self, seq_length, dim, dropout, grad=False):
|
32 |
+
super().__init__()
|
33 |
+
self.embed = nn.Parameter(data=PE1d_sincos(seq_length, dim), requires_grad=grad)
|
34 |
+
self.dropout = nn.Dropout(p=dropout)
|
35 |
+
|
36 |
+
def forward(self, x):
|
37 |
+
# x.shape: bs, seq_len, feat_dim
|
38 |
+
l = x.shape[1]
|
39 |
+
x = x.permute(1, 0, 2) + self.embed[:l].expand(x.permute(1, 0, 2).shape)
|
40 |
+
x = self.dropout(x.permute(1, 0, 2))
|
41 |
+
return x
|
42 |
+
|
43 |
+
|
generate_human_motion/VQTrans/models/quantize_cnn.py
ADDED
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torch.nn.functional as F
|
5 |
+
|
6 |
+
class QuantizeEMAReset(nn.Module):
|
7 |
+
def __init__(self, nb_code, code_dim, args):
|
8 |
+
super().__init__()
|
9 |
+
self.nb_code = nb_code
|
10 |
+
self.code_dim = code_dim
|
11 |
+
self.mu = args.mu
|
12 |
+
self.reset_codebook()
|
13 |
+
|
14 |
+
def reset_codebook(self):
|
15 |
+
self.init = False
|
16 |
+
self.code_sum = None
|
17 |
+
self.code_count = None
|
18 |
+
if torch.cuda.is_available():
|
19 |
+
self.register_buffer('codebook', torch.zeros(self.nb_code, self.code_dim).cuda())
|
20 |
+
else:
|
21 |
+
self.register_buffer('codebook', torch.zeros(self.nb_code, self.code_dim))
|
22 |
+
|
23 |
+
def _tile(self, x):
|
24 |
+
nb_code_x, code_dim = x.shape
|
25 |
+
if nb_code_x < self.nb_code:
|
26 |
+
n_repeats = (self.nb_code + nb_code_x - 1) // nb_code_x
|
27 |
+
std = 0.01 / np.sqrt(code_dim)
|
28 |
+
out = x.repeat(n_repeats, 1)
|
29 |
+
out = out + torch.randn_like(out) * std
|
30 |
+
else :
|
31 |
+
out = x
|
32 |
+
return out
|
33 |
+
|
34 |
+
def init_codebook(self, x):
|
35 |
+
out = self._tile(x)
|
36 |
+
self.codebook = out[:self.nb_code]
|
37 |
+
self.code_sum = self.codebook.clone()
|
38 |
+
self.code_count = torch.ones(self.nb_code, device=self.codebook.device)
|
39 |
+
self.init = True
|
40 |
+
|
41 |
+
@torch.no_grad()
|
42 |
+
def compute_perplexity(self, code_idx) :
|
43 |
+
# Calculate new centres
|
44 |
+
code_onehot = torch.zeros(self.nb_code, code_idx.shape[0], device=code_idx.device) # nb_code, N * L
|
45 |
+
code_onehot.scatter_(0, code_idx.view(1, code_idx.shape[0]), 1)
|
46 |
+
|
47 |
+
code_count = code_onehot.sum(dim=-1) # nb_code
|
48 |
+
prob = code_count / torch.sum(code_count)
|
49 |
+
perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
|
50 |
+
return perplexity
|
51 |
+
|
52 |
+
@torch.no_grad()
|
53 |
+
def update_codebook(self, x, code_idx):
|
54 |
+
|
55 |
+
code_onehot = torch.zeros(self.nb_code, x.shape[0], device=x.device) # nb_code, N * L
|
56 |
+
code_onehot.scatter_(0, code_idx.view(1, x.shape[0]), 1)
|
57 |
+
|
58 |
+
code_sum = torch.matmul(code_onehot, x) # nb_code, w
|
59 |
+
code_count = code_onehot.sum(dim=-1) # nb_code
|
60 |
+
|
61 |
+
out = self._tile(x)
|
62 |
+
code_rand = out[:self.nb_code]
|
63 |
+
|
64 |
+
# Update centres
|
65 |
+
self.code_sum = self.mu * self.code_sum + (1. - self.mu) * code_sum # w, nb_code
|
66 |
+
self.code_count = self.mu * self.code_count + (1. - self.mu) * code_count # nb_code
|
67 |
+
|
68 |
+
usage = (self.code_count.view(self.nb_code, 1) >= 1.0).float()
|
69 |
+
code_update = self.code_sum.view(self.nb_code, self.code_dim) / self.code_count.view(self.nb_code, 1)
|
70 |
+
|
71 |
+
self.codebook = usage * code_update + (1 - usage) * code_rand
|
72 |
+
prob = code_count / torch.sum(code_count)
|
73 |
+
perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
|
74 |
+
|
75 |
+
|
76 |
+
return perplexity
|
77 |
+
|
78 |
+
def preprocess(self, x):
|
79 |
+
# NCT -> NTC -> [NT, C]
|
80 |
+
x = x.permute(0, 2, 1).contiguous()
|
81 |
+
x = x.view(-1, x.shape[-1])
|
82 |
+
return x
|
83 |
+
|
84 |
+
def quantize(self, x):
|
85 |
+
# Calculate latent code x_l
|
86 |
+
k_w = self.codebook.t()
|
87 |
+
distance = torch.sum(x ** 2, dim=-1, keepdim=True) - 2 * torch.matmul(x, k_w) + torch.sum(k_w ** 2, dim=0,
|
88 |
+
keepdim=True) # (N * L, b)
|
89 |
+
_, code_idx = torch.min(distance, dim=-1)
|
90 |
+
return code_idx
|
91 |
+
|
92 |
+
def dequantize(self, code_idx):
|
93 |
+
x = F.embedding(code_idx, self.codebook)
|
94 |
+
return x
|
95 |
+
|
96 |
+
|
97 |
+
def forward(self, x):
|
98 |
+
N, width, T = x.shape
|
99 |
+
|
100 |
+
# Preprocess
|
101 |
+
x = self.preprocess(x)
|
102 |
+
|
103 |
+
# Init codebook if not inited
|
104 |
+
if self.training and not self.init:
|
105 |
+
self.init_codebook(x)
|
106 |
+
|
107 |
+
# quantize and dequantize through bottleneck
|
108 |
+
code_idx = self.quantize(x)
|
109 |
+
x_d = self.dequantize(code_idx)
|
110 |
+
|
111 |
+
# Update embeddings
|
112 |
+
if self.training:
|
113 |
+
perplexity = self.update_codebook(x, code_idx)
|
114 |
+
else :
|
115 |
+
perplexity = self.compute_perplexity(code_idx)
|
116 |
+
|
117 |
+
# Loss
|
118 |
+
commit_loss = F.mse_loss(x, x_d.detach())
|
119 |
+
|
120 |
+
# Passthrough
|
121 |
+
x_d = x + (x_d - x).detach()
|
122 |
+
|
123 |
+
# Postprocess
|
124 |
+
x_d = x_d.view(N, T, -1).permute(0, 2, 1).contiguous() #(N, DIM, T)
|
125 |
+
|
126 |
+
return x_d, commit_loss, perplexity
|
127 |
+
|
128 |
+
|
129 |
+
|
130 |
+
class Quantizer(nn.Module):
|
131 |
+
def __init__(self, n_e, e_dim, beta):
|
132 |
+
super(Quantizer, self).__init__()
|
133 |
+
|
134 |
+
self.e_dim = e_dim
|
135 |
+
self.n_e = n_e
|
136 |
+
self.beta = beta
|
137 |
+
|
138 |
+
self.embedding = nn.Embedding(self.n_e, self.e_dim)
|
139 |
+
self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)
|
140 |
+
|
141 |
+
def forward(self, z):
|
142 |
+
|
143 |
+
N, width, T = z.shape
|
144 |
+
z = self.preprocess(z)
|
145 |
+
assert z.shape[-1] == self.e_dim
|
146 |
+
z_flattened = z.contiguous().view(-1, self.e_dim)
|
147 |
+
|
148 |
+
# B x V
|
149 |
+
d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
|
150 |
+
torch.sum(self.embedding.weight**2, dim=1) - 2 * \
|
151 |
+
torch.matmul(z_flattened, self.embedding.weight.t())
|
152 |
+
# B x 1
|
153 |
+
min_encoding_indices = torch.argmin(d, dim=1)
|
154 |
+
z_q = self.embedding(min_encoding_indices).view(z.shape)
|
155 |
+
|
156 |
+
# compute loss for embedding
|
157 |
+
loss = torch.mean((z_q - z.detach())**2) + self.beta * \
|
158 |
+
torch.mean((z_q.detach() - z)**2)
|
159 |
+
|
160 |
+
# preserve gradients
|
161 |
+
z_q = z + (z_q - z).detach()
|
162 |
+
z_q = z_q.view(N, T, -1).permute(0, 2, 1).contiguous() #(N, DIM, T)
|
163 |
+
|
164 |
+
min_encodings = F.one_hot(min_encoding_indices, self.n_e).type(z.dtype)
|
165 |
+
e_mean = torch.mean(min_encodings, dim=0)
|
166 |
+
perplexity = torch.exp(-torch.sum(e_mean*torch.log(e_mean + 1e-10)))
|
167 |
+
return z_q, loss, perplexity
|
168 |
+
|
169 |
+
def quantize(self, z):
|
170 |
+
|
171 |
+
assert z.shape[-1] == self.e_dim
|
172 |
+
|
173 |
+
# B x V
|
174 |
+
d = torch.sum(z ** 2, dim=1, keepdim=True) + \
|
175 |
+
torch.sum(self.embedding.weight ** 2, dim=1) - 2 * \
|
176 |
+
torch.matmul(z, self.embedding.weight.t())
|
177 |
+
# B x 1
|
178 |
+
min_encoding_indices = torch.argmin(d, dim=1)
|
179 |
+
return min_encoding_indices
|
180 |
+
|
181 |
+
def dequantize(self, indices):
|
182 |
+
|
183 |
+
index_flattened = indices.view(-1)
|
184 |
+
z_q = self.embedding(index_flattened)
|
185 |
+
z_q = z_q.view(indices.shape + (self.e_dim, )).contiguous()
|
186 |
+
return z_q
|
187 |
+
|
188 |
+
def preprocess(self, x):
|
189 |
+
# NCT -> NTC -> [NT, C]
|
190 |
+
x = x.permute(0, 2, 1).contiguous()
|
191 |
+
x = x.view(-1, x.shape[-1])
|
192 |
+
return x
|
193 |
+
|
194 |
+
|
195 |
+
|
196 |
+
class QuantizeReset(nn.Module):
|
197 |
+
def __init__(self, nb_code, code_dim, args):
|
198 |
+
super().__init__()
|
199 |
+
self.nb_code = nb_code
|
200 |
+
self.code_dim = code_dim
|
201 |
+
self.reset_codebook()
|
202 |
+
self.codebook = nn.Parameter(torch.randn(nb_code, code_dim))
|
203 |
+
|
204 |
+
def reset_codebook(self):
|
205 |
+
self.init = False
|
206 |
+
self.code_count = None
|
207 |
+
|
208 |
+
def _tile(self, x):
|
209 |
+
nb_code_x, code_dim = x.shape
|
210 |
+
if nb_code_x < self.nb_code:
|
211 |
+
n_repeats = (self.nb_code + nb_code_x - 1) // nb_code_x
|
212 |
+
std = 0.01 / np.sqrt(code_dim)
|
213 |
+
out = x.repeat(n_repeats, 1)
|
214 |
+
out = out + torch.randn_like(out) * std
|
215 |
+
else :
|
216 |
+
out = x
|
217 |
+
return out
|
218 |
+
|
219 |
+
def init_codebook(self, x):
|
220 |
+
out = self._tile(x)
|
221 |
+
self.codebook = nn.Parameter(out[:self.nb_code])
|
222 |
+
self.code_count = torch.ones(self.nb_code, device=self.codebook.device)
|
223 |
+
self.init = True
|
224 |
+
|
225 |
+
@torch.no_grad()
|
226 |
+
def compute_perplexity(self, code_idx) :
|
227 |
+
# Calculate new centres
|
228 |
+
code_onehot = torch.zeros(self.nb_code, code_idx.shape[0], device=code_idx.device) # nb_code, N * L
|
229 |
+
code_onehot.scatter_(0, code_idx.view(1, code_idx.shape[0]), 1)
|
230 |
+
|
231 |
+
code_count = code_onehot.sum(dim=-1) # nb_code
|
232 |
+
prob = code_count / torch.sum(code_count)
|
233 |
+
perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
|
234 |
+
return perplexity
|
235 |
+
|
236 |
+
def update_codebook(self, x, code_idx):
|
237 |
+
|
238 |
+
code_onehot = torch.zeros(self.nb_code, x.shape[0], device=x.device) # nb_code, N * L
|
239 |
+
code_onehot.scatter_(0, code_idx.view(1, x.shape[0]), 1)
|
240 |
+
|
241 |
+
code_count = code_onehot.sum(dim=-1) # nb_code
|
242 |
+
|
243 |
+
out = self._tile(x)
|
244 |
+
code_rand = out[:self.nb_code]
|
245 |
+
|
246 |
+
# Update centres
|
247 |
+
self.code_count = code_count # nb_code
|
248 |
+
usage = (self.code_count.view(self.nb_code, 1) >= 1.0).float()
|
249 |
+
|
250 |
+
self.codebook.data = usage * self.codebook.data + (1 - usage) * code_rand
|
251 |
+
prob = code_count / torch.sum(code_count)
|
252 |
+
perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
|
253 |
+
|
254 |
+
|
255 |
+
return perplexity
|
256 |
+
|
257 |
+
def preprocess(self, x):
|
258 |
+
# NCT -> NTC -> [NT, C]
|
259 |
+
x = x.permute(0, 2, 1).contiguous()
|
260 |
+
x = x.view(-1, x.shape[-1])
|
261 |
+
return x
|
262 |
+
|
263 |
+
def quantize(self, x):
|
264 |
+
# Calculate latent code x_l
|
265 |
+
k_w = self.codebook.t()
|
266 |
+
distance = torch.sum(x ** 2, dim=-1, keepdim=True) - 2 * torch.matmul(x, k_w) + torch.sum(k_w ** 2, dim=0,
|
267 |
+
keepdim=True) # (N * L, b)
|
268 |
+
_, code_idx = torch.min(distance, dim=-1)
|
269 |
+
return code_idx
|
270 |
+
|
271 |
+
def dequantize(self, code_idx):
|
272 |
+
x = F.embedding(code_idx, self.codebook)
|
273 |
+
return x
|
274 |
+
|
275 |
+
|
276 |
+
def forward(self, x):
|
277 |
+
N, width, T = x.shape
|
278 |
+
# Preprocess
|
279 |
+
x = self.preprocess(x)
|
280 |
+
# Init codebook if not inited
|
281 |
+
if self.training and not self.init:
|
282 |
+
self.init_codebook(x)
|
283 |
+
# quantize and dequantize through bottleneck
|
284 |
+
code_idx = self.quantize(x)
|
285 |
+
x_d = self.dequantize(code_idx)
|
286 |
+
# Update embeddings
|
287 |
+
if self.training:
|
288 |
+
perplexity = self.update_codebook(x, code_idx)
|
289 |
+
else :
|
290 |
+
perplexity = self.compute_perplexity(code_idx)
|
291 |
+
|
292 |
+
# Loss
|
293 |
+
commit_loss = F.mse_loss(x, x_d.detach())
|
294 |
+
|
295 |
+
# Passthrough
|
296 |
+
x_d = x + (x_d - x).detach()
|
297 |
+
|
298 |
+
# Postprocess
|
299 |
+
x_d = x_d.view(N, T, -1).permute(0, 2, 1).contiguous() #(N, DIM, T)
|
300 |
+
|
301 |
+
return x_d, commit_loss, perplexity
|
302 |
+
|
303 |
+
class QuantizeEMA(nn.Module):
|
304 |
+
def __init__(self, nb_code, code_dim, args):
|
305 |
+
super().__init__()
|
306 |
+
self.nb_code = nb_code
|
307 |
+
self.code_dim = code_dim
|
308 |
+
self.mu = 0.99
|
309 |
+
self.reset_codebook()
|
310 |
+
|
311 |
+
def reset_codebook(self):
|
312 |
+
self.init = False
|
313 |
+
self.code_sum = None
|
314 |
+
self.code_count = None
|
315 |
+
self.register_buffer('codebook', torch.zeros(self.nb_code, self.code_dim).cuda())
|
316 |
+
|
317 |
+
def _tile(self, x):
|
318 |
+
nb_code_x, code_dim = x.shape
|
319 |
+
if nb_code_x < self.nb_code:
|
320 |
+
n_repeats = (self.nb_code + nb_code_x - 1) // nb_code_x
|
321 |
+
std = 0.01 / np.sqrt(code_dim)
|
322 |
+
out = x.repeat(n_repeats, 1)
|
323 |
+
out = out + torch.randn_like(out) * std
|
324 |
+
else :
|
325 |
+
out = x
|
326 |
+
return out
|
327 |
+
|
328 |
+
def init_codebook(self, x):
|
329 |
+
out = self._tile(x)
|
330 |
+
self.codebook = out[:self.nb_code]
|
331 |
+
self.code_sum = self.codebook.clone()
|
332 |
+
self.code_count = torch.ones(self.nb_code, device=self.codebook.device)
|
333 |
+
self.init = True
|
334 |
+
|
335 |
+
@torch.no_grad()
|
336 |
+
def compute_perplexity(self, code_idx) :
|
337 |
+
# Calculate new centres
|
338 |
+
code_onehot = torch.zeros(self.nb_code, code_idx.shape[0], device=code_idx.device) # nb_code, N * L
|
339 |
+
code_onehot.scatter_(0, code_idx.view(1, code_idx.shape[0]), 1)
|
340 |
+
|
341 |
+
code_count = code_onehot.sum(dim=-1) # nb_code
|
342 |
+
prob = code_count / torch.sum(code_count)
|
343 |
+
perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
|
344 |
+
return perplexity
|
345 |
+
|
346 |
+
@torch.no_grad()
|
347 |
+
def update_codebook(self, x, code_idx):
|
348 |
+
|
349 |
+
code_onehot = torch.zeros(self.nb_code, x.shape[0], device=x.device) # nb_code, N * L
|
350 |
+
code_onehot.scatter_(0, code_idx.view(1, x.shape[0]), 1)
|
351 |
+
|
352 |
+
code_sum = torch.matmul(code_onehot, x) # nb_code, w
|
353 |
+
code_count = code_onehot.sum(dim=-1) # nb_code
|
354 |
+
|
355 |
+
# Update centres
|
356 |
+
self.code_sum = self.mu * self.code_sum + (1. - self.mu) * code_sum # w, nb_code
|
357 |
+
self.code_count = self.mu * self.code_count + (1. - self.mu) * code_count # nb_code
|
358 |
+
|
359 |
+
code_update = self.code_sum.view(self.nb_code, self.code_dim) / self.code_count.view(self.nb_code, 1)
|
360 |
+
|
361 |
+
self.codebook = code_update
|
362 |
+
prob = code_count / torch.sum(code_count)
|
363 |
+
perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
|
364 |
+
|
365 |
+
return perplexity
|
366 |
+
|
367 |
+
def preprocess(self, x):
|
368 |
+
# NCT -> NTC -> [NT, C]
|
369 |
+
x = x.permute(0, 2, 1).contiguous()
|
370 |
+
x = x.view(-1, x.shape[-1])
|
371 |
+
return x
|
372 |
+
|
373 |
+
def quantize(self, x):
|
374 |
+
# Calculate latent code x_l
|
375 |
+
k_w = self.codebook.t()
|
376 |
+
distance = torch.sum(x ** 2, dim=-1, keepdim=True) - 2 * torch.matmul(x, k_w) + torch.sum(k_w ** 2, dim=0,
|
377 |
+
keepdim=True) # (N * L, b)
|
378 |
+
_, code_idx = torch.min(distance, dim=-1)
|
379 |
+
return code_idx
|
380 |
+
|
381 |
+
def dequantize(self, code_idx):
|
382 |
+
x = F.embedding(code_idx, self.codebook)
|
383 |
+
return x
|
384 |
+
|
385 |
+
|
386 |
+
def forward(self, x):
|
387 |
+
N, width, T = x.shape
|
388 |
+
|
389 |
+
# Preprocess
|
390 |
+
x = self.preprocess(x)
|
391 |
+
|
392 |
+
# Init codebook if not inited
|
393 |
+
if self.training and not self.init:
|
394 |
+
self.init_codebook(x)
|
395 |
+
|
396 |
+
# quantize and dequantize through bottleneck
|
397 |
+
code_idx = self.quantize(x)
|
398 |
+
x_d = self.dequantize(code_idx)
|
399 |
+
|
400 |
+
# Update embeddings
|
401 |
+
if self.training:
|
402 |
+
perplexity = self.update_codebook(x, code_idx)
|
403 |
+
else :
|
404 |
+
perplexity = self.compute_perplexity(code_idx)
|
405 |
+
|
406 |
+
# Loss
|
407 |
+
commit_loss = F.mse_loss(x, x_d.detach())
|
408 |
+
|
409 |
+
# Passthrough
|
410 |
+
x_d = x + (x_d - x).detach()
|
411 |
+
|
412 |
+
# Postprocess
|
413 |
+
x_d = x_d.view(N, T, -1).permute(0, 2, 1).contiguous() #(N, DIM, T)
|
414 |
+
|
415 |
+
return x_d, commit_loss, perplexity
|
generate_human_motion/VQTrans/models/resnet.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
import torch
|
3 |
+
|
4 |
+
class nonlinearity(nn.Module):
|
5 |
+
def __init__(self):
|
6 |
+
super().__init__()
|
7 |
+
|
8 |
+
def forward(self, x):
|
9 |
+
# swish
|
10 |
+
return x * torch.sigmoid(x)
|
11 |
+
|
12 |
+
class ResConv1DBlock(nn.Module):
|
13 |
+
def __init__(self, n_in, n_state, dilation=1, activation='silu', norm=None, dropout=None):
|
14 |
+
super().__init__()
|
15 |
+
padding = dilation
|
16 |
+
self.norm = norm
|
17 |
+
if norm == "LN":
|
18 |
+
self.norm1 = nn.LayerNorm(n_in)
|
19 |
+
self.norm2 = nn.LayerNorm(n_in)
|
20 |
+
elif norm == "GN":
|
21 |
+
self.norm1 = nn.GroupNorm(num_groups=32, num_channels=n_in, eps=1e-6, affine=True)
|
22 |
+
self.norm2 = nn.GroupNorm(num_groups=32, num_channels=n_in, eps=1e-6, affine=True)
|
23 |
+
elif norm == "BN":
|
24 |
+
self.norm1 = nn.BatchNorm1d(num_features=n_in, eps=1e-6, affine=True)
|
25 |
+
self.norm2 = nn.BatchNorm1d(num_features=n_in, eps=1e-6, affine=True)
|
26 |
+
|
27 |
+
else:
|
28 |
+
self.norm1 = nn.Identity()
|
29 |
+
self.norm2 = nn.Identity()
|
30 |
+
|
31 |
+
if activation == "relu":
|
32 |
+
self.activation1 = nn.ReLU()
|
33 |
+
self.activation2 = nn.ReLU()
|
34 |
+
|
35 |
+
elif activation == "silu":
|
36 |
+
self.activation1 = nonlinearity()
|
37 |
+
self.activation2 = nonlinearity()
|
38 |
+
|
39 |
+
elif activation == "gelu":
|
40 |
+
self.activation1 = nn.GELU()
|
41 |
+
self.activation2 = nn.GELU()
|
42 |
+
|
43 |
+
|
44 |
+
|
45 |
+
self.conv1 = nn.Conv1d(n_in, n_state, 3, 1, padding, dilation)
|
46 |
+
self.conv2 = nn.Conv1d(n_state, n_in, 1, 1, 0,)
|
47 |
+
|
48 |
+
|
49 |
+
def forward(self, x):
|
50 |
+
x_orig = x
|
51 |
+
if self.norm == "LN":
|
52 |
+
x = self.norm1(x.transpose(-2, -1))
|
53 |
+
x = self.activation1(x.transpose(-2, -1))
|
54 |
+
else:
|
55 |
+
x = self.norm1(x)
|
56 |
+
x = self.activation1(x)
|
57 |
+
|
58 |
+
x = self.conv1(x)
|
59 |
+
|
60 |
+
if self.norm == "LN":
|
61 |
+
x = self.norm2(x.transpose(-2, -1))
|
62 |
+
x = self.activation2(x.transpose(-2, -1))
|
63 |
+
else:
|
64 |
+
x = self.norm2(x)
|
65 |
+
x = self.activation2(x)
|
66 |
+
|
67 |
+
x = self.conv2(x)
|
68 |
+
x = x + x_orig
|
69 |
+
return x
|
70 |
+
|
71 |
+
class Resnet1D(nn.Module):
|
72 |
+
def __init__(self, n_in, n_depth, dilation_growth_rate=1, reverse_dilation=True, activation='relu', norm=None):
|
73 |
+
super().__init__()
|
74 |
+
|
75 |
+
blocks = [ResConv1DBlock(n_in, n_in, dilation=dilation_growth_rate ** depth, activation=activation, norm=norm) for depth in range(n_depth)]
|
76 |
+
if reverse_dilation:
|
77 |
+
blocks = blocks[::-1]
|
78 |
+
|
79 |
+
self.model = nn.Sequential(*blocks)
|
80 |
+
|
81 |
+
def forward(self, x):
|
82 |
+
return self.model(x)
|
generate_human_motion/VQTrans/models/rotation2xyz.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This code is based on https://github.com/Mathux/ACTOR.git
|
2 |
+
import torch
|
3 |
+
import VQTrans.utils.rotation_conversions as geometry
|
4 |
+
|
5 |
+
|
6 |
+
from smpl import SMPL, JOINTSTYPE_ROOT
|
7 |
+
# from .get_model import JOINTSTYPES
|
8 |
+
JOINTSTYPES = ["a2m", "a2mpl", "smpl", "vibe", "vertices"]
|
9 |
+
|
10 |
+
|
11 |
+
class Rotation2xyz:
|
12 |
+
def __init__(self, device, dataset='amass'):
|
13 |
+
self.device = device
|
14 |
+
self.dataset = dataset
|
15 |
+
self.smpl_model = SMPL().eval().to(device)
|
16 |
+
|
17 |
+
def __call__(self, x, mask, pose_rep, translation, glob,
|
18 |
+
jointstype, vertstrans, betas=None, beta=0,
|
19 |
+
glob_rot=None, get_rotations_back=False, **kwargs):
|
20 |
+
if pose_rep == "xyz":
|
21 |
+
return x
|
22 |
+
|
23 |
+
if mask is None:
|
24 |
+
mask = torch.ones((x.shape[0], x.shape[-1]), dtype=bool, device=x.device)
|
25 |
+
|
26 |
+
if not glob and glob_rot is None:
|
27 |
+
raise TypeError("You must specify global rotation if glob is False")
|
28 |
+
|
29 |
+
if jointstype not in JOINTSTYPES:
|
30 |
+
raise NotImplementedError("This jointstype is not implemented.")
|
31 |
+
|
32 |
+
if translation:
|
33 |
+
x_translations = x[:, -1, :3]
|
34 |
+
x_rotations = x[:, :-1]
|
35 |
+
else:
|
36 |
+
x_rotations = x
|
37 |
+
|
38 |
+
x_rotations = x_rotations.permute(0, 3, 1, 2)
|
39 |
+
nsamples, time, njoints, feats = x_rotations.shape
|
40 |
+
|
41 |
+
# Compute rotations (convert only masked sequences output)
|
42 |
+
if pose_rep == "rotvec":
|
43 |
+
rotations = geometry.axis_angle_to_matrix(x_rotations[mask])
|
44 |
+
elif pose_rep == "rotmat":
|
45 |
+
rotations = x_rotations[mask].view(-1, njoints, 3, 3)
|
46 |
+
elif pose_rep == "rotquat":
|
47 |
+
rotations = geometry.quaternion_to_matrix(x_rotations[mask])
|
48 |
+
elif pose_rep == "rot6d":
|
49 |
+
rotations = geometry.rotation_6d_to_matrix(x_rotations[mask])
|
50 |
+
else:
|
51 |
+
raise NotImplementedError("No geometry for this one.")
|
52 |
+
|
53 |
+
if not glob:
|
54 |
+
global_orient = torch.tensor(glob_rot, device=x.device)
|
55 |
+
global_orient = geometry.axis_angle_to_matrix(global_orient).view(1, 1, 3, 3)
|
56 |
+
global_orient = global_orient.repeat(len(rotations), 1, 1, 1)
|
57 |
+
else:
|
58 |
+
global_orient = rotations[:, 0]
|
59 |
+
rotations = rotations[:, 1:]
|
60 |
+
|
61 |
+
if betas is None:
|
62 |
+
betas = torch.zeros([rotations.shape[0], self.smpl_model.num_betas],
|
63 |
+
dtype=rotations.dtype, device=rotations.device)
|
64 |
+
betas[:, 1] = beta
|
65 |
+
# import ipdb; ipdb.set_trace()
|
66 |
+
out = self.smpl_model(body_pose=rotations, global_orient=global_orient, betas=betas)
|
67 |
+
|
68 |
+
# get the desirable joints
|
69 |
+
joints = out[jointstype]
|
70 |
+
|
71 |
+
x_xyz = torch.empty(nsamples, time, joints.shape[1], 3, device=x.device, dtype=x.dtype)
|
72 |
+
x_xyz[~mask] = 0
|
73 |
+
x_xyz[mask] = joints
|
74 |
+
|
75 |
+
x_xyz = x_xyz.permute(0, 2, 3, 1).contiguous()
|
76 |
+
|
77 |
+
# the first translation root at the origin on the prediction
|
78 |
+
if jointstype != "vertices":
|
79 |
+
rootindex = JOINTSTYPE_ROOT[jointstype]
|
80 |
+
x_xyz = x_xyz - x_xyz[:, [rootindex], :, :]
|
81 |
+
|
82 |
+
if translation and vertstrans:
|
83 |
+
# the first translation root at the origin
|
84 |
+
x_translations = x_translations - x_translations[:, :, [0]]
|
85 |
+
|
86 |
+
# add the translation to all the joints
|
87 |
+
x_xyz = x_xyz + x_translations[:, None, :, :]
|
88 |
+
|
89 |
+
if get_rotations_back:
|
90 |
+
return x_xyz, rotations, global_orient
|
91 |
+
else:
|
92 |
+
return x_xyz
|
generate_human_motion/VQTrans/models/smpl.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This code is based on https://github.com/Mathux/ACTOR.git
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
|
5 |
+
import contextlib
|
6 |
+
|
7 |
+
from smplx import SMPLLayer as _SMPLLayer
|
8 |
+
from smplx.lbs import vertices2joints
|
9 |
+
|
10 |
+
|
11 |
+
# action2motion_joints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 21, 24, 38]
|
12 |
+
# change 0 and 8
|
13 |
+
action2motion_joints = [8, 1, 2, 3, 4, 5, 6, 7, 0, 9, 10, 11, 12, 13, 14, 21, 24, 38]
|
14 |
+
|
15 |
+
from VQTrans.utils.config import SMPL_MODEL_PATH, JOINT_REGRESSOR_TRAIN_EXTRA
|
16 |
+
|
17 |
+
JOINTSTYPE_ROOT = {"a2m": 0, # action2motion
|
18 |
+
"smpl": 0,
|
19 |
+
"a2mpl": 0, # set(smpl, a2m)
|
20 |
+
"vibe": 8} # 0 is the 8 position: OP MidHip below
|
21 |
+
|
22 |
+
JOINT_MAP = {
|
23 |
+
'OP Nose': 24, 'OP Neck': 12, 'OP RShoulder': 17,
|
24 |
+
'OP RElbow': 19, 'OP RWrist': 21, 'OP LShoulder': 16,
|
25 |
+
'OP LElbow': 18, 'OP LWrist': 20, 'OP MidHip': 0,
|
26 |
+
'OP RHip': 2, 'OP RKnee': 5, 'OP RAnkle': 8,
|
27 |
+
'OP LHip': 1, 'OP LKnee': 4, 'OP LAnkle': 7,
|
28 |
+
'OP REye': 25, 'OP LEye': 26, 'OP REar': 27,
|
29 |
+
'OP LEar': 28, 'OP LBigToe': 29, 'OP LSmallToe': 30,
|
30 |
+
'OP LHeel': 31, 'OP RBigToe': 32, 'OP RSmallToe': 33, 'OP RHeel': 34,
|
31 |
+
'Right Ankle': 8, 'Right Knee': 5, 'Right Hip': 45,
|
32 |
+
'Left Hip': 46, 'Left Knee': 4, 'Left Ankle': 7,
|
33 |
+
'Right Wrist': 21, 'Right Elbow': 19, 'Right Shoulder': 17,
|
34 |
+
'Left Shoulder': 16, 'Left Elbow': 18, 'Left Wrist': 20,
|
35 |
+
'Neck (LSP)': 47, 'Top of Head (LSP)': 48,
|
36 |
+
'Pelvis (MPII)': 49, 'Thorax (MPII)': 50,
|
37 |
+
'Spine (H36M)': 51, 'Jaw (H36M)': 52,
|
38 |
+
'Head (H36M)': 53, 'Nose': 24, 'Left Eye': 26,
|
39 |
+
'Right Eye': 25, 'Left Ear': 28, 'Right Ear': 27
|
40 |
+
}
|
41 |
+
|
42 |
+
JOINT_NAMES = [
|
43 |
+
'OP Nose', 'OP Neck', 'OP RShoulder',
|
44 |
+
'OP RElbow', 'OP RWrist', 'OP LShoulder',
|
45 |
+
'OP LElbow', 'OP LWrist', 'OP MidHip',
|
46 |
+
'OP RHip', 'OP RKnee', 'OP RAnkle',
|
47 |
+
'OP LHip', 'OP LKnee', 'OP LAnkle',
|
48 |
+
'OP REye', 'OP LEye', 'OP REar',
|
49 |
+
'OP LEar', 'OP LBigToe', 'OP LSmallToe',
|
50 |
+
'OP LHeel', 'OP RBigToe', 'OP RSmallToe', 'OP RHeel',
|
51 |
+
'Right Ankle', 'Right Knee', 'Right Hip',
|
52 |
+
'Left Hip', 'Left Knee', 'Left Ankle',
|
53 |
+
'Right Wrist', 'Right Elbow', 'Right Shoulder',
|
54 |
+
'Left Shoulder', 'Left Elbow', 'Left Wrist',
|
55 |
+
'Neck (LSP)', 'Top of Head (LSP)',
|
56 |
+
'Pelvis (MPII)', 'Thorax (MPII)',
|
57 |
+
'Spine (H36M)', 'Jaw (H36M)',
|
58 |
+
'Head (H36M)', 'Nose', 'Left Eye',
|
59 |
+
'Right Eye', 'Left Ear', 'Right Ear'
|
60 |
+
]
|
61 |
+
|
62 |
+
|
63 |
+
# adapted from VIBE/SPIN to output smpl_joints, vibe joints and action2motion joints
|
64 |
+
class SMPL(_SMPLLayer):
|
65 |
+
""" Extension of the official SMPL implementation to support more joints """
|
66 |
+
|
67 |
+
def __init__(self, model_path=SMPL_MODEL_PATH, **kwargs):
|
68 |
+
kwargs["model_path"] = model_path
|
69 |
+
|
70 |
+
# remove the verbosity for the 10-shapes beta parameters
|
71 |
+
with contextlib.redirect_stdout(None):
|
72 |
+
super(SMPL, self).__init__(**kwargs)
|
73 |
+
|
74 |
+
J_regressor_extra = np.load(JOINT_REGRESSOR_TRAIN_EXTRA)
|
75 |
+
self.register_buffer('J_regressor_extra', torch.tensor(J_regressor_extra, dtype=torch.float32))
|
76 |
+
vibe_indexes = np.array([JOINT_MAP[i] for i in JOINT_NAMES])
|
77 |
+
a2m_indexes = vibe_indexes[action2motion_joints]
|
78 |
+
smpl_indexes = np.arange(24)
|
79 |
+
a2mpl_indexes = np.unique(np.r_[smpl_indexes, a2m_indexes])
|
80 |
+
|
81 |
+
self.maps = {"vibe": vibe_indexes,
|
82 |
+
"a2m": a2m_indexes,
|
83 |
+
"smpl": smpl_indexes,
|
84 |
+
"a2mpl": a2mpl_indexes}
|
85 |
+
|
86 |
+
def forward(self, *args, **kwargs):
|
87 |
+
smpl_output = super(SMPL, self).forward(*args, **kwargs)
|
88 |
+
|
89 |
+
extra_joints = vertices2joints(self.J_regressor_extra, smpl_output.vertices)
|
90 |
+
all_joints = torch.cat([smpl_output.joints, extra_joints], dim=1)
|
91 |
+
|
92 |
+
output = {"vertices": smpl_output.vertices}
|
93 |
+
|
94 |
+
for joinstype, indexes in self.maps.items():
|
95 |
+
output[joinstype] = all_joints[:, indexes]
|
96 |
+
|
97 |
+
return output
|
generate_human_motion/VQTrans/models/t2m_trans.py
ADDED
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
from torch.nn import functional as F
|
5 |
+
from torch.distributions import Categorical
|
6 |
+
import pos_encoding as pos_encoding
|
7 |
+
|
8 |
+
class Text2Motion_Transformer(nn.Module):
|
9 |
+
|
10 |
+
def __init__(self,
|
11 |
+
num_vq=1024,
|
12 |
+
embed_dim=512,
|
13 |
+
clip_dim=512,
|
14 |
+
block_size=16,
|
15 |
+
num_layers=2,
|
16 |
+
n_head=8,
|
17 |
+
drop_out_rate=0.1,
|
18 |
+
fc_rate=4):
|
19 |
+
super().__init__()
|
20 |
+
self.trans_base = CrossCondTransBase(num_vq, embed_dim, clip_dim, block_size, num_layers, n_head, drop_out_rate, fc_rate)
|
21 |
+
self.trans_head = CrossCondTransHead(num_vq, embed_dim, block_size, num_layers, n_head, drop_out_rate, fc_rate)
|
22 |
+
self.block_size = block_size
|
23 |
+
self.num_vq = num_vq
|
24 |
+
|
25 |
+
def get_block_size(self):
|
26 |
+
return self.block_size
|
27 |
+
|
28 |
+
def forward(self, idxs, clip_feature):
|
29 |
+
feat = self.trans_base(idxs, clip_feature)
|
30 |
+
logits = self.trans_head(feat)
|
31 |
+
return logits
|
32 |
+
|
33 |
+
def sample(self, clip_feature, if_categorial=False):
|
34 |
+
for k in range(self.block_size):
|
35 |
+
if k == 0:
|
36 |
+
x = []
|
37 |
+
else:
|
38 |
+
x = xs
|
39 |
+
logits = self.forward(x, clip_feature)
|
40 |
+
logits = logits[:, -1, :]
|
41 |
+
probs = F.softmax(logits, dim=-1)
|
42 |
+
if if_categorial:
|
43 |
+
dist = Categorical(probs)
|
44 |
+
idx = dist.sample()
|
45 |
+
if idx == self.num_vq:
|
46 |
+
break
|
47 |
+
idx = idx.unsqueeze(-1)
|
48 |
+
else:
|
49 |
+
_, idx = torch.topk(probs, k=1, dim=-1)
|
50 |
+
if idx[0] == self.num_vq:
|
51 |
+
break
|
52 |
+
# append to the sequence and continue
|
53 |
+
if k == 0:
|
54 |
+
xs = idx
|
55 |
+
else:
|
56 |
+
xs = torch.cat((xs, idx), dim=1)
|
57 |
+
|
58 |
+
if k == self.block_size - 1:
|
59 |
+
return xs[:, :-1]
|
60 |
+
return xs
|
61 |
+
|
62 |
+
class CausalCrossConditionalSelfAttention(nn.Module):
|
63 |
+
|
64 |
+
def __init__(self, embed_dim=512, block_size=16, n_head=8, drop_out_rate=0.1):
|
65 |
+
super().__init__()
|
66 |
+
assert embed_dim % 8 == 0
|
67 |
+
# key, query, value projections for all heads
|
68 |
+
self.key = nn.Linear(embed_dim, embed_dim)
|
69 |
+
self.query = nn.Linear(embed_dim, embed_dim)
|
70 |
+
self.value = nn.Linear(embed_dim, embed_dim)
|
71 |
+
|
72 |
+
self.attn_drop = nn.Dropout(drop_out_rate)
|
73 |
+
self.resid_drop = nn.Dropout(drop_out_rate)
|
74 |
+
|
75 |
+
self.proj = nn.Linear(embed_dim, embed_dim)
|
76 |
+
# causal mask to ensure that attention is only applied to the left in the input sequence
|
77 |
+
self.register_buffer("mask", torch.tril(torch.ones(block_size, block_size)).view(1, 1, block_size, block_size))
|
78 |
+
self.n_head = n_head
|
79 |
+
|
80 |
+
def forward(self, x):
|
81 |
+
B, T, C = x.size()
|
82 |
+
|
83 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
84 |
+
k = self.key(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
85 |
+
q = self.query(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
86 |
+
v = self.value(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
87 |
+
# causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
|
88 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
89 |
+
att = att.masked_fill(self.mask[:,:,:T,:T] == 0, float('-inf'))
|
90 |
+
att = F.softmax(att, dim=-1)
|
91 |
+
att = self.attn_drop(att)
|
92 |
+
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
|
93 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
94 |
+
|
95 |
+
# output projection
|
96 |
+
y = self.resid_drop(self.proj(y))
|
97 |
+
return y
|
98 |
+
|
99 |
+
class Block(nn.Module):
|
100 |
+
|
101 |
+
def __init__(self, embed_dim=512, block_size=16, n_head=8, drop_out_rate=0.1, fc_rate=4):
|
102 |
+
super().__init__()
|
103 |
+
self.ln1 = nn.LayerNorm(embed_dim)
|
104 |
+
self.ln2 = nn.LayerNorm(embed_dim)
|
105 |
+
self.attn = CausalCrossConditionalSelfAttention(embed_dim, block_size, n_head, drop_out_rate)
|
106 |
+
self.mlp = nn.Sequential(
|
107 |
+
nn.Linear(embed_dim, fc_rate * embed_dim),
|
108 |
+
nn.GELU(),
|
109 |
+
nn.Linear(fc_rate * embed_dim, embed_dim),
|
110 |
+
nn.Dropout(drop_out_rate),
|
111 |
+
)
|
112 |
+
|
113 |
+
def forward(self, x):
|
114 |
+
x = x + self.attn(self.ln1(x))
|
115 |
+
x = x + self.mlp(self.ln2(x))
|
116 |
+
return x
|
117 |
+
|
118 |
+
class CrossCondTransBase(nn.Module):
|
119 |
+
|
120 |
+
def __init__(self,
|
121 |
+
num_vq=1024,
|
122 |
+
embed_dim=512,
|
123 |
+
clip_dim=512,
|
124 |
+
block_size=16,
|
125 |
+
num_layers=2,
|
126 |
+
n_head=8,
|
127 |
+
drop_out_rate=0.1,
|
128 |
+
fc_rate=4):
|
129 |
+
super().__init__()
|
130 |
+
self.tok_emb = nn.Embedding(num_vq + 2, embed_dim)
|
131 |
+
self.cond_emb = nn.Linear(clip_dim, embed_dim)
|
132 |
+
self.pos_embedding = nn.Embedding(block_size, embed_dim)
|
133 |
+
self.drop = nn.Dropout(drop_out_rate)
|
134 |
+
# transformer block
|
135 |
+
self.blocks = nn.Sequential(*[Block(embed_dim, block_size, n_head, drop_out_rate, fc_rate) for _ in range(num_layers)])
|
136 |
+
self.pos_embed = pos_encoding.PositionEmbedding(block_size, embed_dim, 0.0, False)
|
137 |
+
|
138 |
+
self.block_size = block_size
|
139 |
+
|
140 |
+
self.apply(self._init_weights)
|
141 |
+
|
142 |
+
def get_block_size(self):
|
143 |
+
return self.block_size
|
144 |
+
|
145 |
+
def _init_weights(self, module):
|
146 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
147 |
+
module.weight.data.normal_(mean=0.0, std=0.02)
|
148 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
149 |
+
module.bias.data.zero_()
|
150 |
+
elif isinstance(module, nn.LayerNorm):
|
151 |
+
module.bias.data.zero_()
|
152 |
+
module.weight.data.fill_(1.0)
|
153 |
+
|
154 |
+
def forward(self, idx, clip_feature):
|
155 |
+
if len(idx) == 0:
|
156 |
+
token_embeddings = self.cond_emb(clip_feature).unsqueeze(1)
|
157 |
+
else:
|
158 |
+
b, t = idx.size()
|
159 |
+
assert t <= self.block_size, "Cannot forward, model block size is exhausted."
|
160 |
+
# forward the Trans model
|
161 |
+
token_embeddings = self.tok_emb(idx)
|
162 |
+
token_embeddings = torch.cat([self.cond_emb(clip_feature).unsqueeze(1), token_embeddings], dim=1)
|
163 |
+
|
164 |
+
x = self.pos_embed(token_embeddings)
|
165 |
+
x = self.blocks(x)
|
166 |
+
|
167 |
+
return x
|
168 |
+
|
169 |
+
|
170 |
+
class CrossCondTransHead(nn.Module):
|
171 |
+
|
172 |
+
def __init__(self,
|
173 |
+
num_vq=1024,
|
174 |
+
embed_dim=512,
|
175 |
+
block_size=16,
|
176 |
+
num_layers=2,
|
177 |
+
n_head=8,
|
178 |
+
drop_out_rate=0.1,
|
179 |
+
fc_rate=4):
|
180 |
+
super().__init__()
|
181 |
+
|
182 |
+
self.blocks = nn.Sequential(*[Block(embed_dim, block_size, n_head, drop_out_rate, fc_rate) for _ in range(num_layers)])
|
183 |
+
self.ln_f = nn.LayerNorm(embed_dim)
|
184 |
+
self.head = nn.Linear(embed_dim, num_vq + 1, bias=False)
|
185 |
+
self.block_size = block_size
|
186 |
+
|
187 |
+
self.apply(self._init_weights)
|
188 |
+
|
189 |
+
def get_block_size(self):
|
190 |
+
return self.block_size
|
191 |
+
|
192 |
+
def _init_weights(self, module):
|
193 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
194 |
+
module.weight.data.normal_(mean=0.0, std=0.02)
|
195 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
196 |
+
module.bias.data.zero_()
|
197 |
+
elif isinstance(module, nn.LayerNorm):
|
198 |
+
module.bias.data.zero_()
|
199 |
+
module.weight.data.fill_(1.0)
|
200 |
+
|
201 |
+
def forward(self, x):
|
202 |
+
x = self.blocks(x)
|
203 |
+
x = self.ln_f(x)
|
204 |
+
logits = self.head(x)
|
205 |
+
return logits
|
206 |
+
|
207 |
+
|
208 |
+
|
209 |
+
|
210 |
+
|
211 |
+
|
generate_human_motion/VQTrans/models/vqvae.py
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
from encdec import Encoder, Decoder
|
3 |
+
from quantize_cnn import QuantizeEMAReset, Quantizer, QuantizeEMA, QuantizeReset
|
4 |
+
|
5 |
+
|
6 |
+
class VQVAE_251(nn.Module):
|
7 |
+
def __init__(self,
|
8 |
+
args,
|
9 |
+
nb_code=1024,
|
10 |
+
code_dim=512,
|
11 |
+
output_emb_width=512,
|
12 |
+
down_t=3,
|
13 |
+
stride_t=2,
|
14 |
+
width=512,
|
15 |
+
depth=3,
|
16 |
+
dilation_growth_rate=3,
|
17 |
+
activation='relu',
|
18 |
+
norm=None):
|
19 |
+
|
20 |
+
super().__init__()
|
21 |
+
self.code_dim = code_dim
|
22 |
+
self.num_code = nb_code
|
23 |
+
self.quant = args.quantizer
|
24 |
+
self.encoder = Encoder(251 if args.dataname == 'kit' else 263, output_emb_width, down_t, stride_t, width, depth, dilation_growth_rate, activation=activation, norm=norm)
|
25 |
+
self.decoder = Decoder(251 if args.dataname == 'kit' else 263, output_emb_width, down_t, stride_t, width, depth, dilation_growth_rate, activation=activation, norm=norm)
|
26 |
+
if args.quantizer == "ema_reset":
|
27 |
+
self.quantizer = QuantizeEMAReset(nb_code, code_dim, args)
|
28 |
+
elif args.quantizer == "orig":
|
29 |
+
self.quantizer = Quantizer(nb_code, code_dim, 1.0)
|
30 |
+
elif args.quantizer == "ema":
|
31 |
+
self.quantizer = QuantizeEMA(nb_code, code_dim, args)
|
32 |
+
elif args.quantizer == "reset":
|
33 |
+
self.quantizer = QuantizeReset(nb_code, code_dim, args)
|
34 |
+
|
35 |
+
|
36 |
+
def preprocess(self, x):
|
37 |
+
# (bs, T, Jx3) -> (bs, Jx3, T)
|
38 |
+
x = x.permute(0,2,1).float()
|
39 |
+
return x
|
40 |
+
|
41 |
+
|
42 |
+
def postprocess(self, x):
|
43 |
+
# (bs, Jx3, T) -> (bs, T, Jx3)
|
44 |
+
x = x.permute(0,2,1)
|
45 |
+
return x
|
46 |
+
|
47 |
+
|
48 |
+
def encode(self, x):
|
49 |
+
N, T, _ = x.shape
|
50 |
+
x_in = self.preprocess(x)
|
51 |
+
x_encoder = self.encoder(x_in)
|
52 |
+
x_encoder = self.postprocess(x_encoder)
|
53 |
+
x_encoder = x_encoder.contiguous().view(-1, x_encoder.shape[-1]) # (NT, C)
|
54 |
+
code_idx = self.quantizer.quantize(x_encoder)
|
55 |
+
code_idx = code_idx.view(N, -1)
|
56 |
+
return code_idx
|
57 |
+
|
58 |
+
|
59 |
+
def forward(self, x):
|
60 |
+
|
61 |
+
x_in = self.preprocess(x)
|
62 |
+
# Encode
|
63 |
+
x_encoder = self.encoder(x_in)
|
64 |
+
|
65 |
+
## quantization
|
66 |
+
x_quantized, loss, perplexity = self.quantizer(x_encoder)
|
67 |
+
|
68 |
+
## decoder
|
69 |
+
x_decoder = self.decoder(x_quantized)
|
70 |
+
x_out = self.postprocess(x_decoder)
|
71 |
+
return x_out, loss, perplexity
|
72 |
+
|
73 |
+
|
74 |
+
def forward_decoder(self, x):
|
75 |
+
x_d = self.quantizer.dequantize(x)
|
76 |
+
x_d = x_d.view(1, -1, self.code_dim).permute(0, 2, 1).contiguous()
|
77 |
+
|
78 |
+
# decoder
|
79 |
+
x_decoder = self.decoder(x_d)
|
80 |
+
x_out = self.postprocess(x_decoder)
|
81 |
+
return x_out
|
82 |
+
|
83 |
+
|
84 |
+
|
85 |
+
class HumanVQVAE(nn.Module):
|
86 |
+
def __init__(self,
|
87 |
+
args,
|
88 |
+
nb_code=512,
|
89 |
+
code_dim=512,
|
90 |
+
output_emb_width=512,
|
91 |
+
down_t=3,
|
92 |
+
stride_t=2,
|
93 |
+
width=512,
|
94 |
+
depth=3,
|
95 |
+
dilation_growth_rate=3,
|
96 |
+
activation='relu',
|
97 |
+
norm=None):
|
98 |
+
|
99 |
+
super().__init__()
|
100 |
+
|
101 |
+
self.nb_joints = 21 if args.dataname == 'kit' else 22
|
102 |
+
self.vqvae = VQVAE_251(args, nb_code, code_dim, output_emb_width, down_t, stride_t, width, depth, dilation_growth_rate, activation=activation, norm=norm)
|
103 |
+
|
104 |
+
def encode(self, x):
|
105 |
+
b, t, c = x.size()
|
106 |
+
quants = self.vqvae.encode(x) # (N, T)
|
107 |
+
return quants
|
108 |
+
|
109 |
+
def forward(self, x):
|
110 |
+
|
111 |
+
x_out, loss, perplexity = self.vqvae(x)
|
112 |
+
|
113 |
+
return x_out, loss, perplexity
|
114 |
+
|
115 |
+
def forward_decoder(self, x):
|
116 |
+
x_out = self.vqvae.forward_decoder(x)
|
117 |
+
return x_out
|
118 |
+
|
generate_human_motion/VQTrans/options/__pycache__/option_transformer.cpython-310.pyc
ADDED
Binary file (3.24 kB). View file
|
|
generate_human_motion/VQTrans/options/get_eval_option.py
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from argparse import Namespace
|
2 |
+
import re
|
3 |
+
from os.path import join as pjoin
|
4 |
+
|
5 |
+
|
6 |
+
def is_float(numStr):
|
7 |
+
flag = False
|
8 |
+
numStr = str(numStr).strip().lstrip('-').lstrip('+')
|
9 |
+
try:
|
10 |
+
reg = re.compile(r'^[-+]?[0-9]+\.[0-9]+$')
|
11 |
+
res = reg.match(str(numStr))
|
12 |
+
if res:
|
13 |
+
flag = True
|
14 |
+
except Exception as ex:
|
15 |
+
print("is_float() - error: " + str(ex))
|
16 |
+
return flag
|
17 |
+
|
18 |
+
|
19 |
+
def is_number(numStr):
|
20 |
+
flag = False
|
21 |
+
numStr = str(numStr).strip().lstrip('-').lstrip('+')
|
22 |
+
if str(numStr).isdigit():
|
23 |
+
flag = True
|
24 |
+
return flag
|
25 |
+
|
26 |
+
|
27 |
+
def get_opt(opt_path, device):
|
28 |
+
opt = Namespace()
|
29 |
+
opt_dict = vars(opt)
|
30 |
+
|
31 |
+
skip = ('-------------- End ----------------',
|
32 |
+
'------------ Options -------------',
|
33 |
+
'\n')
|
34 |
+
print('Reading', opt_path)
|
35 |
+
with open(opt_path) as f:
|
36 |
+
for line in f:
|
37 |
+
if line.strip() not in skip:
|
38 |
+
# print(line.strip())
|
39 |
+
key, value = line.strip().split(': ')
|
40 |
+
if value in ('True', 'False'):
|
41 |
+
opt_dict[key] = (value == 'True')
|
42 |
+
# print(key, value)
|
43 |
+
elif is_float(value):
|
44 |
+
opt_dict[key] = float(value)
|
45 |
+
elif is_number(value):
|
46 |
+
opt_dict[key] = int(value)
|
47 |
+
else:
|
48 |
+
opt_dict[key] = str(value)
|
49 |
+
|
50 |
+
# print(opt)
|
51 |
+
opt_dict['which_epoch'] = 'finest'
|
52 |
+
opt.save_root = pjoin(opt.checkpoints_dir, opt.dataset_name, opt.name)
|
53 |
+
opt.model_dir = pjoin(opt.save_root, 'model')
|
54 |
+
opt.meta_dir = pjoin(opt.save_root, 'meta')
|
55 |
+
|
56 |
+
if opt.dataset_name == 't2m':
|
57 |
+
opt.data_root = './dataset/HumanML3D/'
|
58 |
+
opt.motion_dir = pjoin(opt.data_root, 'new_joint_vecs')
|
59 |
+
opt.text_dir = pjoin(opt.data_root, 'texts')
|
60 |
+
opt.joints_num = 22
|
61 |
+
opt.dim_pose = 263
|
62 |
+
opt.max_motion_length = 196
|
63 |
+
opt.max_motion_frame = 196
|
64 |
+
opt.max_motion_token = 55
|
65 |
+
elif opt.dataset_name == 'kit':
|
66 |
+
opt.data_root = './dataset/KIT-ML/'
|
67 |
+
opt.motion_dir = pjoin(opt.data_root, 'new_joint_vecs')
|
68 |
+
opt.text_dir = pjoin(opt.data_root, 'texts')
|
69 |
+
opt.joints_num = 21
|
70 |
+
opt.dim_pose = 251
|
71 |
+
opt.max_motion_length = 196
|
72 |
+
opt.max_motion_frame = 196
|
73 |
+
opt.max_motion_token = 55
|
74 |
+
else:
|
75 |
+
raise KeyError('Dataset not recognized')
|
76 |
+
|
77 |
+
opt.dim_word = 300
|
78 |
+
opt.num_classes = 200 // opt.unit_length
|
79 |
+
opt.is_train = False
|
80 |
+
opt.is_continue = False
|
81 |
+
opt.device = device
|
82 |
+
|
83 |
+
return opt
|
generate_human_motion/VQTrans/options/option_transformer.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
|
3 |
+
def get_args_parser():
|
4 |
+
parser = argparse.ArgumentParser(description='Optimal Transport AutoEncoder training for Amass',
|
5 |
+
add_help=True,
|
6 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
7 |
+
|
8 |
+
## dataloader
|
9 |
+
|
10 |
+
parser.add_argument('--dataname', type=str, default='kit', help='dataset directory')
|
11 |
+
parser.add_argument('--batch-size', default=128, type=int, help='batch size')
|
12 |
+
parser.add_argument('--fps', default=[20], nargs="+", type=int, help='frames per second')
|
13 |
+
parser.add_argument('--seq-len', type=int, default=64, help='training motion length')
|
14 |
+
|
15 |
+
## optimization
|
16 |
+
parser.add_argument('--total-iter', default=100000, type=int, help='number of total iterations to run')
|
17 |
+
parser.add_argument('--warm-up-iter', default=1000, type=int, help='number of total iterations for warmup')
|
18 |
+
parser.add_argument('--lr', default=2e-4, type=float, help='max learning rate')
|
19 |
+
parser.add_argument('--lr-scheduler', default=[60000], nargs="+", type=int, help="learning rate schedule (iterations)")
|
20 |
+
parser.add_argument('--gamma', default=0.05, type=float, help="learning rate decay")
|
21 |
+
|
22 |
+
parser.add_argument('--weight-decay', default=1e-6, type=float, help='weight decay')
|
23 |
+
parser.add_argument('--decay-option',default='all', type=str, choices=['all', 'noVQ'], help='disable weight decay on codebook')
|
24 |
+
parser.add_argument('--optimizer',default='adamw', type=str, choices=['adam', 'adamw'], help='disable weight decay on codebook')
|
25 |
+
|
26 |
+
## vqvae arch
|
27 |
+
parser.add_argument("--code-dim", type=int, default=512, help="embedding dimension")
|
28 |
+
parser.add_argument("--nb-code", type=int, default=512, help="nb of embedding")
|
29 |
+
parser.add_argument("--mu", type=float, default=0.99, help="exponential moving average to update the codebook")
|
30 |
+
parser.add_argument("--down-t", type=int, default=3, help="downsampling rate")
|
31 |
+
parser.add_argument("--stride-t", type=int, default=2, help="stride size")
|
32 |
+
parser.add_argument("--width", type=int, default=512, help="width of the network")
|
33 |
+
parser.add_argument("--depth", type=int, default=3, help="depth of the network")
|
34 |
+
parser.add_argument("--dilation-growth-rate", type=int, default=3, help="dilation growth rate")
|
35 |
+
parser.add_argument("--output-emb-width", type=int, default=512, help="output embedding width")
|
36 |
+
parser.add_argument('--vq-act', type=str, default='relu', choices = ['relu', 'silu', 'gelu'], help='dataset directory')
|
37 |
+
|
38 |
+
## gpt arch
|
39 |
+
parser.add_argument("--block-size", type=int, default=25, help="seq len")
|
40 |
+
parser.add_argument("--embed-dim-gpt", type=int, default=512, help="embedding dimension")
|
41 |
+
parser.add_argument("--clip-dim", type=int, default=512, help="latent dimension in the clip feature")
|
42 |
+
parser.add_argument("--num-layers", type=int, default=2, help="nb of transformer layers")
|
43 |
+
parser.add_argument("--n-head-gpt", type=int, default=8, help="nb of heads")
|
44 |
+
parser.add_argument("--ff-rate", type=int, default=4, help="feedforward size")
|
45 |
+
parser.add_argument("--drop-out-rate", type=float, default=0.1, help="dropout ratio in the pos encoding")
|
46 |
+
|
47 |
+
## quantizer
|
48 |
+
parser.add_argument("--quantizer", type=str, default='ema_reset', choices = ['ema', 'orig', 'ema_reset', 'reset'], help="eps for optimal transport")
|
49 |
+
parser.add_argument('--quantbeta', type=float, default=1.0, help='dataset directory')
|
50 |
+
|
51 |
+
## resume
|
52 |
+
parser.add_argument("--resume-pth", type=str, default=None, help='resume vq pth')
|
53 |
+
parser.add_argument("--resume-trans", type=str, default=None, help='resume gpt pth')
|
54 |
+
|
55 |
+
|
56 |
+
## output directory
|
57 |
+
parser.add_argument('--out-dir', type=str, default='output_GPT_Final/', help='output directory')
|
58 |
+
parser.add_argument('--exp-name', type=str, default='exp_debug', help='name of the experiment, will create a file inside out-dir')
|
59 |
+
parser.add_argument('--vq-name', type=str, default='exp_debug', help='name of the generated dataset .npy, will create a file inside out-dir')
|
60 |
+
## other
|
61 |
+
parser.add_argument('--print-iter', default=200, type=int, help='print frequency')
|
62 |
+
parser.add_argument('--eval-iter', default=5000, type=int, help='evaluation frequency')
|
63 |
+
parser.add_argument('--seed', default=123, type=int, help='seed for initializing training. ')
|
64 |
+
parser.add_argument("--if-maxtest", action='store_true', help="test in max")
|
65 |
+
parser.add_argument('--pkeep', type=float, default=1.0, help='keep rate for gpt training')
|
66 |
+
|
67 |
+
|
68 |
+
return parser.parse_args()
|
generate_human_motion/VQTrans/options/option_vq.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
|
3 |
+
def get_args_parser():
|
4 |
+
parser = argparse.ArgumentParser(description='Optimal Transport AutoEncoder training for AIST',
|
5 |
+
add_help=True,
|
6 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
7 |
+
|
8 |
+
## dataloader
|
9 |
+
parser.add_argument('--dataname', type=str, default='kit', help='dataset directory')
|
10 |
+
parser.add_argument('--batch-size', default=128, type=int, help='batch size')
|
11 |
+
parser.add_argument('--window-size', type=int, default=64, help='training motion length')
|
12 |
+
|
13 |
+
## optimization
|
14 |
+
parser.add_argument('--total-iter', default=200000, type=int, help='number of total iterations to run')
|
15 |
+
parser.add_argument('--warm-up-iter', default=1000, type=int, help='number of total iterations for warmup')
|
16 |
+
parser.add_argument('--lr', default=2e-4, type=float, help='max learning rate')
|
17 |
+
parser.add_argument('--lr-scheduler', default=[50000, 400000], nargs="+", type=int, help="learning rate schedule (iterations)")
|
18 |
+
parser.add_argument('--gamma', default=0.05, type=float, help="learning rate decay")
|
19 |
+
|
20 |
+
parser.add_argument('--weight-decay', default=0.0, type=float, help='weight decay')
|
21 |
+
parser.add_argument("--commit", type=float, default=0.02, help="hyper-parameter for the commitment loss")
|
22 |
+
parser.add_argument('--loss-vel', type=float, default=0.1, help='hyper-parameter for the velocity loss')
|
23 |
+
parser.add_argument('--recons-loss', type=str, default='l2', help='reconstruction loss')
|
24 |
+
|
25 |
+
## vqvae arch
|
26 |
+
parser.add_argument("--code-dim", type=int, default=512, help="embedding dimension")
|
27 |
+
parser.add_argument("--nb-code", type=int, default=512, help="nb of embedding")
|
28 |
+
parser.add_argument("--mu", type=float, default=0.99, help="exponential moving average to update the codebook")
|
29 |
+
parser.add_argument("--down-t", type=int, default=2, help="downsampling rate")
|
30 |
+
parser.add_argument("--stride-t", type=int, default=2, help="stride size")
|
31 |
+
parser.add_argument("--width", type=int, default=512, help="width of the network")
|
32 |
+
parser.add_argument("--depth", type=int, default=3, help="depth of the network")
|
33 |
+
parser.add_argument("--dilation-growth-rate", type=int, default=3, help="dilation growth rate")
|
34 |
+
parser.add_argument("--output-emb-width", type=int, default=512, help="output embedding width")
|
35 |
+
parser.add_argument('--vq-act', type=str, default='relu', choices = ['relu', 'silu', 'gelu'], help='dataset directory')
|
36 |
+
parser.add_argument('--vq-norm', type=str, default=None, help='dataset directory')
|
37 |
+
|
38 |
+
## quantizer
|
39 |
+
parser.add_argument("--quantizer", type=str, default='ema_reset', choices = ['ema', 'orig', 'ema_reset', 'reset'], help="eps for optimal transport")
|
40 |
+
parser.add_argument('--beta', type=float, default=1.0, help='commitment loss in standard VQ')
|
41 |
+
|
42 |
+
## resume
|
43 |
+
parser.add_argument("--resume-pth", type=str, default=None, help='resume pth for VQ')
|
44 |
+
parser.add_argument("--resume-gpt", type=str, default=None, help='resume pth for GPT')
|
45 |
+
|
46 |
+
|
47 |
+
## output directory
|
48 |
+
parser.add_argument('--out-dir', type=str, default='output_vqfinal/', help='output directory')
|
49 |
+
parser.add_argument('--results-dir', type=str, default='visual_results/', help='output directory')
|
50 |
+
parser.add_argument('--visual-name', type=str, default='baseline', help='output directory')
|
51 |
+
parser.add_argument('--exp-name', type=str, default='exp_debug', help='name of the experiment, will create a file inside out-dir')
|
52 |
+
## other
|
53 |
+
parser.add_argument('--print-iter', default=200, type=int, help='print frequency')
|
54 |
+
parser.add_argument('--eval-iter', default=1000, type=int, help='evaluation frequency')
|
55 |
+
parser.add_argument('--seed', default=123, type=int, help='seed for initializing training.')
|
56 |
+
|
57 |
+
parser.add_argument('--vis-gt', action='store_true', help='whether visualize GT motions')
|
58 |
+
parser.add_argument('--nb-vis', default=20, type=int, help='nb of visualizations')
|
59 |
+
|
60 |
+
|
61 |
+
return parser.parse_args()
|
generate_human_motion/VQTrans/output/02ab4ad275eda92f352e2ed8d942eeef_pred.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:80236f3d1abbbbebe1d8c507192e43d4bc0a45530ba07878359aac3b32b497c8
|
3 |
+
size 10253253
|
generate_human_motion/VQTrans/output/06c27c738e874b23067c006f52e18ebc_pred.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d4ae194ab73d235b8db97d33b8d16fa5992eebd0d8a827ec795441e6f6000295
|
3 |
+
size 4961733
|
generate_human_motion/VQTrans/output/0edd5f692aeec051d748dee0844f94e1_pred.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:00eb8444c64fc2e33a9e19f66c0f2c8f104000da647c0aabc510a5bb46afd1a9
|
3 |
+
size 6946053
|
generate_human_motion/VQTrans/output/23cb7d0e26bb1646b3d386331971449c_pred.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9e05998e1d4ac1eebcba89ec989112b6fcdb55c8cceeef2faea7cb564a381525
|
3 |
+
size 16206213
|