Upload 36 files
Browse files- dataset/dataset_TM_eval.py +241 -0
- dataset/dataset_TM_train.py +188 -0
- dataset/dataset_VQ.py +109 -0
- dataset/dataset_tokenize.py +136 -0
- dataset/prepare/download_extractor.sh +15 -0
- dataset/prepare/download_glove.sh +9 -0
- dataset/prepare/download_model.sh +12 -0
- dataset/prepare/download_smpl.sh +13 -0
- models/__pycache__/encdec.cpython-38.pyc +0 -0
- models/__pycache__/encdec.cpython-39.pyc +0 -0
- models/__pycache__/evaluator_wrapper.cpython-38.pyc +0 -0
- models/__pycache__/evaluator_wrapper.cpython-39.pyc +0 -0
- models/__pycache__/modules.cpython-38.pyc +0 -0
- models/__pycache__/modules.cpython-39.pyc +0 -0
- models/__pycache__/pos_encoding.cpython-38.pyc +0 -0
- models/__pycache__/pos_encoding.cpython-39.pyc +0 -0
- models/__pycache__/quantize_cnn.cpython-38.pyc +0 -0
- models/__pycache__/quantize_cnn.cpython-39.pyc +0 -0
- models/__pycache__/resnet.cpython-38.pyc +0 -0
- models/__pycache__/resnet.cpython-39.pyc +0 -0
- models/__pycache__/rotation2xyz.cpython-38.pyc +0 -0
- models/__pycache__/smpl.cpython-38.pyc +0 -0
- models/__pycache__/t2m_trans.cpython-38.pyc +0 -0
- models/__pycache__/t2m_trans.cpython-39.pyc +0 -0
- models/__pycache__/vqvae.cpython-38.pyc +0 -0
- models/__pycache__/vqvae.cpython-39.pyc +0 -0
- models/encdec.py +67 -0
- models/evaluator_wrapper.py +92 -0
- models/modules.py +109 -0
- models/pos_encoding.py +43 -0
- models/quantize_cnn.py +413 -0
- models/resnet.py +82 -0
- models/rotation2xyz.py +92 -0
- models/smpl.py +97 -0
- models/t2m_trans.py +239 -0
- models/vqvae.py +118 -0
dataset/dataset_TM_eval.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 53 |
+
mean = np.load(pjoin(self.meta_dir, 'mean.npy'))
|
| 54 |
+
std = np.load(pjoin(self.meta_dir, 'std.npy'))
|
| 55 |
+
|
| 56 |
+
if is_test:
|
| 57 |
+
split_file = pjoin(self.data_root, 'test.txt') # test.txt
|
| 58 |
+
else:
|
| 59 |
+
split_file = pjoin(self.data_root, 'val.txt')
|
| 60 |
+
|
| 61 |
+
min_motion_len = 40 if self.dataset_name =='t2m' else 24
|
| 62 |
+
# min_motion_len = 64
|
| 63 |
+
|
| 64 |
+
joints_num = self.joints_num
|
| 65 |
+
|
| 66 |
+
data_dict = {}
|
| 67 |
+
id_list = []
|
| 68 |
+
with cs.open(split_file, 'r') as f:
|
| 69 |
+
for line in f.readlines():
|
| 70 |
+
id_list.append(line.strip())
|
| 71 |
+
|
| 72 |
+
new_name_list = []
|
| 73 |
+
length_list = []
|
| 74 |
+
for name in tqdm(id_list):
|
| 75 |
+
try:
|
| 76 |
+
motion = np.load(pjoin(self.motion_dir, name + '.npy'))
|
| 77 |
+
if (len(motion)) < min_motion_len or (len(motion) >= 200):
|
| 78 |
+
continue
|
| 79 |
+
text_data = []
|
| 80 |
+
flag = False
|
| 81 |
+
|
| 82 |
+
with cs.open(pjoin(self.text_dir, name + '.txt')) as f:
|
| 83 |
+
for line in f.readlines():
|
| 84 |
+
text_dict = {}
|
| 85 |
+
line_split = line.strip().split('#')
|
| 86 |
+
caption = line_split[0]
|
| 87 |
+
txt_perb = line_split[-1]
|
| 88 |
+
tokens = line_split[1].split(' ')
|
| 89 |
+
f_tag = float(line_split[2])
|
| 90 |
+
to_tag = float(line_split[3])
|
| 91 |
+
f_tag = 0.0 if np.isnan(f_tag) else f_tag
|
| 92 |
+
to_tag = 0.0 if np.isnan(to_tag) else to_tag
|
| 93 |
+
|
| 94 |
+
text_dict['caption'] = caption
|
| 95 |
+
text_dict['caption_perb'] = txt_perb
|
| 96 |
+
text_dict['tokens'] = tokens
|
| 97 |
+
if f_tag == 0.0 and to_tag == 0.0:
|
| 98 |
+
flag = True
|
| 99 |
+
text_data.append(text_dict)
|
| 100 |
+
else:
|
| 101 |
+
try:
|
| 102 |
+
n_motion = motion[int(f_tag*fps) : int(to_tag*fps)]
|
| 103 |
+
if (len(n_motion)) < min_motion_len or (len(n_motion) >= 200):
|
| 104 |
+
continue
|
| 105 |
+
new_name = random.choice('ABCDEFGHIJKLMNOPQRSTUVW') + '_' + name
|
| 106 |
+
while new_name in data_dict:
|
| 107 |
+
new_name = random.choice('ABCDEFGHIJKLMNOPQRSTUVW') + '_' + name
|
| 108 |
+
data_dict[new_name] = {'motion': n_motion,
|
| 109 |
+
'length': len(n_motion),
|
| 110 |
+
'text':[text_dict]}
|
| 111 |
+
new_name_list.append(new_name)
|
| 112 |
+
length_list.append(len(n_motion))
|
| 113 |
+
except:
|
| 114 |
+
print(line_split)
|
| 115 |
+
print(line_split[2], line_split[3], f_tag, to_tag, name)
|
| 116 |
+
# break
|
| 117 |
+
|
| 118 |
+
if flag:
|
| 119 |
+
data_dict[name] = {'motion': motion,
|
| 120 |
+
'length': len(motion),
|
| 121 |
+
'text': text_data}
|
| 122 |
+
new_name_list.append(name)
|
| 123 |
+
length_list.append(len(motion))
|
| 124 |
+
except Exception as e:
|
| 125 |
+
# print(e)
|
| 126 |
+
pass
|
| 127 |
+
|
| 128 |
+
name_list, length_list = zip(*sorted(zip(new_name_list, length_list), key=lambda x: x[1]))
|
| 129 |
+
self.mean = mean
|
| 130 |
+
self.std = std
|
| 131 |
+
self.length_arr = np.array(length_list)
|
| 132 |
+
self.data_dict = data_dict
|
| 133 |
+
self.name_list = name_list
|
| 134 |
+
self.reset_max_len(self.max_length)
|
| 135 |
+
|
| 136 |
+
def reset_max_len(self, length):
|
| 137 |
+
assert length <= self.max_motion_length
|
| 138 |
+
self.pointer = np.searchsorted(self.length_arr, length)
|
| 139 |
+
print("Pointer Pointing at %d"%self.pointer)
|
| 140 |
+
self.max_length = length
|
| 141 |
+
|
| 142 |
+
def inv_transform(self, data):
|
| 143 |
+
return data * self.std + self.mean
|
| 144 |
+
|
| 145 |
+
def forward_transform(self, data):
|
| 146 |
+
return (data - self.mean) / self.std
|
| 147 |
+
|
| 148 |
+
def __len__(self):
|
| 149 |
+
return len(self.data_dict) - self.pointer
|
| 150 |
+
|
| 151 |
+
def __getitem__(self, item):
|
| 152 |
+
idx = self.pointer + item
|
| 153 |
+
name = self.name_list[idx]
|
| 154 |
+
data = self.data_dict[name]
|
| 155 |
+
# data = self.data_dict[self.name_list[idx]]
|
| 156 |
+
motion, m_length, text_list = data['motion'], data['length'], data['text']
|
| 157 |
+
# Randomly select a caption
|
| 158 |
+
text_data = random.choice(text_list)
|
| 159 |
+
caption, tokens, caption_perb = text_data['caption'], text_data['tokens'], text_data['caption_perb']
|
| 160 |
+
|
| 161 |
+
if len(tokens) < self.max_text_len:
|
| 162 |
+
# pad with "unk"
|
| 163 |
+
tokens = ['sos/OTHER'] + tokens + ['eos/OTHER']
|
| 164 |
+
sent_len = len(tokens)
|
| 165 |
+
tokens = tokens + ['unk/OTHER'] * (self.max_text_len + 2 - sent_len)
|
| 166 |
+
else:
|
| 167 |
+
# crop
|
| 168 |
+
tokens = tokens[:self.max_text_len]
|
| 169 |
+
tokens = ['sos/OTHER'] + tokens + ['eos/OTHER']
|
| 170 |
+
sent_len = len(tokens)
|
| 171 |
+
pos_one_hots = []
|
| 172 |
+
word_embeddings = []
|
| 173 |
+
for token in tokens:
|
| 174 |
+
word_emb, pos_oh = self.w_vectorizer[token]
|
| 175 |
+
pos_one_hots.append(pos_oh[None, :])
|
| 176 |
+
word_embeddings.append(word_emb[None, :])
|
| 177 |
+
pos_one_hots = np.concatenate(pos_one_hots, axis=0)
|
| 178 |
+
word_embeddings = np.concatenate(word_embeddings, axis=0)
|
| 179 |
+
|
| 180 |
+
if self.unit_length < 10:
|
| 181 |
+
coin2 = np.random.choice(['single', 'single', 'double'])
|
| 182 |
+
else:
|
| 183 |
+
coin2 = 'single'
|
| 184 |
+
|
| 185 |
+
if coin2 == 'double':
|
| 186 |
+
m_length = (m_length // self.unit_length - 1) * self.unit_length
|
| 187 |
+
elif coin2 == 'single':
|
| 188 |
+
m_length = (m_length // self.unit_length) * self.unit_length
|
| 189 |
+
idx = random.randint(0, len(motion) - m_length)
|
| 190 |
+
motion = motion[idx:idx+m_length]
|
| 191 |
+
|
| 192 |
+
"Z Normalization"
|
| 193 |
+
motion = (motion - self.mean) / self.std
|
| 194 |
+
|
| 195 |
+
if m_length < self.max_motion_length:
|
| 196 |
+
motion = np.concatenate([motion,
|
| 197 |
+
np.zeros((self.max_motion_length - m_length, motion.shape[1]))
|
| 198 |
+
], axis=0)
|
| 199 |
+
|
| 200 |
+
return word_embeddings, pos_one_hots, caption, caption_perb, sent_len, motion, m_length, '_'.join(tokens), name
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def DATALoader(dataset_name, is_test,
|
| 206 |
+
batch_size, w_vectorizer,
|
| 207 |
+
num_workers = 8, unit_length = 4) :
|
| 208 |
+
|
| 209 |
+
val_loader = torch.utils.data.DataLoader(Text2MotionDataset(dataset_name, is_test, w_vectorizer, unit_length=unit_length),
|
| 210 |
+
batch_size,
|
| 211 |
+
shuffle = True,
|
| 212 |
+
num_workers=num_workers,
|
| 213 |
+
collate_fn=collate_fn,
|
| 214 |
+
drop_last = True)
|
| 215 |
+
return val_loader
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 219 |
+
|
| 220 |
+
def DATALoader_ddp(dataset_name, is_test,
|
| 221 |
+
batch_size, w_vectorizer,
|
| 222 |
+
num_workers = 8, unit_length = 4):
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
val_dataset = Text2MotionDataset(dataset_name, is_test, w_vectorizer, unit_length=unit_length)
|
| 226 |
+
|
| 227 |
+
val_sampler = DistributedSampler(val_dataset)
|
| 228 |
+
|
| 229 |
+
val_loader = torch.utils.data.DataLoader(val_dataset,
|
| 230 |
+
batch_size,
|
| 231 |
+
num_workers=num_workers,
|
| 232 |
+
collate_fn=collate_fn,
|
| 233 |
+
drop_last = True,
|
| 234 |
+
sampler=val_sampler)
|
| 235 |
+
return val_loader
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def cycle(iterable):
|
| 239 |
+
while True:
|
| 240 |
+
for x in iterable:
|
| 241 |
+
yield x
|
dataset/dataset_TM_train.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import options.option_transformer as option_trans
|
| 11 |
+
args = option_trans.get_args_parser()
|
| 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, feat_bias = 5, unit_length = 4, codebook_size = 1024, tokenizer_name=None,method=None):
|
| 21 |
+
|
| 22 |
+
self.max_length = 64
|
| 23 |
+
self.pointer = 0
|
| 24 |
+
self.dataset_name = dataset_name
|
| 25 |
+
|
| 26 |
+
self.unit_length = unit_length
|
| 27 |
+
# self.mot_start_idx = codebook_size
|
| 28 |
+
self.mot_end_idx = codebook_size
|
| 29 |
+
self.mot_pad_idx = codebook_size + 1
|
| 30 |
+
self.method=method
|
| 31 |
+
if dataset_name == 't2m':
|
| 32 |
+
self.data_root = './dataset/HumanML3D'
|
| 33 |
+
self.motion_dir = pjoin(self.data_root, 'new_joint_vecs')
|
| 34 |
+
self.text_dir = pjoin(self.data_root, 'texts')
|
| 35 |
+
self.joints_num = 22
|
| 36 |
+
radius = 4
|
| 37 |
+
fps = 20
|
| 38 |
+
self.max_motion_length = 26 if unit_length == 8 else 51
|
| 39 |
+
dim_pose = 263
|
| 40 |
+
kinematic_chain = paramUtil.t2m_kinematic_chain
|
| 41 |
+
elif dataset_name == 'kit':
|
| 42 |
+
self.data_root = './dataset/KIT-ML'
|
| 43 |
+
self.motion_dir = pjoin(self.data_root, 'new_joint_vecs')
|
| 44 |
+
self.text_dir = pjoin(self.data_root, 'texts')
|
| 45 |
+
self.joints_num = 21
|
| 46 |
+
radius = 240 * 8
|
| 47 |
+
fps = 12.5
|
| 48 |
+
dim_pose = 251
|
| 49 |
+
self.max_motion_length = 26 if unit_length == 8 else 51
|
| 50 |
+
kinematic_chain = paramUtil.kit_kinematic_chain
|
| 51 |
+
|
| 52 |
+
split_file = pjoin(self.data_root, 'train.txt')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
id_list = []
|
| 56 |
+
with cs.open(split_file, 'r') as f:
|
| 57 |
+
for line in f.readlines():
|
| 58 |
+
id_list.append(line.strip())
|
| 59 |
+
|
| 60 |
+
new_name_list = []
|
| 61 |
+
data_dict = {}
|
| 62 |
+
if self.method=='adv':
|
| 63 |
+
|
| 64 |
+
pass
|
| 65 |
+
for name in tqdm(id_list):
|
| 66 |
+
try:
|
| 67 |
+
m_token_list = np.load(pjoin(self.data_root, tokenizer_name, '%s.npy'%name))
|
| 68 |
+
|
| 69 |
+
# Read text
|
| 70 |
+
with cs.open(pjoin(self.text_dir, name + '.txt')) as f:
|
| 71 |
+
text_data = []
|
| 72 |
+
flag = False
|
| 73 |
+
lines = f.readlines()
|
| 74 |
+
|
| 75 |
+
for line in lines:
|
| 76 |
+
try:
|
| 77 |
+
text_dict = {}
|
| 78 |
+
line_split = line.strip().split('#')
|
| 79 |
+
caption = line_split[0]
|
| 80 |
+
txt_perb = line_split[-1]
|
| 81 |
+
t_tokens = line_split[1].split(' ')
|
| 82 |
+
f_tag = float(line_split[2])
|
| 83 |
+
to_tag = float(line_split[3])
|
| 84 |
+
f_tag = 0.0 if np.isnan(f_tag) else f_tag
|
| 85 |
+
to_tag = 0.0 if np.isnan(to_tag) else to_tag
|
| 86 |
+
|
| 87 |
+
text_dict['caption'] = caption
|
| 88 |
+
text_dict['tokens'] = t_tokens
|
| 89 |
+
text_dict['caption_perb'] = txt_perb
|
| 90 |
+
|
| 91 |
+
if f_tag == 0.0 and to_tag == 0.0:
|
| 92 |
+
flag = True
|
| 93 |
+
text_data.append(text_dict)
|
| 94 |
+
else:
|
| 95 |
+
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)]
|
| 96 |
+
|
| 97 |
+
if len(m_token_list_new) == 0:
|
| 98 |
+
continue
|
| 99 |
+
new_name = '%s_%f_%f'%(name, f_tag, to_tag)
|
| 100 |
+
|
| 101 |
+
data_dict[new_name] = {'m_token_list': m_token_list_new,
|
| 102 |
+
'text':[text_dict]}
|
| 103 |
+
new_name_list.append(new_name)
|
| 104 |
+
except:
|
| 105 |
+
pass
|
| 106 |
+
|
| 107 |
+
if flag:
|
| 108 |
+
data_dict[name] = {'m_token_list': m_token_list,
|
| 109 |
+
'text':text_data}
|
| 110 |
+
new_name_list.append(name)
|
| 111 |
+
except:
|
| 112 |
+
pass
|
| 113 |
+
self.data_dict = data_dict
|
| 114 |
+
self.name_list = new_name_list
|
| 115 |
+
|
| 116 |
+
def __len__(self):
|
| 117 |
+
return len(self.data_dict)
|
| 118 |
+
|
| 119 |
+
def __getitem__(self, item):
|
| 120 |
+
data = self.data_dict[self.name_list[item]]
|
| 121 |
+
m_token_list, text_list = data['m_token_list'], data['text']
|
| 122 |
+
m_tokens = random.choice(m_token_list)
|
| 123 |
+
|
| 124 |
+
text_data = random.choice(text_list)
|
| 125 |
+
caption,caption_perb= text_data['caption'], text_data['caption_perb']
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
coin = np.random.choice([False, False, True])
|
| 129 |
+
# print(len(m_tokens))
|
| 130 |
+
if coin:
|
| 131 |
+
# drop one token at the head or tail
|
| 132 |
+
coin2 = np.random.choice([True, False])
|
| 133 |
+
if coin2:
|
| 134 |
+
m_tokens = m_tokens[:-1]
|
| 135 |
+
else:
|
| 136 |
+
m_tokens = m_tokens[1:]
|
| 137 |
+
m_tokens_len = m_tokens.shape[0]
|
| 138 |
+
|
| 139 |
+
if m_tokens_len+1 < self.max_motion_length:
|
| 140 |
+
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)
|
| 141 |
+
else:
|
| 142 |
+
m_tokens = np.concatenate([m_tokens, np.ones((1), dtype=int) * self.mot_end_idx], axis=0)
|
| 143 |
+
|
| 144 |
+
return caption,caption_perb, m_tokens.reshape(-1), m_tokens_len
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def DATALoader(dataset_name,
|
| 150 |
+
batch_size, codebook_size, tokenizer_name, unit_length=4,
|
| 151 |
+
num_workers = 0) :
|
| 152 |
+
|
| 153 |
+
train_loader = torch.utils.data.DataLoader(Text2MotionDataset(dataset_name, codebook_size = codebook_size, tokenizer_name = tokenizer_name, unit_length=unit_length),
|
| 154 |
+
batch_size,
|
| 155 |
+
shuffle=False,
|
| 156 |
+
num_workers=num_workers,
|
| 157 |
+
#collate_fn=collate_fn,
|
| 158 |
+
drop_last = True)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
return train_loader
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 165 |
+
|
| 166 |
+
def DATALoader_ddp(dataset_name,
|
| 167 |
+
batch_size, codebook_size, tokenizer_name, unit_length=4,
|
| 168 |
+
num_workers = 0) :
|
| 169 |
+
|
| 170 |
+
dataset = Text2MotionDataset(dataset_name, codebook_size = codebook_size, tokenizer_name = tokenizer_name, unit_length=unit_length)
|
| 171 |
+
train_sampler = DistributedSampler(dataset)
|
| 172 |
+
train_loader = torch.utils.data.DataLoader(dataset,
|
| 173 |
+
batch_size,
|
| 174 |
+
num_workers=num_workers,
|
| 175 |
+
#collate_fn=collate_fn,
|
| 176 |
+
drop_last = True,
|
| 177 |
+
sampler=train_sampler)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
return train_loader
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def cycle(iterable):
|
| 184 |
+
while True:
|
| 185 |
+
for x in iterable:
|
| 186 |
+
yield x
|
| 187 |
+
|
| 188 |
+
|
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
|
dataset/dataset_tokenize.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 63 |
+
continue
|
| 64 |
+
|
| 65 |
+
data_dict[name] = {'motion': motion,
|
| 66 |
+
'length': len(motion),
|
| 67 |
+
'name': name}
|
| 68 |
+
new_name_list.append(name)
|
| 69 |
+
length_list.append(len(motion))
|
| 70 |
+
except:
|
| 71 |
+
# Some motion may not exist in KIT dataset
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
self.mean = mean
|
| 76 |
+
self.std = std
|
| 77 |
+
self.length_arr = np.array(length_list)
|
| 78 |
+
self.data_dict = data_dict
|
| 79 |
+
self.name_list = new_name_list
|
| 80 |
+
|
| 81 |
+
def inv_transform(self, data):
|
| 82 |
+
return data * self.std + self.mean
|
| 83 |
+
|
| 84 |
+
def __len__(self):
|
| 85 |
+
return len(self.data_dict)
|
| 86 |
+
|
| 87 |
+
def __getitem__(self, item):
|
| 88 |
+
name = self.name_list[item]
|
| 89 |
+
data = self.data_dict[name]
|
| 90 |
+
motion, m_length = data['motion'], data['length']
|
| 91 |
+
|
| 92 |
+
m_length = (m_length // self.unit_length) * self.unit_length
|
| 93 |
+
|
| 94 |
+
idx = random.randint(0, len(motion) - m_length)
|
| 95 |
+
motion = motion[idx:idx+m_length]
|
| 96 |
+
|
| 97 |
+
"Z Normalization"
|
| 98 |
+
motion = (motion - self.mean) / self.std
|
| 99 |
+
|
| 100 |
+
return motion, name
|
| 101 |
+
|
| 102 |
+
def DATALoader(dataset_name,
|
| 103 |
+
batch_size = 4,
|
| 104 |
+
num_workers = 8, unit_length = 4) :
|
| 105 |
+
|
| 106 |
+
train_loader = torch.utils.data.DataLoader(VQMotionDataset(dataset_name, unit_length=unit_length),
|
| 107 |
+
batch_size,
|
| 108 |
+
shuffle=True,
|
| 109 |
+
num_workers=num_workers,
|
| 110 |
+
#collate_fn=collate_fn,
|
| 111 |
+
drop_last = True)
|
| 112 |
+
|
| 113 |
+
return train_loader
|
| 114 |
+
|
| 115 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 116 |
+
|
| 117 |
+
# def DATALoader_ddp(dataset_name,
|
| 118 |
+
# batch_size = 4,
|
| 119 |
+
# num_workers = 8, unit_length = 4) :
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# dataset = VQMotionDataset(dataset_name, unit_length=unit_length)
|
| 123 |
+
# train_sampler = DistributedSampler(dataset)
|
| 124 |
+
|
| 125 |
+
# train_loader = torch.utils.data.DataLoader(dataset,
|
| 126 |
+
# batch_size=batch_size,
|
| 127 |
+
# shuffle=False,
|
| 128 |
+
# num_workers=num_workers,
|
| 129 |
+
# sampler=train_sampler)
|
| 130 |
+
|
| 131 |
+
# return train_loader
|
| 132 |
+
|
| 133 |
+
def cycle(iterable):
|
| 134 |
+
while True:
|
| 135 |
+
for x in iterable:
|
| 136 |
+
yield x
|
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/1KNU8CsMAnxFrwopKBBkC8jEULGLPBHQp/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!"
|
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!"
|
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!"
|
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!"
|
models/__pycache__/encdec.cpython-38.pyc
ADDED
|
Binary file (2.08 kB). View file
|
|
|
models/__pycache__/encdec.cpython-39.pyc
ADDED
|
Binary file (2.09 kB). View file
|
|
|
models/__pycache__/evaluator_wrapper.cpython-38.pyc
ADDED
|
Binary file (2.9 kB). View file
|
|
|
models/__pycache__/evaluator_wrapper.cpython-39.pyc
ADDED
|
Binary file (2.96 kB). View file
|
|
|
models/__pycache__/modules.cpython-38.pyc
ADDED
|
Binary file (3.54 kB). View file
|
|
|
models/__pycache__/modules.cpython-39.pyc
ADDED
|
Binary file (3.57 kB). View file
|
|
|
models/__pycache__/pos_encoding.cpython-38.pyc
ADDED
|
Binary file (1.75 kB). View file
|
|
|
models/__pycache__/pos_encoding.cpython-39.pyc
ADDED
|
Binary file (1.75 kB). View file
|
|
|
models/__pycache__/quantize_cnn.cpython-38.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
models/__pycache__/quantize_cnn.cpython-39.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
models/__pycache__/resnet.cpython-38.pyc
ADDED
|
Binary file (2.78 kB). View file
|
|
|
models/__pycache__/resnet.cpython-39.pyc
ADDED
|
Binary file (2.78 kB). View file
|
|
|
models/__pycache__/rotation2xyz.cpython-38.pyc
ADDED
|
Binary file (2.39 kB). View file
|
|
|
models/__pycache__/smpl.cpython-38.pyc
ADDED
|
Binary file (3.37 kB). View file
|
|
|
models/__pycache__/t2m_trans.cpython-38.pyc
ADDED
|
Binary file (7.66 kB). View file
|
|
|
models/__pycache__/t2m_trans.cpython-39.pyc
ADDED
|
Binary file (7.58 kB). View file
|
|
|
models/__pycache__/vqvae.cpython-38.pyc
ADDED
|
Binary file (3.46 kB). View file
|
|
|
models/__pycache__/vqvae.cpython-39.pyc
ADDED
|
Binary file (3.47 kB). View file
|
|
|
models/encdec.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
from models.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 |
+
|
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
|
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,enforce_sorted=False)
|
| 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)
|
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 |
+
|
models/quantize_cnn.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
self.register_buffer('codebook', torch.zeros(self.nb_code, self.code_dim).cuda())
|
| 19 |
+
|
| 20 |
+
def _tile(self, x):
|
| 21 |
+
nb_code_x, code_dim = x.shape
|
| 22 |
+
if nb_code_x < self.nb_code:
|
| 23 |
+
n_repeats = (self.nb_code + nb_code_x - 1) // nb_code_x
|
| 24 |
+
std = 0.01 / np.sqrt(code_dim)
|
| 25 |
+
out = x.repeat(n_repeats, 1)
|
| 26 |
+
out = out + torch.randn_like(out) * std
|
| 27 |
+
else :
|
| 28 |
+
out = x
|
| 29 |
+
return out
|
| 30 |
+
|
| 31 |
+
def init_codebook(self, x):
|
| 32 |
+
out = self._tile(x)
|
| 33 |
+
self.codebook = out[:self.nb_code]
|
| 34 |
+
self.code_sum = self.codebook.clone()
|
| 35 |
+
self.code_count = torch.ones(self.nb_code, device=self.codebook.device)
|
| 36 |
+
self.init = True
|
| 37 |
+
|
| 38 |
+
@torch.no_grad()
|
| 39 |
+
def compute_perplexity(self, code_idx) :
|
| 40 |
+
# Calculate new centres
|
| 41 |
+
code_onehot = torch.zeros(self.nb_code, code_idx.shape[0], device=code_idx.device) # nb_code, N * L
|
| 42 |
+
code_onehot.scatter_(0, code_idx.view(1, code_idx.shape[0]), 1)
|
| 43 |
+
|
| 44 |
+
code_count = code_onehot.sum(dim=-1) # nb_code
|
| 45 |
+
prob = code_count / torch.sum(code_count)
|
| 46 |
+
perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
|
| 47 |
+
return perplexity
|
| 48 |
+
|
| 49 |
+
@torch.no_grad()
|
| 50 |
+
def update_codebook(self, x, code_idx):
|
| 51 |
+
|
| 52 |
+
code_onehot = torch.zeros(self.nb_code, x.shape[0], device=x.device) # nb_code, N * L
|
| 53 |
+
code_onehot.scatter_(0, code_idx.view(1, x.shape[0]), 1)
|
| 54 |
+
|
| 55 |
+
code_sum = torch.matmul(code_onehot, x) # nb_code, w
|
| 56 |
+
code_count = code_onehot.sum(dim=-1) # nb_code
|
| 57 |
+
|
| 58 |
+
out = self._tile(x)
|
| 59 |
+
code_rand = out[:self.nb_code]
|
| 60 |
+
|
| 61 |
+
# Update centres
|
| 62 |
+
self.code_sum = self.mu * self.code_sum + (1. - self.mu) * code_sum # w, nb_code
|
| 63 |
+
self.code_count = self.mu * self.code_count + (1. - self.mu) * code_count # nb_code
|
| 64 |
+
|
| 65 |
+
usage = (self.code_count.view(self.nb_code, 1) >= 1.0).float()
|
| 66 |
+
code_update = self.code_sum.view(self.nb_code, self.code_dim) / self.code_count.view(self.nb_code, 1)
|
| 67 |
+
|
| 68 |
+
self.codebook = usage * code_update + (1 - usage) * code_rand
|
| 69 |
+
prob = code_count / torch.sum(code_count)
|
| 70 |
+
perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
return perplexity
|
| 74 |
+
|
| 75 |
+
def preprocess(self, x):
|
| 76 |
+
# NCT -> NTC -> [NT, C]
|
| 77 |
+
x = x.permute(0, 2, 1).contiguous()
|
| 78 |
+
x = x.view(-1, x.shape[-1])
|
| 79 |
+
return x
|
| 80 |
+
|
| 81 |
+
def quantize(self, x):
|
| 82 |
+
# Calculate latent code x_l
|
| 83 |
+
k_w = self.codebook.t()
|
| 84 |
+
distance = torch.sum(x ** 2, dim=-1, keepdim=True) - 2 * torch.matmul(x, k_w) + torch.sum(k_w ** 2, dim=0,
|
| 85 |
+
keepdim=True) # (N * L, b)
|
| 86 |
+
_, code_idx = torch.min(distance, dim=-1)
|
| 87 |
+
return code_idx
|
| 88 |
+
|
| 89 |
+
def dequantize(self, code_idx):
|
| 90 |
+
x = F.embedding(code_idx, self.codebook)
|
| 91 |
+
return x
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def forward(self, x):
|
| 95 |
+
N, width, T = x.shape
|
| 96 |
+
|
| 97 |
+
# Preprocess
|
| 98 |
+
x = self.preprocess(x)
|
| 99 |
+
|
| 100 |
+
# Init codebook if not inited
|
| 101 |
+
if self.training and not self.init:
|
| 102 |
+
self.init_codebook(x)
|
| 103 |
+
|
| 104 |
+
# quantize and dequantize through bottleneck
|
| 105 |
+
code_idx = self.quantize(x)
|
| 106 |
+
x_d = self.dequantize(code_idx)
|
| 107 |
+
|
| 108 |
+
# Update embeddings
|
| 109 |
+
if self.training:
|
| 110 |
+
perplexity = self.update_codebook(x, code_idx)
|
| 111 |
+
else :
|
| 112 |
+
perplexity = self.compute_perplexity(code_idx)
|
| 113 |
+
|
| 114 |
+
# Loss
|
| 115 |
+
commit_loss = F.mse_loss(x, x_d.detach())
|
| 116 |
+
|
| 117 |
+
# Passthrough
|
| 118 |
+
x_d = x + (x_d - x).detach()
|
| 119 |
+
|
| 120 |
+
# Postprocess
|
| 121 |
+
x_d = x_d.view(N, T, -1).permute(0, 2, 1).contiguous() #(N, DIM, T)
|
| 122 |
+
|
| 123 |
+
return x_d, commit_loss, perplexity
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class Quantizer(nn.Module):
|
| 128 |
+
def __init__(self, n_e, e_dim, beta):
|
| 129 |
+
super(Quantizer, self).__init__()
|
| 130 |
+
|
| 131 |
+
self.e_dim = e_dim
|
| 132 |
+
self.n_e = n_e
|
| 133 |
+
self.beta = beta
|
| 134 |
+
|
| 135 |
+
self.embedding = nn.Embedding(self.n_e, self.e_dim)
|
| 136 |
+
self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)
|
| 137 |
+
|
| 138 |
+
def forward(self, z):
|
| 139 |
+
|
| 140 |
+
N, width, T = z.shape
|
| 141 |
+
z = self.preprocess(z)
|
| 142 |
+
assert z.shape[-1] == self.e_dim
|
| 143 |
+
z_flattened = z.contiguous().view(-1, self.e_dim)
|
| 144 |
+
|
| 145 |
+
# B x V
|
| 146 |
+
d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
|
| 147 |
+
torch.sum(self.embedding.weight**2, dim=1) - 2 * \
|
| 148 |
+
torch.matmul(z_flattened, self.embedding.weight.t())
|
| 149 |
+
# B x 1
|
| 150 |
+
min_encoding_indices = torch.argmin(d, dim=1)
|
| 151 |
+
z_q = self.embedding(min_encoding_indices).view(z.shape)
|
| 152 |
+
|
| 153 |
+
# compute loss for embedding
|
| 154 |
+
loss = torch.mean((z_q - z.detach())**2) + self.beta * \
|
| 155 |
+
torch.mean((z_q.detach() - z)**2)
|
| 156 |
+
|
| 157 |
+
# preserve gradients
|
| 158 |
+
z_q = z + (z_q - z).detach()
|
| 159 |
+
z_q = z_q.view(N, T, -1).permute(0, 2, 1).contiguous() #(N, DIM, T)
|
| 160 |
+
|
| 161 |
+
min_encodings = F.one_hot(min_encoding_indices, self.n_e).type(z.dtype)
|
| 162 |
+
e_mean = torch.mean(min_encodings, dim=0)
|
| 163 |
+
perplexity = torch.exp(-torch.sum(e_mean*torch.log(e_mean + 1e-10)))
|
| 164 |
+
return z_q, loss, perplexity
|
| 165 |
+
|
| 166 |
+
def quantize(self, z):
|
| 167 |
+
|
| 168 |
+
assert z.shape[-1] == self.e_dim
|
| 169 |
+
|
| 170 |
+
# B x V
|
| 171 |
+
d = torch.sum(z ** 2, dim=1, keepdim=True) + \
|
| 172 |
+
torch.sum(self.embedding.weight ** 2, dim=1) - 2 * \
|
| 173 |
+
torch.matmul(z, self.embedding.weight.t())
|
| 174 |
+
# B x 1
|
| 175 |
+
min_encoding_indices = torch.argmin(d, dim=1)
|
| 176 |
+
return min_encoding_indices
|
| 177 |
+
|
| 178 |
+
def dequantize(self, indices):
|
| 179 |
+
|
| 180 |
+
index_flattened = indices.view(-1)
|
| 181 |
+
z_q = self.embedding(index_flattened)
|
| 182 |
+
z_q = z_q.view(indices.shape + (self.e_dim, )).contiguous()
|
| 183 |
+
return z_q
|
| 184 |
+
|
| 185 |
+
def preprocess(self, x):
|
| 186 |
+
# NCT -> NTC -> [NT, C]
|
| 187 |
+
x = x.permute(0, 2, 1).contiguous()
|
| 188 |
+
x = x.view(-1, x.shape[-1])
|
| 189 |
+
return x
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class QuantizeReset(nn.Module):
|
| 194 |
+
def __init__(self, nb_code, code_dim, args):
|
| 195 |
+
super().__init__()
|
| 196 |
+
self.nb_code = nb_code
|
| 197 |
+
self.code_dim = code_dim
|
| 198 |
+
self.reset_codebook()
|
| 199 |
+
self.codebook = nn.Parameter(torch.randn(nb_code, code_dim))
|
| 200 |
+
|
| 201 |
+
def reset_codebook(self):
|
| 202 |
+
self.init = False
|
| 203 |
+
self.code_count = None
|
| 204 |
+
|
| 205 |
+
def _tile(self, x):
|
| 206 |
+
nb_code_x, code_dim = x.shape
|
| 207 |
+
if nb_code_x < self.nb_code:
|
| 208 |
+
n_repeats = (self.nb_code + nb_code_x - 1) // nb_code_x
|
| 209 |
+
std = 0.01 / np.sqrt(code_dim)
|
| 210 |
+
out = x.repeat(n_repeats, 1)
|
| 211 |
+
out = out + torch.randn_like(out) * std
|
| 212 |
+
else :
|
| 213 |
+
out = x
|
| 214 |
+
return out
|
| 215 |
+
|
| 216 |
+
def init_codebook(self, x):
|
| 217 |
+
out = self._tile(x)
|
| 218 |
+
self.codebook = nn.Parameter(out[:self.nb_code])
|
| 219 |
+
self.code_count = torch.ones(self.nb_code, device=self.codebook.device)
|
| 220 |
+
self.init = True
|
| 221 |
+
|
| 222 |
+
@torch.no_grad()
|
| 223 |
+
def compute_perplexity(self, code_idx) :
|
| 224 |
+
# Calculate new centres
|
| 225 |
+
code_onehot = torch.zeros(self.nb_code, code_idx.shape[0], device=code_idx.device) # nb_code, N * L
|
| 226 |
+
code_onehot.scatter_(0, code_idx.view(1, code_idx.shape[0]), 1)
|
| 227 |
+
|
| 228 |
+
code_count = code_onehot.sum(dim=-1) # nb_code
|
| 229 |
+
prob = code_count / torch.sum(code_count)
|
| 230 |
+
perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
|
| 231 |
+
return perplexity
|
| 232 |
+
|
| 233 |
+
def update_codebook(self, x, code_idx):
|
| 234 |
+
|
| 235 |
+
code_onehot = torch.zeros(self.nb_code, x.shape[0], device=x.device) # nb_code, N * L
|
| 236 |
+
code_onehot.scatter_(0, code_idx.view(1, x.shape[0]), 1)
|
| 237 |
+
|
| 238 |
+
code_count = code_onehot.sum(dim=-1) # nb_code
|
| 239 |
+
|
| 240 |
+
out = self._tile(x)
|
| 241 |
+
code_rand = out[:self.nb_code]
|
| 242 |
+
|
| 243 |
+
# Update centres
|
| 244 |
+
self.code_count = code_count # nb_code
|
| 245 |
+
usage = (self.code_count.view(self.nb_code, 1) >= 1.0).float()
|
| 246 |
+
|
| 247 |
+
self.codebook.data = usage * self.codebook.data + (1 - usage) * code_rand
|
| 248 |
+
prob = code_count / torch.sum(code_count)
|
| 249 |
+
perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
return perplexity
|
| 253 |
+
|
| 254 |
+
def preprocess(self, x):
|
| 255 |
+
# NCT -> NTC -> [NT, C]
|
| 256 |
+
x = x.permute(0, 2, 1).contiguous()
|
| 257 |
+
x = x.view(-1, x.shape[-1])
|
| 258 |
+
return x
|
| 259 |
+
|
| 260 |
+
def quantize(self, x):
|
| 261 |
+
# Calculate latent code x_l
|
| 262 |
+
k_w = self.codebook.t()
|
| 263 |
+
distance = torch.sum(x ** 2, dim=-1, keepdim=True) - 2 * torch.matmul(x, k_w) + torch.sum(k_w ** 2, dim=0,
|
| 264 |
+
keepdim=True) # (N * L, b)
|
| 265 |
+
_, code_idx = torch.min(distance, dim=-1)
|
| 266 |
+
return code_idx
|
| 267 |
+
|
| 268 |
+
def dequantize(self, code_idx):
|
| 269 |
+
x = F.embedding(code_idx, self.codebook)
|
| 270 |
+
return x
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def forward(self, x):
|
| 274 |
+
N, width, T = x.shape
|
| 275 |
+
# Preprocess
|
| 276 |
+
x = self.preprocess(x)
|
| 277 |
+
# Init codebook if not inited
|
| 278 |
+
if self.training and not self.init:
|
| 279 |
+
self.init_codebook(x)
|
| 280 |
+
# quantize and dequantize through bottleneck
|
| 281 |
+
code_idx = self.quantize(x)
|
| 282 |
+
x_d = self.dequantize(code_idx)
|
| 283 |
+
# Update embeddings
|
| 284 |
+
if self.training:
|
| 285 |
+
perplexity = self.update_codebook(x, code_idx)
|
| 286 |
+
else :
|
| 287 |
+
perplexity = self.compute_perplexity(code_idx)
|
| 288 |
+
|
| 289 |
+
# Loss
|
| 290 |
+
commit_loss = F.mse_loss(x, x_d.detach())
|
| 291 |
+
|
| 292 |
+
# Passthrough
|
| 293 |
+
x_d = x + (x_d - x).detach()
|
| 294 |
+
|
| 295 |
+
# Postprocess
|
| 296 |
+
x_d = x_d.view(N, T, -1).permute(0, 2, 1).contiguous() #(N, DIM, T)
|
| 297 |
+
|
| 298 |
+
return x_d, commit_loss, perplexity
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class QuantizeEMA(nn.Module):
|
| 302 |
+
def __init__(self, nb_code, code_dim, args):
|
| 303 |
+
super().__init__()
|
| 304 |
+
self.nb_code = nb_code
|
| 305 |
+
self.code_dim = code_dim
|
| 306 |
+
self.mu = 0.99
|
| 307 |
+
self.reset_codebook()
|
| 308 |
+
|
| 309 |
+
def reset_codebook(self):
|
| 310 |
+
self.init = False
|
| 311 |
+
self.code_sum = None
|
| 312 |
+
self.code_count = None
|
| 313 |
+
self.register_buffer('codebook', torch.zeros(self.nb_code, self.code_dim).cuda())
|
| 314 |
+
|
| 315 |
+
def _tile(self, x):
|
| 316 |
+
nb_code_x, code_dim = x.shape
|
| 317 |
+
if nb_code_x < self.nb_code:
|
| 318 |
+
n_repeats = (self.nb_code + nb_code_x - 1) // nb_code_x
|
| 319 |
+
std = 0.01 / np.sqrt(code_dim)
|
| 320 |
+
out = x.repeat(n_repeats, 1)
|
| 321 |
+
out = out + torch.randn_like(out) * std
|
| 322 |
+
else :
|
| 323 |
+
out = x
|
| 324 |
+
return out
|
| 325 |
+
|
| 326 |
+
def init_codebook(self, x):
|
| 327 |
+
out = self._tile(x)
|
| 328 |
+
self.codebook = out[:self.nb_code]
|
| 329 |
+
self.code_sum = self.codebook.clone()
|
| 330 |
+
self.code_count = torch.ones(self.nb_code, device=self.codebook.device)
|
| 331 |
+
self.init = True
|
| 332 |
+
|
| 333 |
+
@torch.no_grad()
|
| 334 |
+
def compute_perplexity(self, code_idx) :
|
| 335 |
+
# Calculate new centres
|
| 336 |
+
code_onehot = torch.zeros(self.nb_code, code_idx.shape[0], device=code_idx.device) # nb_code, N * L
|
| 337 |
+
code_onehot.scatter_(0, code_idx.view(1, code_idx.shape[0]), 1)
|
| 338 |
+
|
| 339 |
+
code_count = code_onehot.sum(dim=-1) # nb_code
|
| 340 |
+
prob = code_count / torch.sum(code_count)
|
| 341 |
+
perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
|
| 342 |
+
return perplexity
|
| 343 |
+
|
| 344 |
+
@torch.no_grad()
|
| 345 |
+
def update_codebook(self, x, code_idx):
|
| 346 |
+
|
| 347 |
+
code_onehot = torch.zeros(self.nb_code, x.shape[0], device=x.device) # nb_code, N * L
|
| 348 |
+
code_onehot.scatter_(0, code_idx.view(1, x.shape[0]), 1)
|
| 349 |
+
|
| 350 |
+
code_sum = torch.matmul(code_onehot, x) # nb_code, w
|
| 351 |
+
code_count = code_onehot.sum(dim=-1) # nb_code
|
| 352 |
+
|
| 353 |
+
# Update centres
|
| 354 |
+
self.code_sum = self.mu * self.code_sum + (1. - self.mu) * code_sum # w, nb_code
|
| 355 |
+
self.code_count = self.mu * self.code_count + (1. - self.mu) * code_count # nb_code
|
| 356 |
+
|
| 357 |
+
code_update = self.code_sum.view(self.nb_code, self.code_dim) / self.code_count.view(self.nb_code, 1)
|
| 358 |
+
|
| 359 |
+
self.codebook = code_update
|
| 360 |
+
prob = code_count / torch.sum(code_count)
|
| 361 |
+
perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
|
| 362 |
+
|
| 363 |
+
return perplexity
|
| 364 |
+
|
| 365 |
+
def preprocess(self, x):
|
| 366 |
+
# NCT -> NTC -> [NT, C]
|
| 367 |
+
x = x.permute(0, 2, 1).contiguous()
|
| 368 |
+
x = x.view(-1, x.shape[-1])
|
| 369 |
+
return x
|
| 370 |
+
|
| 371 |
+
def quantize(self, x):
|
| 372 |
+
# Calculate latent code x_l
|
| 373 |
+
k_w = self.codebook.t()
|
| 374 |
+
distance = torch.sum(x ** 2, dim=-1, keepdim=True) - 2 * torch.matmul(x, k_w) + torch.sum(k_w ** 2, dim=0,
|
| 375 |
+
keepdim=True) # (N * L, b)
|
| 376 |
+
_, code_idx = torch.min(distance, dim=-1)
|
| 377 |
+
return code_idx
|
| 378 |
+
|
| 379 |
+
def dequantize(self, code_idx):
|
| 380 |
+
x = F.embedding(code_idx, self.codebook)
|
| 381 |
+
return x
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def forward(self, x):
|
| 385 |
+
N, width, T = x.shape
|
| 386 |
+
|
| 387 |
+
# Preprocess
|
| 388 |
+
x = self.preprocess(x)
|
| 389 |
+
|
| 390 |
+
# Init codebook if not inited
|
| 391 |
+
if self.training and not self.init:
|
| 392 |
+
self.init_codebook(x)
|
| 393 |
+
|
| 394 |
+
# quantize and dequantize through bottleneck
|
| 395 |
+
code_idx = self.quantize(x)
|
| 396 |
+
x_d = self.dequantize(code_idx)
|
| 397 |
+
|
| 398 |
+
# Update embeddings
|
| 399 |
+
if self.training:
|
| 400 |
+
perplexity = self.update_codebook(x, code_idx)
|
| 401 |
+
else :
|
| 402 |
+
perplexity = self.compute_perplexity(code_idx)
|
| 403 |
+
|
| 404 |
+
# Loss
|
| 405 |
+
commit_loss = F.mse_loss(x, x_d.detach())
|
| 406 |
+
|
| 407 |
+
# Passthrough
|
| 408 |
+
x_d = x + (x_d - x).detach()
|
| 409 |
+
|
| 410 |
+
# Postprocess
|
| 411 |
+
x_d = x_d.view(N, T, -1).permute(0, 2, 1).contiguous() #(N, DIM, T)
|
| 412 |
+
|
| 413 |
+
return x_d, commit_loss, perplexity
|
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)
|
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 utils.rotation_conversions as geometry
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from models.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
|
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 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
|
models/t2m_trans.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 models.pos_encoding as pos_encoding
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Text2Motion_Transformer(nn.Module):
|
| 12 |
+
|
| 13 |
+
def __init__(self,
|
| 14 |
+
num_vq=1024,
|
| 15 |
+
embed_dim=512,
|
| 16 |
+
clip_dim=512,
|
| 17 |
+
block_size=16,
|
| 18 |
+
num_layers=2,
|
| 19 |
+
n_head=8,
|
| 20 |
+
drop_out_rate=0.1,
|
| 21 |
+
fc_rate=4,
|
| 22 |
+
|
| 23 |
+
):
|
| 24 |
+
super().__init__()
|
| 25 |
+
self.trans_base = CrossCondTransBase(num_vq, embed_dim, clip_dim, block_size, num_layers, n_head, drop_out_rate, fc_rate)
|
| 26 |
+
self.trans_head = CrossCondTransHead(num_vq, embed_dim, block_size, num_layers, n_head, drop_out_rate, fc_rate)
|
| 27 |
+
self.block_size = block_size
|
| 28 |
+
self.num_vq = num_vq
|
| 29 |
+
|
| 30 |
+
def get_block_size(self):
|
| 31 |
+
return self.block_size
|
| 32 |
+
|
| 33 |
+
def forward(self, idxs, clip_feature):
|
| 34 |
+
feat = self.trans_base(idxs, clip_feature)
|
| 35 |
+
logits = self.trans_head(feat)
|
| 36 |
+
return logits
|
| 37 |
+
|
| 38 |
+
def sample(self, clip_feature, if_categorial=False,att=False):
|
| 39 |
+
for k in range(self.block_size):
|
| 40 |
+
if k == 0:
|
| 41 |
+
x = []
|
| 42 |
+
logits = self.forward(x, clip_feature)
|
| 43 |
+
if att==True:
|
| 44 |
+
return self.trans_base.blocks[0].get_attention_weights()
|
| 45 |
+
|
| 46 |
+
logits = logits[:, -1, :]
|
| 47 |
+
probs = F.softmax(logits, dim=-1)
|
| 48 |
+
|
| 49 |
+
else:
|
| 50 |
+
x = xs
|
| 51 |
+
logits = self.forward(x, clip_feature)
|
| 52 |
+
logits = logits[:, -1, :]
|
| 53 |
+
probs = F.softmax(logits, dim=-1)
|
| 54 |
+
if if_categorial:
|
| 55 |
+
dist = Categorical(probs)
|
| 56 |
+
idx = dist.sample()
|
| 57 |
+
if idx == self.num_vq:
|
| 58 |
+
break
|
| 59 |
+
idx = idx.unsqueeze(-1)
|
| 60 |
+
else:
|
| 61 |
+
_, idx = torch.topk(probs, k=1, dim=-1)
|
| 62 |
+
if idx[0] == self.num_vq:
|
| 63 |
+
break
|
| 64 |
+
# append to the sequence and continue
|
| 65 |
+
if k == 0:
|
| 66 |
+
xs = idx
|
| 67 |
+
else:
|
| 68 |
+
xs = torch.cat((xs, idx), dim=1)
|
| 69 |
+
|
| 70 |
+
if k == self.block_size - 1:
|
| 71 |
+
return xs[:, :-1]
|
| 72 |
+
return xs
|
| 73 |
+
|
| 74 |
+
class CausalCrossConditionalSelfAttention(nn.Module):
|
| 75 |
+
|
| 76 |
+
def __init__(self, embed_dim=512, block_size=16, n_head=8, drop_out_rate=0.1):
|
| 77 |
+
super().__init__()
|
| 78 |
+
assert embed_dim % 8 == 0
|
| 79 |
+
# key, query, value projections for all heads
|
| 80 |
+
self.key = nn.Linear(embed_dim, embed_dim)
|
| 81 |
+
self.query = nn.Linear(embed_dim, embed_dim)
|
| 82 |
+
self.value = nn.Linear(embed_dim, embed_dim)
|
| 83 |
+
|
| 84 |
+
self.attn_drop = nn.Dropout(drop_out_rate)
|
| 85 |
+
self.resid_drop = nn.Dropout(drop_out_rate)
|
| 86 |
+
|
| 87 |
+
self.proj = nn.Linear(embed_dim, embed_dim)
|
| 88 |
+
# causal mask to ensure that attention is only applied to the left in the input sequence
|
| 89 |
+
self.register_buffer("mask", torch.tril(torch.ones(block_size, block_size)).view(1, 1, block_size, block_size))
|
| 90 |
+
self.n_head = n_head
|
| 91 |
+
self.att=None
|
| 92 |
+
def forward(self, x):
|
| 93 |
+
B, T, C = x.size()
|
| 94 |
+
|
| 95 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
| 96 |
+
k = self.key(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
| 97 |
+
q = self.query(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
| 98 |
+
v = self.value(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
| 99 |
+
# causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
|
| 100 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
| 101 |
+
att = att.masked_fill(self.mask[:,:,:T,:T] == 0, float('-inf'))
|
| 102 |
+
att = F.softmax(att, dim=-1)
|
| 103 |
+
att = self.attn_drop(att)
|
| 104 |
+
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
|
| 105 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
| 106 |
+
self.att=att
|
| 107 |
+
# output projection
|
| 108 |
+
y = self.resid_drop(self.proj(y))
|
| 109 |
+
|
| 110 |
+
return y
|
| 111 |
+
|
| 112 |
+
def get_attention_weights(self):
|
| 113 |
+
return self.att
|
| 114 |
+
|
| 115 |
+
class Block(nn.Module):
|
| 116 |
+
|
| 117 |
+
def __init__(self, embed_dim=512, block_size=16, n_head=8, drop_out_rate=0.1, fc_rate=4,num_layers=-1,num=None):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.num_layers=num_layers
|
| 120 |
+
self.num=num
|
| 121 |
+
self.attn_weight=None
|
| 122 |
+
self.ln1 = nn.LayerNorm(embed_dim)
|
| 123 |
+
self.ln2 = nn.LayerNorm(embed_dim)
|
| 124 |
+
self.attn = CausalCrossConditionalSelfAttention(embed_dim, block_size, n_head, drop_out_rate)
|
| 125 |
+
self.mlp = nn.Sequential(
|
| 126 |
+
nn.Linear(embed_dim, fc_rate * embed_dim),
|
| 127 |
+
nn.GELU(),
|
| 128 |
+
nn.Linear(fc_rate * embed_dim, embed_dim),
|
| 129 |
+
nn.Dropout(drop_out_rate),
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
def forward(self, x):
|
| 133 |
+
x = x + self.attn(self.ln1(x))
|
| 134 |
+
if self.num==0:
|
| 135 |
+
self.attn_weight = self.attn.get_attention_weights()
|
| 136 |
+
x = x + self.mlp(self.ln2(x))
|
| 137 |
+
return x
|
| 138 |
+
def get_attention_weights(self):
|
| 139 |
+
return self.attn_weight
|
| 140 |
+
|
| 141 |
+
class CrossCondTransBase(nn.Module):
|
| 142 |
+
|
| 143 |
+
def __init__(self,
|
| 144 |
+
num_vq=1024,
|
| 145 |
+
embed_dim=512,
|
| 146 |
+
clip_dim=512,
|
| 147 |
+
block_size=16,
|
| 148 |
+
num_layers=2,
|
| 149 |
+
n_head=8,
|
| 150 |
+
drop_out_rate=0.1,
|
| 151 |
+
fc_rate=4,
|
| 152 |
+
):
|
| 153 |
+
super().__init__()
|
| 154 |
+
|
| 155 |
+
self.tok_emb = nn.Embedding(num_vq + 2, embed_dim)
|
| 156 |
+
self.cond_emb = nn.Linear(clip_dim, embed_dim)
|
| 157 |
+
self.pos_embedding = nn.Embedding(block_size, embed_dim)
|
| 158 |
+
self.drop = nn.Dropout(drop_out_rate)
|
| 159 |
+
# transformer block
|
| 160 |
+
self.blocks = nn.Sequential(*[Block(embed_dim, block_size, n_head, drop_out_rate, fc_rate,num=_) for _ in range(num_layers)])
|
| 161 |
+
self.pos_embed = pos_encoding.PositionEmbedding(block_size, embed_dim, 0.0, False)
|
| 162 |
+
|
| 163 |
+
self.block_size = block_size
|
| 164 |
+
self.first_att_weights = None
|
| 165 |
+
self.apply(self._init_weights)
|
| 166 |
+
|
| 167 |
+
def get_block_size(self):
|
| 168 |
+
return self.block_size
|
| 169 |
+
|
| 170 |
+
def _init_weights(self, module):
|
| 171 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
| 172 |
+
module.weight.data.normal_(mean=0.0, std=0.02)
|
| 173 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 174 |
+
module.bias.data.zero_()
|
| 175 |
+
elif isinstance(module, nn.LayerNorm):
|
| 176 |
+
module.bias.data.zero_()
|
| 177 |
+
module.weight.data.fill_(1.0)
|
| 178 |
+
|
| 179 |
+
def forward(self, idx, clip_feature):
|
| 180 |
+
if len(idx) == 0:
|
| 181 |
+
token_embeddings = self.cond_emb(clip_feature).unsqueeze(1)
|
| 182 |
+
else:
|
| 183 |
+
b, t = idx.size()
|
| 184 |
+
assert t <= self.block_size, "Cannot forward, model block size is exhausted."
|
| 185 |
+
# forward the Trans model
|
| 186 |
+
token_embeddings = self.tok_emb(idx)
|
| 187 |
+
# clip_feature.dtype = token_embeddings.dtype
|
| 188 |
+
token_embeddings = torch.cat([self.cond_emb(clip_feature.to(torch.float32)).unsqueeze(1), token_embeddings], dim=1)
|
| 189 |
+
|
| 190 |
+
x = self.pos_embed(token_embeddings)
|
| 191 |
+
x = self.blocks(x)
|
| 192 |
+
|
| 193 |
+
return x
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class CrossCondTransHead(nn.Module):
|
| 199 |
+
|
| 200 |
+
def __init__(self,
|
| 201 |
+
num_vq=1024,
|
| 202 |
+
embed_dim=512,
|
| 203 |
+
block_size=16,
|
| 204 |
+
num_layers=2,
|
| 205 |
+
n_head=8,
|
| 206 |
+
drop_out_rate=0.1,
|
| 207 |
+
fc_rate=4):
|
| 208 |
+
super().__init__()
|
| 209 |
+
|
| 210 |
+
self.blocks = nn.Sequential(*[Block(embed_dim, block_size, n_head, drop_out_rate, fc_rate,num=_) for _ in range(num_layers)])
|
| 211 |
+
self.ln_f = nn.LayerNorm(embed_dim)
|
| 212 |
+
self.head = nn.Linear(embed_dim, num_vq + 1, bias=False)
|
| 213 |
+
self.block_size = block_size
|
| 214 |
+
|
| 215 |
+
self.apply(self._init_weights)
|
| 216 |
+
|
| 217 |
+
def get_block_size(self):
|
| 218 |
+
return self.block_size
|
| 219 |
+
|
| 220 |
+
def _init_weights(self, module):
|
| 221 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
| 222 |
+
module.weight.data.normal_(mean=0.0, std=0.02)
|
| 223 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 224 |
+
module.bias.data.zero_()
|
| 225 |
+
elif isinstance(module, nn.LayerNorm):
|
| 226 |
+
module.bias.data.zero_()
|
| 227 |
+
module.weight.data.fill_(1.0)
|
| 228 |
+
|
| 229 |
+
def forward(self, x):
|
| 230 |
+
x = self.blocks(x)
|
| 231 |
+
x = self.ln_f(x)
|
| 232 |
+
logits = self.head(x)
|
| 233 |
+
return logits
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
|
models/vqvae.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
from models.encdec import Encoder, Decoder
|
| 3 |
+
from models.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 |
+
|